Example usage for javax.naming.ldap LdapName size

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

Introduction

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

Prototype

public int size() 

Source Link

Document

Retrieves the number of components in this LDAP name.

Usage

From source file:com.evolveum.midpoint.model.common.expression.functions.BasicExpressionFunctions.java

public String determineLdapSingleAttributeValue(String dn, String attributeName, Collection<?> values)
        throws NamingException {
    if (values == null || values.isEmpty()) {
        return null;
    }//from ww w  .  j  ava2  s.c  om

    Collection<String> stringValues = null;
    // Determine item type, try to convert to strings
    Object firstElement = values.iterator().next();
    if (firstElement instanceof String) {
        stringValues = (Collection) values;
    } else if (firstElement instanceof Element) {
        stringValues = new ArrayList<String>(values.size());
        for (Object value : values) {
            Element element = (Element) value;
            stringValues.add(element.getTextContent());
        }
    } else {
        throw new IllegalArgumentException("Unexpected value type " + firstElement.getClass());
    }

    if (stringValues.size() == 1) {
        return stringValues.iterator().next();
    }

    if (StringUtils.isBlank(dn)) {
        throw new IllegalArgumentException(
                "No dn argument specified, cannot determine which of " + values.size() + " values to use");
    }

    LdapName parsedDn = new LdapName(dn);
    for (int i = 0; i < parsedDn.size(); i++) {
        Rdn rdn = parsedDn.getRdn(i);
        Attributes rdnAttributes = rdn.toAttributes();
        NamingEnumeration<String> rdnIDs = rdnAttributes.getIDs();
        while (rdnIDs.hasMore()) {
            String rdnID = rdnIDs.next();
            Attribute attribute = rdnAttributes.get(rdnID);
            if (attributeName.equals(attribute.getID())) {
                for (int j = 0; j < attribute.size(); j++) {
                    Object value = attribute.get(j);
                    if (stringValues.contains(value)) {
                        return (String) value;
                    }
                }
            }
        }
    }

    // Fallback. No values in DN. Just return the first alphabetically-wise value.
    return Collections.min(stringValues);
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

protected Collection<String> lookupGroupChildren(final SearchResult searchResult, final String gid,
        final boolean disjoint, final LdapName groupDistinguishedNamePrefix,
        final LdapName userDistinguishedNamePrefix) throws NamingException {
    final InitialDirContext ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext();
    try {//from ww  w.ja  va2 s .com
        LOGGER.debug("Processing group: {}, from source: {}", gid, searchResult.getNameInNamespace());

        final Collection<String> children = new HashSet<>();

        final Attributes attributes = searchResult.getAttributes();
        Attribute memAttribute = this.getRangeRestrictedAttribute(attributes, this.memberAttributeName);
        int nextStart = this.attributeBatchSize;

        while (memAttribute != null) {
            for (int i = 0; i < memAttribute.size(); i++) {
                final String attribute = (String) memAttribute.get(i);
                if (attribute != null && attribute.length() > 0) {
                    try {
                        // Attempt to parse the member attribute as a DN. If this fails we have a fallback
                        // in the catch block
                        final LdapName distinguishedNameForComparison = fixedLdapName(
                                attribute.toLowerCase(Locale.ENGLISH));
                        Attribute nameAttribute;

                        // If the user and group search bases are different we may be able to recognize user
                        // and group DNs without a secondary lookup
                        if (disjoint) {
                            final LdapName distinguishedName = fixedLdapName(attribute);
                            final Attributes nameAttributes = distinguishedName
                                    .getRdn(distinguishedName.size() - 1).toAttributes();

                            // Recognize user DNs
                            if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix)
                                    && (nameAttribute = nameAttributes.get(this.userIdAttributeName)) != null) {
                                final Collection<String> attributeValues = this.mapAttribute(nameAttribute,
                                        String.class);
                                final String personName = attributeValues.iterator().next();
                                LOGGER.debug("User DN recognized: {}", personName);
                                children.add(personName);
                                continue;
                            }

                            // Recognize group DNs
                            if (distinguishedNameForComparison.startsWith(groupDistinguishedNamePrefix)
                                    && (nameAttribute = nameAttributes
                                            .get(this.groupIdAttributeName)) != null) {
                                final Collection<String> attributeValues = this.mapAttribute(nameAttribute,
                                        String.class);
                                final String groupName = attributeValues.iterator().next();
                                LOGGER.debug("Group DN recognized: {}{}", AuthorityType.GROUP.getPrefixString(),
                                        groupName);
                                children.add(AuthorityType.GROUP.getPrefixString() + groupName);
                                continue;
                            }
                        }

                        // If we can't determine the name and type from the DN alone, try a directory lookup
                        if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix)
                                || distinguishedNameForComparison.startsWith(groupDistinguishedNamePrefix)) {
                            try {
                                final Attributes childAttributes = ctx.getAttributes(jndiName(attribute),
                                        new String[] { "objectclass", this.groupIdAttributeName,
                                                this.userIdAttributeName });
                                final Attribute objectClass = childAttributes.get("objectclass");
                                if (this.hasAttributeValue(objectClass, this.personType)) {
                                    nameAttribute = childAttributes.get(this.userIdAttributeName);
                                    if (nameAttribute == null) {
                                        if (this.errorOnMissingUID) {
                                            throw new AlfrescoRuntimeException(
                                                    "User missing user id attribute DN =" + attribute
                                                            + "  att = " + this.userIdAttributeName);
                                        } else {
                                            LOGGER.warn("User missing user id attribute DN =" + attribute
                                                    + "  att = " + this.userIdAttributeName);
                                            continue;
                                        }
                                    }

                                    final Collection<String> attributeValues = this.mapAttribute(nameAttribute,
                                            String.class);
                                    final String personName = attributeValues.iterator().next();

                                    LOGGER.debug("User DN recognized by directory lookup: {}", personName);
                                    children.add(personName);
                                    continue;
                                } else if (this.hasAttributeValue(objectClass, this.groupType)) {
                                    nameAttribute = childAttributes.get(this.groupIdAttributeName);
                                    if (nameAttribute == null) {
                                        if (this.errorOnMissingGID) {
                                            final Object[] params = { searchResult.getNameInNamespace(),
                                                    this.groupIdAttributeName };
                                            throw new AlfrescoRuntimeException(
                                                    "synchronization.err.ldap.get.group.id.missing", params);
                                        } else {
                                            LOGGER.warn("Missing GID on {}", childAttributes);
                                            continue;
                                        }
                                    }

                                    final Collection<String> attributeValues = this.mapAttribute(nameAttribute,
                                            String.class);
                                    final String groupName = attributeValues.iterator().next();
                                    LOGGER.debug("Group DN recognized by directory lookup: {}{}",
                                            AuthorityType.GROUP.getPrefixString(), groupName);
                                    children.add(AuthorityType.GROUP.getPrefixString() + groupName);
                                    continue;
                                }
                            } catch (final NamingException e) {
                                // Unresolvable name
                                if (this.errorOnMissingMembers) {
                                    final Object[] params = { gid, attribute, e.getLocalizedMessage() };
                                    throw new AlfrescoRuntimeException(
                                            "synchronization.err.ldap.group.member.missing.exception", params,
                                            e);
                                }
                                LOGGER.warn(
                                        "Failed to resolve member of group '{}, ' with distinguished name: {}",
                                        gid, attribute, e);
                                continue;
                            }
                        }
                        if (this.errorOnMissingMembers) {
                            final Object[] params = { gid, attribute };
                            throw new AlfrescoRuntimeException("synchronization.err.ldap.group.member.missing",
                                    params);
                        }
                        LOGGER.warn("Failed to resolve member of group '{}' with distinguished name: {}", gid,
                                attribute);
                    } catch (final InvalidNameException e) {
                        // The member attribute didn't parse as a DN. So assume we have a group class like
                        // posixGroup (FDS) that directly lists user names
                        LOGGER.debug("Member DN recognized as posixGroup: {}", attribute);
                        children.add(attribute);
                    }
                }
            }

            // If we are using attribute matching and we haven't got to the end (indicated by an asterisk),
            // fetch the next batch
            if (nextStart > 0
                    && !PATTERN_RANGE_END.matcher(memAttribute.getID().toLowerCase(Locale.ENGLISH)).find()) {
                final Attributes childAttributes = ctx.getAttributes(
                        jndiName(searchResult.getNameInNamespace()), new String[] { this.memberAttributeName
                                + ";range=" + nextStart + '-' + (nextStart + this.attributeBatchSize - 1) });
                memAttribute = this.getRangeRestrictedAttribute(childAttributes, this.memberAttributeName);
                nextStart += this.attributeBatchSize;
            } else {
                memAttribute = null;
            }
        }

        return children;
    } finally {
        this.commonAfterQueryCleanup(null, null, ctx);
    }
}

From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

public Collection<NodeDescription> getGroups(Date modifiedSince) {
    // Work out whether the user and group trees are disjoint. This may allow us to optimize reverse DN
    // resolution.
    final Set<LdapName> groupDistinguishedNamePrefixes = new LinkedHashSet<>();
    for (String groupSearchBase : this.groupSearchBases) {
        try {//from  w  ww  .  ja  v  a  2s .  c o  m
            final LdapName groupDistinguishedNamePrefix = fixedLdapName(groupSearchBase.toLowerCase());
            groupDistinguishedNamePrefixes.add(groupDistinguishedNamePrefix);
        } catch (InvalidNameException e) {
            Object[] params = { groupSearchBase.toLowerCase(), e.getLocalizedMessage() };
            throw new AlfrescoRuntimeException("synchronization.err.ldap.search.base.invalid", params, e);
        }
    }
    final Set<LdapName> userDistinguishedNamePrefixes = new LinkedHashSet<>();
    for (String userSearchBase : this.userSearchBases) {
        try {
            final LdapName userDistinguishedNamePrefix = fixedLdapName(userSearchBase.toLowerCase());
            userDistinguishedNamePrefixes.add(userDistinguishedNamePrefix);
        } catch (InvalidNameException e) {
            Object[] params = { userSearchBase.toLowerCase(), e.getLocalizedMessage() };
            throw new AlfrescoRuntimeException("synchronization.err.ldap.search.base.invalid", params, e);
        }
    }

    final Set<LdapName> distinctGroupDNPrefixes = new LinkedHashSet<>(groupDistinguishedNamePrefixes);
    final Set<LdapName> distinctUserDNPrefixes = new LinkedHashSet<>(userDistinguishedNamePrefixes);
    removeCommonPrefixedNamesFromSets(distinctGroupDNPrefixes, distinctUserDNPrefixes);

    // If there exist either distinct user DNs or group DNs, then the
    // sets are disjoint, and we may be able to recognize user or group
    // DNs without secondary lookup
    final boolean disjoint = !distinctUserDNPrefixes.isEmpty() || !distinctGroupDNPrefixes.isEmpty();

    if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) {
        if (disjoint) {
            LDAPMultiBaseUserRegistry.logger.debug("Distinct user " + "DN prefixes: " + distinctUserDNPrefixes);
            LDAPMultiBaseUserRegistry.logger
                    .debug("Distinct group " + "DN prefixes: " + distinctGroupDNPrefixes);
        }
    }

    // Choose / generate the query
    String query;
    if (modifiedSince == null) {
        query = this.groupQuery;
    } else {
        query = MessageFormat.format(this.groupDifferentialQuery, this.timestampFormat.format(modifiedSince));
    }

    // Run the query and process the results
    final Map<String, NodeDescription> lookup = new TreeMap<String, NodeDescription>();
    processQuery(new SearchCallback() {
        // We get a whole new context to avoid interference with cookies from paged results
        private DirContext ctx = LDAPMultiBaseUserRegistry.this.ldapInitialContextFactory
                .getDefaultIntialDirContext();

        public void process(SearchResult result) throws NamingException, ParseException {
            Attributes attributes = result.getAttributes();
            Attribute gidAttribute = attributes.get(LDAPMultiBaseUserRegistry.this.groupIdAttributeName);
            if (gidAttribute == null) {
                if (LDAPMultiBaseUserRegistry.this.errorOnMissingGID) {
                    Object[] params = { result.getNameInNamespace(),
                            LDAPMultiBaseUserRegistry.this.groupIdAttributeName };
                    throw new AlfrescoRuntimeException("synchronization.err.ldap.get.group.id.missing", params);
                } else {
                    LDAPMultiBaseUserRegistry.logger.warn("Missing GID on " + attributes);
                    return;
                }
            }
            String groupShortName = gidAttribute.get(0).toString();
            String gid = "GROUP_" + groupShortName;

            NodeDescription group = lookup.get(gid);
            if (group == null) {
                // Apply the mapped properties to the node description
                group = mapToNode(LDAPMultiBaseUserRegistry.this.groupAttributeMapping,
                        LDAPMultiBaseUserRegistry.this.groupAttributeDefaults, result);

                // Make sure the "GROUP_" prefix is applied
                group.getProperties().put(ContentModel.PROP_AUTHORITY_NAME, gid);
                lookup.put(gid, group);
            } else if (LDAPMultiBaseUserRegistry.this.errorOnDuplicateGID) {
                throw new AlfrescoRuntimeException("Duplicate group id found for " + gid);
            } else {
                LDAPMultiBaseUserRegistry.logger
                        .warn("Duplicate gid found for " + gid + " -> merging definitions");
            }

            Set<String> childAssocs = group.getChildAssociations();

            // Get the repeating (and possibly range restricted) member attribute
            Attribute memAttribute = getRangeRestrictedAttribute(attributes,
                    LDAPMultiBaseUserRegistry.this.memberAttributeName);
            int nextStart = LDAPMultiBaseUserRegistry.this.attributeBatchSize;
            if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) {
                LDAPMultiBaseUserRegistry.logger
                        .debug("Processing group: " + gid + ", from source: " + group.getSourceId());
            }
            // Loop until we get to the end of the range
            while (memAttribute != null) {
                for (int i = 0; i < memAttribute.size(); i++) {
                    String attribute = (String) memAttribute.get(i);
                    if (attribute != null && attribute.length() > 0) {
                        try {
                            // Attempt to parse the member attribute as a DN. If this fails we have a fallback
                            // in the catch block
                            LdapName distinguishedNameForComparison = fixedLdapName(attribute.toLowerCase());
                            Attribute nameAttribute;

                            // If the user and group search bases are different we may be able to recognize user
                            // and group DNs without a secondary lookup
                            if (disjoint) {
                                LdapName distinguishedName = fixedLdapName(attribute);
                                Attributes nameAttributes = distinguishedName
                                        .getRdn(distinguishedName.size() - 1).toAttributes();

                                // Recognize user DNs
                                if (nameStartsWithNameInSet(distinguishedNameForComparison,
                                        distinctUserDNPrefixes)
                                        && (nameAttribute = nameAttributes.get(
                                                LDAPMultiBaseUserRegistry.this.userIdAttributeName)) != null) {
                                    if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) {
                                        LDAPMultiBaseUserRegistry.logger
                                                .debug("User DN recognized: " + nameAttribute.get());
                                    }
                                    childAssocs.add((String) nameAttribute.get());
                                    continue;
                                }

                                // Recognize group DNs
                                if (nameStartsWithNameInSet(distinguishedNameForComparison,
                                        distinctGroupDNPrefixes)
                                        && (nameAttribute = nameAttributes.get(
                                                LDAPMultiBaseUserRegistry.this.groupIdAttributeName)) != null) {
                                    if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) {
                                        LDAPMultiBaseUserRegistry.logger.debug(
                                                "Group DN recognized: " + "GROUP_" + nameAttribute.get());
                                    }
                                    childAssocs.add("GROUP_" + nameAttribute.get());
                                    continue;
                                }
                            }

                            // If we can't determine the name and type from the DN alone, try a directory lookup
                            if (nameStartsWithNameInSet(distinguishedNameForComparison,
                                    userDistinguishedNamePrefixes)
                                    || nameStartsWithNameInSet(distinguishedNameForComparison,
                                            groupDistinguishedNamePrefixes)) {
                                try {
                                    Attributes childAttributes = this.ctx.getAttributes(jndiName(attribute),
                                            new String[] { "objectclass",
                                                    LDAPMultiBaseUserRegistry.this.groupIdAttributeName,
                                                    LDAPMultiBaseUserRegistry.this.userIdAttributeName });
                                    Attribute objectClass = childAttributes.get("objectclass");
                                    if (hasAttributeValue(objectClass,
                                            LDAPMultiBaseUserRegistry.this.personType)) {
                                        nameAttribute = childAttributes
                                                .get(LDAPMultiBaseUserRegistry.this.userIdAttributeName);
                                        if (nameAttribute == null) {
                                            if (LDAPMultiBaseUserRegistry.this.errorOnMissingUID) {
                                                throw new AlfrescoRuntimeException(
                                                        "User missing user id attribute DN =" + attribute
                                                                + "  att = "
                                                                + LDAPMultiBaseUserRegistry.this.userIdAttributeName);
                                            } else {
                                                LDAPMultiBaseUserRegistry.logger
                                                        .warn("User missing user id attribute DN =" + attribute
                                                                + "  att = "
                                                                + LDAPMultiBaseUserRegistry.this.userIdAttributeName);
                                                continue;
                                            }
                                        }
                                        if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) {
                                            LDAPMultiBaseUserRegistry.logger
                                                    .debug("User DN recognized by directory lookup: "
                                                            + nameAttribute.get());
                                        }
                                        childAssocs.add((String) nameAttribute.get());
                                        continue;
                                    } else if (hasAttributeValue(objectClass,
                                            LDAPMultiBaseUserRegistry.this.groupType)) {
                                        nameAttribute = childAttributes
                                                .get(LDAPMultiBaseUserRegistry.this.groupIdAttributeName);
                                        if (nameAttribute == null) {
                                            if (LDAPMultiBaseUserRegistry.this.errorOnMissingGID) {
                                                Object[] params = { result.getNameInNamespace(),
                                                        LDAPMultiBaseUserRegistry.this.groupIdAttributeName };
                                                throw new AlfrescoRuntimeException(
                                                        "synchronization.err.ldap.get.group.id.missing",
                                                        params);
                                            } else {
                                                LDAPMultiBaseUserRegistry.logger
                                                        .warn("Missing GID on " + childAttributes);
                                                continue;
                                            }
                                        }
                                        if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) {
                                            LDAPMultiBaseUserRegistry.logger
                                                    .debug("Group DN recognized by directory lookup: "
                                                            + "GROUP_" + nameAttribute.get());
                                        }
                                        childAssocs.add("GROUP_" + nameAttribute.get());
                                        continue;
                                    }
                                } catch (NamingException e) {
                                    // Unresolvable name
                                    if (LDAPMultiBaseUserRegistry.this.errorOnMissingMembers) {
                                        Object[] params = { groupShortName, attribute,
                                                e.getLocalizedMessage() };
                                        throw new AlfrescoRuntimeException(
                                                "synchronization.err.ldap.group.member.missing.exception",
                                                params, e);
                                    }
                                    LDAPMultiBaseUserRegistry.logger.warn("Failed to resolve member of group '"
                                            + groupShortName + "' with distinguished name: " + attribute, e);
                                    continue;
                                }
                            }
                            if (LDAPMultiBaseUserRegistry.this.errorOnMissingMembers) {
                                Object[] params = { groupShortName, attribute };
                                throw new AlfrescoRuntimeException(
                                        "synchronization.err.ldap.group.member.missing", params);
                            }
                            LDAPMultiBaseUserRegistry.logger.warn("Failed to resolve member of group '"
                                    + groupShortName + "' with distinguished name: " + attribute);
                        } catch (InvalidNameException e) {
                            // The member attribute didn't parse as a DN. So assume we have a group class like
                            // posixGroup (FDS) that directly lists user names
                            if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) {
                                LDAPMultiBaseUserRegistry.logger
                                        .debug("Member DN recognized as posixGroup: " + attribute);
                            }
                            childAssocs.add(attribute);
                        }
                    }
                }

                // If we are using attribute matching and we haven't got to the end (indicated by an asterisk),
                // fetch the next batch
                if (nextStart > 0 && !LDAPMultiBaseUserRegistry.PATTERN_RANGE_END
                        .matcher(memAttribute.getID().toLowerCase()).find()) {
                    Attributes childAttributes = this.ctx.getAttributes(jndiName(result.getNameInNamespace()),
                            new String[] { LDAPMultiBaseUserRegistry.this.memberAttributeName + ";range="
                                    + nextStart + '-'
                                    + (nextStart + LDAPMultiBaseUserRegistry.this.attributeBatchSize - 1) });
                    memAttribute = getRangeRestrictedAttribute(childAttributes,
                            LDAPMultiBaseUserRegistry.this.memberAttributeName);
                    nextStart += LDAPMultiBaseUserRegistry.this.attributeBatchSize;
                } else {
                    memAttribute = null;
                }
            }
        }

        public void close() throws NamingException {
            this.ctx.close();
        }
    }, this.groupSearchBases, query, this.groupKeys.getFirst());

    if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) {
        LDAPMultiBaseUserRegistry.logger.debug("Found " + lookup.size());
    }

    return lookup.values();
}

From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java

public Collection<NodeDescription> getGroups(Date modifiedSince) {
    // Work out whether the user and group trees are disjoint. This may allow us to optimize reverse DN
    // resolution.
    final LdapName groupDistinguishedNamePrefix;
    try {/*  ww w  .  jav a2 s  .co  m*/
        groupDistinguishedNamePrefix = fixedLdapName(this.groupSearchBase.toLowerCase());
    } catch (InvalidNameException e) {
        Object[] params = { this.groupSearchBase.toLowerCase(), e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search.base.invalid", params, e);
    }
    final LdapName userDistinguishedNamePrefix;
    try {
        userDistinguishedNamePrefix = fixedLdapName(this.userSearchBase.toLowerCase());
    } catch (InvalidNameException e) {
        Object[] params = { this.userSearchBase.toLowerCase(), e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search.base.invalid", params, e);
    }

    final boolean disjoint = !groupDistinguishedNamePrefix.startsWith(userDistinguishedNamePrefix)
            && !userDistinguishedNamePrefix.startsWith(groupDistinguishedNamePrefix);

    // Choose / generate the query
    String query;
    if (modifiedSince == null) {
        query = this.groupQuery;
    } else {
        query = MessageFormat.format(this.groupDifferentialQuery, this.timestampFormat.format(modifiedSince));
    }

    // Run the query and process the results
    final Map<String, NodeDescription> lookup = new TreeMap<String, NodeDescription>();
    processQuery(new AbstractSearchCallback() {
        // We get a whole new context to avoid interference with cookies from paged results
        private DirContext ctx = LDAPUserRegistry.this.ldapInitialContextFactory.getDefaultIntialDirContext();

        protected void doProcess(SearchResult result) throws NamingException, ParseException {
            Attributes attributes = result.getAttributes();
            Attribute gidAttribute = attributes.get(LDAPUserRegistry.this.groupIdAttributeName);
            if (gidAttribute == null) {
                if (LDAPUserRegistry.this.errorOnMissingGID) {
                    Object[] params = { result.getNameInNamespace(),
                            LDAPUserRegistry.this.groupIdAttributeName };
                    throw new AlfrescoRuntimeException("synchronization.err.ldap.get.group.id.missing", params);
                } else {
                    LDAPUserRegistry.logger.warn("Missing GID on " + attributes);
                    return;
                }
            }
            String groupShortName = gidAttribute.get(0).toString();
            String gid = "GROUP_" + groupShortName;

            NodeDescription group = lookup.get(gid);
            if (group == null) {
                // Apply the mapped properties to the node description
                group = mapToNode(LDAPUserRegistry.this.groupAttributeMapping,
                        LDAPUserRegistry.this.groupAttributeDefaults, result);

                // Make sure the "GROUP_" prefix is applied
                group.getProperties().put(ContentModel.PROP_AUTHORITY_NAME, gid);
                lookup.put(gid, group);
            } else if (LDAPUserRegistry.this.errorOnDuplicateGID) {
                throw new AlfrescoRuntimeException("Duplicate group id found for " + gid);
            } else {
                LDAPUserRegistry.logger.warn("Duplicate gid found for " + gid + " -> merging definitions");
            }

            Set<String> childAssocs = group.getChildAssociations();

            // Get the repeating (and possibly range restricted) member attribute
            Attribute memAttribute = getRangeRestrictedAttribute(attributes,
                    LDAPUserRegistry.this.memberAttributeName);
            int nextStart = LDAPUserRegistry.this.attributeBatchSize;
            if (LDAPUserRegistry.logger.isDebugEnabled()) {
                LDAPUserRegistry.logger
                        .debug("Processing group: " + gid + ", from source: " + group.getSourceId());
            }
            // Loop until we get to the end of the range
            while (memAttribute != null) {
                for (int i = 0; i < memAttribute.size(); i++) {
                    String attribute = (String) memAttribute.get(i);
                    if (attribute != null && attribute.length() > 0) {
                        try {
                            // Attempt to parse the member attribute as a DN. If this fails we have a fallback
                            // in the catch block
                            LdapName distinguishedNameForComparison = fixedLdapName(attribute.toLowerCase());
                            Attribute nameAttribute;

                            // If the user and group search bases are different we may be able to recognize user
                            // and group DNs without a secondary lookup
                            if (disjoint) {
                                LdapName distinguishedName = fixedLdapName(attribute);
                                Attributes nameAttributes = distinguishedName
                                        .getRdn(distinguishedName.size() - 1).toAttributes();

                                // Recognize user DNs
                                if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix)
                                        && (nameAttribute = nameAttributes
                                                .get(LDAPUserRegistry.this.userIdAttributeName)) != null) {
                                    if (LDAPUserRegistry.logger.isDebugEnabled()) {
                                        LDAPUserRegistry.logger
                                                .debug("User DN recognized: " + nameAttribute.get());
                                    }
                                    childAssocs.add((String) nameAttribute.get());
                                    continue;
                                }

                                // Recognize group DNs
                                if (distinguishedNameForComparison.startsWith(groupDistinguishedNamePrefix)
                                        && (nameAttribute = nameAttributes
                                                .get(LDAPUserRegistry.this.groupIdAttributeName)) != null) {
                                    if (LDAPUserRegistry.logger.isDebugEnabled()) {
                                        LDAPUserRegistry.logger.debug(
                                                "Group DN recognized: " + "GROUP_" + nameAttribute.get());
                                    }
                                    childAssocs.add("GROUP_" + nameAttribute.get());
                                    continue;
                                }
                            }

                            // If we can't determine the name and type from the DN alone, try a directory lookup
                            if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix)
                                    || distinguishedNameForComparison
                                            .startsWith(groupDistinguishedNamePrefix)) {
                                try {
                                    Attributes childAttributes = this.ctx.getAttributes(jndiName(attribute),
                                            new String[] { "objectclass",
                                                    LDAPUserRegistry.this.groupIdAttributeName,
                                                    LDAPUserRegistry.this.userIdAttributeName });
                                    Attribute objectClass = childAttributes.get("objectclass");
                                    if (hasAttributeValue(objectClass, LDAPUserRegistry.this.personType)) {
                                        nameAttribute = childAttributes
                                                .get(LDAPUserRegistry.this.userIdAttributeName);
                                        if (nameAttribute == null) {
                                            if (LDAPUserRegistry.this.errorOnMissingUID) {
                                                throw new AlfrescoRuntimeException(
                                                        "User missing user id attribute DN =" + attribute
                                                                + "  att = "
                                                                + LDAPUserRegistry.this.userIdAttributeName);
                                            } else {
                                                LDAPUserRegistry.logger
                                                        .warn("User missing user id attribute DN =" + attribute
                                                                + "  att = "
                                                                + LDAPUserRegistry.this.userIdAttributeName);
                                                continue;
                                            }
                                        }
                                        if (LDAPUserRegistry.logger.isDebugEnabled()) {
                                            LDAPUserRegistry.logger
                                                    .debug("User DN recognized by directory lookup: "
                                                            + nameAttribute.get());
                                        }
                                        childAssocs.add((String) nameAttribute.get());
                                        continue;
                                    } else if (hasAttributeValue(objectClass,
                                            LDAPUserRegistry.this.groupType)) {
                                        nameAttribute = childAttributes
                                                .get(LDAPUserRegistry.this.groupIdAttributeName);
                                        if (nameAttribute == null) {
                                            if (LDAPUserRegistry.this.errorOnMissingGID) {
                                                Object[] params = { result.getNameInNamespace(),
                                                        LDAPUserRegistry.this.groupIdAttributeName };
                                                throw new AlfrescoRuntimeException(
                                                        "synchronization.err.ldap.get.group.id.missing",
                                                        params);
                                            } else {
                                                LDAPUserRegistry.logger
                                                        .warn("Missing GID on " + childAttributes);
                                                continue;
                                            }
                                        }
                                        if (LDAPUserRegistry.logger.isDebugEnabled()) {
                                            LDAPUserRegistry.logger
                                                    .debug("Group DN recognized by directory lookup: "
                                                            + "GROUP_" + nameAttribute.get());
                                        }
                                        childAssocs.add("GROUP_" + nameAttribute.get());
                                        continue;
                                    }
                                } catch (NamingException e) {
                                    // Unresolvable name
                                    if (LDAPUserRegistry.this.errorOnMissingMembers) {
                                        Object[] params = { groupShortName, attribute,
                                                e.getLocalizedMessage() };
                                        throw new AlfrescoRuntimeException(
                                                "synchronization.err.ldap.group.member.missing.exception",
                                                params, e);
                                    }
                                    LDAPUserRegistry.logger.warn("Failed to resolve member of group '"
                                            + groupShortName + "' with distinguished name: " + attribute, e);
                                    continue;
                                }
                            }
                            if (LDAPUserRegistry.this.errorOnMissingMembers) {
                                Object[] params = { groupShortName, attribute };
                                throw new AlfrescoRuntimeException(
                                        "synchronization.err.ldap.group.member.missing", params);
                            }
                            LDAPUserRegistry.logger.warn("Failed to resolve member of group '" + groupShortName
                                    + "' with distinguished name: " + attribute);
                        } catch (InvalidNameException e) {
                            // The member attribute didn't parse as a DN. So assume we have a group class like
                            // posixGroup (FDS) that directly lists user names
                            if (LDAPUserRegistry.logger.isDebugEnabled()) {
                                LDAPUserRegistry.logger
                                        .debug("Member DN recognized as posixGroup: " + attribute);
                            }
                            childAssocs.add(attribute);
                        }
                    }
                }

                // If we are using attribute matching and we haven't got to the end (indicated by an asterisk),
                // fetch the next batch
                if (nextStart > 0 && !LDAPUserRegistry.PATTERN_RANGE_END
                        .matcher(memAttribute.getID().toLowerCase()).find()) {
                    Attributes childAttributes = this.ctx.getAttributes(jndiName(result.getNameInNamespace()),
                            new String[] { LDAPUserRegistry.this.memberAttributeName + ";range=" + nextStart
                                    + '-' + (nextStart + LDAPUserRegistry.this.attributeBatchSize - 1) });
                    memAttribute = getRangeRestrictedAttribute(childAttributes,
                            LDAPUserRegistry.this.memberAttributeName);
                    nextStart += LDAPUserRegistry.this.attributeBatchSize;
                } else {
                    memAttribute = null;
                }
            }
        }

        public void close() throws NamingException {
            this.ctx.close();
        }
    }, this.groupSearchBase, query, this.groupKeys.getFirst());

    if (LDAPUserRegistry.logger.isDebugEnabled()) {
        LDAPUserRegistry.logger.debug("Found " + lookup.size());
    }

    return lookup.values();
}

From source file:org.apache.zeppelin.realm.LdapRealm.java

boolean isUserMemberOfDynamicGroup(LdapName userLdapDn, String memberUrl,
        final LdapContextFactory ldapContextFactory) throws NamingException {
    // ldap://host:port/dn?attributes?scope?filter?extensions
    if (memberUrl == null) {
        return false;
    }/*from w w w.  j  a  v a 2  s.co m*/
    String[] tokens = memberUrl.split("\\?");
    if (tokens.length < 4) {
        return false;
    }

    String searchBaseString = tokens[0].substring(tokens[0].lastIndexOf("/") + 1);
    String searchScope = tokens[2];
    String searchFilter = tokens[3];

    LdapName searchBaseDn = new LdapName(searchBaseString);

    // do scope test
    if (searchScope.equalsIgnoreCase("base")) {
        log.debug("DynamicGroup SearchScope base");
        return false;
    }
    if (!userLdapDn.toString().endsWith(searchBaseDn.toString())) {
        return false;
    }
    if (searchScope.equalsIgnoreCase("one") && (userLdapDn.size() != searchBaseDn.size() - 1)) {
        log.debug("DynamicGroup SearchScope one");
        return false;
    }
    // search for the filter, substituting base with userDn
    // search for base_dn=userDn, scope=base, filter=filter
    LdapContext systemLdapCtx = null;
    systemLdapCtx = ldapContextFactory.getSystemLdapContext();
    boolean member = false;
    NamingEnumeration<SearchResult> searchResultEnum = null;
    try {
        searchResultEnum = systemLdapCtx.search(userLdapDn, searchFilter,
                searchScope.equalsIgnoreCase("sub") ? SUBTREE_SCOPE : ONELEVEL_SCOPE);
        if (searchResultEnum.hasMore()) {
            return true;
        }
    } finally {
        try {
            if (searchResultEnum != null) {
                searchResultEnum.close();
            }
        } finally {
            LdapUtils.closeContext(systemLdapCtx);
        }
    }
    return member;
}

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

/**
 * This method escapes the special characters in a LdapName according to the ldap filter escaping standards.
 *
 * @param ldn LDAP name//from www  .  j ava2s .c  om
 * @return A String which special characters are escaped
 */
private String escapeLdapNameForFilter(LdapName ldn) {
    if (ldn == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Received null value to escape special characters. Returning null");
        }
        return null;
    }

    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 = escapedDN.append(",");
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Escaped DN value for filter : " + escapedDN.toString());
    }
    return escapedDN.toString();
}

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

/**
 * This method escapes the special characters in a LdapName according to the ldap filter escaping standards.
 *
 * @param ldn LDAP name//from  w w  w. j  a  va 2 s.  co  m
 * @return A String which special characters are escaped
 */
private static String escapeLdapNameForFilter(LdapName ldn) {
    if (ldn == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Received null value to escape special characters. Returning null");
        }
        return null;
    }

    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 = escapedDN.append(",");
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Escaped DN value for filter : " + escapedDN.toString());
    }
    return escapedDN.toString();
}

From source file:org.cggh.repo.security.sync.ldap.LDAPUserRegistry.java

public Collection<NodeDescription> getGroups(Date modifiedSince) {
    // Work out whether the user and group trees are disjoint. This may allow us to optimize reverse DN
    // resolution.
    final LdapName groupDistinguishedNamePrefix;
    try {/*  w ww  . ja  va  2  s.c om*/
        groupDistinguishedNamePrefix = fixedLdapName(this.groupSearchBase.toLowerCase());
    } catch (InvalidNameException e) {
        Object[] params = { this.groupSearchBase.toLowerCase(), e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search.base.invalid", params, e);
    }
    final LdapName userDistinguishedNamePrefix;
    try {
        userDistinguishedNamePrefix = fixedLdapName(this.userSearchBase.toLowerCase());
    } catch (InvalidNameException e) {
        Object[] params = { this.userSearchBase.toLowerCase(), e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search.base.invalid", params, e);
    }

    final boolean disjoint = !groupDistinguishedNamePrefix.startsWith(userDistinguishedNamePrefix)
            && !userDistinguishedNamePrefix.startsWith(groupDistinguishedNamePrefix);

    // Choose / generate the query
    String query;
    if (modifiedSince == null) {
        query = this.groupQuery;
    } else {
        query = MessageFormat.format(this.groupDifferentialQuery, this.timestampFormat.format(modifiedSince));
    }

    // Run the query and process the results
    final Map<String, NodeDescription> lookup = new TreeMap<String, NodeDescription>();
    processQuery(new AbstractSearchCallback() {
        // We get a whole new context to avoid interference with cookies from paged results
        private DirContext ctx = LDAPUserRegistry.this.ldapInitialContextFactory.getDefaultIntialDirContext();

        protected void doProcess(SearchResult result) throws NamingException, ParseException {
            Attributes attributes = result.getAttributes();
            Attribute gidAttribute = attributes.get(LDAPUserRegistry.this.groupIdAttributeName);
            if (gidAttribute == null) {
                if (LDAPUserRegistry.this.errorOnMissingGID) {
                    Object[] params = { result.getNameInNamespace(),
                            LDAPUserRegistry.this.groupIdAttributeName };
                    throw new AlfrescoRuntimeException("synchronization.err.ldap.get.group.id.missing", params);
                } else {
                    LDAPUserRegistry.logger.warn(
                            "Missing GID2 on " + result.getNameInNamespace() + " attributes:" + attributes);
                    return;
                }
            }
            String groupShortName = gidAttribute.get(0).toString();
            String gid = "GROUP_" + groupShortName;

            NodeDescription group = lookup.get(gid);
            if (group == null) {
                // Apply the mapped properties to the node description
                group = mapToNode(LDAPUserRegistry.this.groupAttributeMapping,
                        LDAPUserRegistry.this.groupAttributeDefaults, result);

                // Make sure the "GROUP_" prefix is applied
                group.getProperties().put(ContentModel.PROP_AUTHORITY_NAME, gid);
                lookup.put(gid, group);
            } else if (LDAPUserRegistry.this.errorOnDuplicateGID) {
                throw new AlfrescoRuntimeException("Duplicate group id found for " + gid);
            } else {
                LDAPUserRegistry.logger.warn("Duplicate gid found for " + gid + " -> merging definitions");
            }

            Set<String> childAssocs = group.getChildAssociations();

            // Get the repeating (and possibly range restricted) member attribute
            Attribute memAttribute = getRangeRestrictedAttribute(attributes,
                    LDAPUserRegistry.this.memberAttributeName);
            int nextStart = LDAPUserRegistry.this.attributeBatchSize;
            if (LDAPUserRegistry.logger.isDebugEnabled()) {
                LDAPUserRegistry.logger
                        .debug("Processing group: " + gid + ", from source: " + group.getSourceId());
            }
            // Loop until we get to the end of the range
            while (memAttribute != null) {
                for (int i = 0; i < memAttribute.size(); i++) {
                    String attribute = (String) memAttribute.get(i);
                    if (attribute != null && attribute.length() > 0) {
                        try {
                            // Attempt to parse the member attribute as a DN. If this fails we have a fallback
                            // in the catch block
                            LdapName distinguishedNameForComparison = fixedLdapName(attribute.toLowerCase());
                            Attribute nameAttribute;

                            // If the user and group search bases are different we may be able to recognize user
                            // and group DNs without a secondary lookup
                            if (disjoint) {
                                LdapName distinguishedName = fixedLdapName(attribute);
                                Attributes nameAttributes = distinguishedName
                                        .getRdn(distinguishedName.size() - 1).toAttributes();

                                // Recognize user DNs
                                if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix)
                                        && (nameAttribute = nameAttributes
                                                .get(LDAPUserRegistry.this.userIdAttributeName)) != null) {
                                    if (LDAPUserRegistry.logger.isDebugEnabled()) {
                                        LDAPUserRegistry.logger
                                                .debug("User DN recognized: " + nameAttribute.get());
                                    }
                                    childAssocs.add((String) nameAttribute.get());
                                    continue;
                                }

                                // Recognize group DNs
                                if (distinguishedNameForComparison.startsWith(groupDistinguishedNamePrefix)
                                        && (nameAttribute = nameAttributes
                                                .get(LDAPUserRegistry.this.groupIdAttributeName)) != null) {
                                    if (LDAPUserRegistry.logger.isDebugEnabled()) {
                                        LDAPUserRegistry.logger.debug(
                                                "Group DN recognized: " + "GROUP_" + nameAttribute.get());
                                    }
                                    childAssocs.add("GROUP_" + nameAttribute.get());
                                    continue;
                                }
                            }

                            // If we can't determine the name and type from the DN alone, try a directory lookup
                            if (distinguishedNameForComparison.startsWith(userDistinguishedNamePrefix)
                                    || distinguishedNameForComparison
                                            .startsWith(groupDistinguishedNamePrefix)) {
                                try {
                                    Attributes childAttributes = this.ctx.getAttributes(jndiName(attribute),
                                            new String[] { "objectclass",
                                                    LDAPUserRegistry.this.groupIdAttributeName,
                                                    LDAPUserRegistry.this.userIdAttributeName });
                                    Attribute objectClass = childAttributes.get("objectclass");
                                    if (hasAttributeValue(objectClass, LDAPUserRegistry.this.personType)) {
                                        nameAttribute = childAttributes
                                                .get(LDAPUserRegistry.this.userIdAttributeName);
                                        if (nameAttribute == null) {
                                            if (LDAPUserRegistry.this.errorOnMissingUID) {
                                                throw new AlfrescoRuntimeException(
                                                        "User missing user id attribute DN =" + attribute
                                                                + "  att = "
                                                                + LDAPUserRegistry.this.userIdAttributeName);
                                            } else {
                                                LDAPUserRegistry.logger
                                                        .warn("User missing user id attribute DN =" + attribute
                                                                + "  att = "
                                                                + LDAPUserRegistry.this.userIdAttributeName);
                                                continue;
                                            }
                                        }
                                        if (LDAPUserRegistry.logger.isDebugEnabled()) {
                                            LDAPUserRegistry.logger
                                                    .debug("User DN recognized by directory lookup: "
                                                            + nameAttribute.get());
                                        }
                                        childAssocs.add((String) nameAttribute.get());
                                        continue;
                                    } else if (hasAttributeValue(objectClass,
                                            LDAPUserRegistry.this.groupType)) {
                                        nameAttribute = childAttributes
                                                .get(LDAPUserRegistry.this.groupIdAttributeName);
                                        if (nameAttribute == null) {
                                            if (LDAPUserRegistry.this.errorOnMissingGID) {
                                                Object[] params = { result.getNameInNamespace(),
                                                        LDAPUserRegistry.this.groupIdAttributeName };
                                                throw new AlfrescoRuntimeException(
                                                        "synchronization.err.ldap.get.group.id.missing",
                                                        params);
                                            } else {
                                                LDAPUserRegistry.logger.warn(
                                                        "Missing GID3 on " + distinguishedNameForComparison
                                                                + " attributes:" + childAttributes);
                                                continue;
                                            }
                                        }
                                        if (LDAPUserRegistry.logger.isDebugEnabled()) {
                                            LDAPUserRegistry.logger
                                                    .debug("Group DN recognized by directory lookup: "
                                                            + "GROUP_" + nameAttribute.get());
                                        }
                                        childAssocs.add("GROUP_" + nameAttribute.get());
                                        continue;
                                    }
                                } catch (NamingException e) {
                                    // Unresolvable name
                                    if (LDAPUserRegistry.this.errorOnMissingMembers) {
                                        Object[] params = { groupShortName, attribute,
                                                e.getLocalizedMessage() };
                                        throw new AlfrescoRuntimeException(
                                                "synchronization.err.ldap.group.member.missing.exception",
                                                params, e);
                                    }
                                    LDAPUserRegistry.logger.warn("Failed to resolve member of group '"
                                            + groupShortName + "' with distinguished name: " + attribute, e);
                                    continue;
                                }
                            }
                            if (LDAPUserRegistry.this.errorOnMissingMembers) {
                                Object[] params = { groupShortName, attribute };
                                throw new AlfrescoRuntimeException(
                                        "synchronization.err.ldap.group.member.missing", params);
                            }
                            LDAPUserRegistry.logger.warn("Failed to resolve member of group '" + groupShortName
                                    + "' with distinguished name: " + attribute);
                        } catch (InvalidNameException e) {
                            // The member attribute didn't parse as a DN. So assume we have a group class like
                            // posixGroup (FDS) that directly lists user names
                            if (LDAPUserRegistry.logger.isDebugEnabled()) {
                                LDAPUserRegistry.logger
                                        .debug("Member DN recognized as posixGroup: " + attribute);
                            }
                            childAssocs.add(attribute);
                        }
                    }
                }

                // If we are using attribute matching and we haven't got to the end (indicated by an asterisk),
                // fetch the next batch
                if (nextStart > 0 && !LDAPUserRegistry.PATTERN_RANGE_END
                        .matcher(memAttribute.getID().toLowerCase()).find()) {
                    Attributes childAttributes = this.ctx.getAttributes(jndiName(result.getNameInNamespace()),
                            new String[] { LDAPUserRegistry.this.memberAttributeName + ";range=" + nextStart
                                    + '-' + (nextStart + LDAPUserRegistry.this.attributeBatchSize - 1) });
                    memAttribute = getRangeRestrictedAttribute(childAttributes,
                            LDAPUserRegistry.this.memberAttributeName);
                    nextStart += LDAPUserRegistry.this.attributeBatchSize;
                } else {
                    memAttribute = null;
                }
            }
        }

        public void close() throws NamingException {
            this.ctx.close();
        }
    }, this.groupSearchBase, query, this.groupKeys.getFirst());

    if (LDAPUserRegistry.logger.isDebugEnabled()) {
        LDAPUserRegistry.logger.debug("Found " + lookup.size());
    }

    return lookup.values();
}

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);
            }/* ww w  .j a v  a  2s.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 ww  .  j  a  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();
}