Example usage for javax.naming.ldap LdapName startsWith

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

Introduction

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

Prototype

public boolean startsWith(List<Rdn> rdns) 

Source Link

Document

Determines whether the specified RDN sequence forms a prefix of this LDAP name.

Usage

From source file:Main.java

public static void main(String args[]) {
    try {//from   w w  w .  jav a2 s  .  c  o  m
        LdapName one = new LdapName("cn=Abc Def, ou=People, o=JNDITutorial");
        LdapName two = new LdapName("cn=Abc Def");
        LdapName three = new LdapName("o=JNDITutorial");
        LdapName four = new LdapName("");

        System.out.println(one.equals(two));
        System.out.println(one.startsWith(three));
        System.out.println(one.endsWith(two));
        System.out.println(one.startsWith(four));
        System.out.println(one.endsWith(four));
        System.out.println(one.endsWith(three));
        System.out.println(one.isEmpty());
        System.out.println(four.isEmpty());
        System.out.println(four.size() == 0);
    } catch (InvalidNameException e) {
        e.printStackTrace();
    }
}

From source file:CompareLdapNames.java

public static void main(String args[]) {
    try {//  w  w w  . j  a  v a  2  s. c o m
        LdapName one = new LdapName("cn=Vincent Ryan, ou=People, o=JNDITutorial");
        LdapName two = new LdapName("cn=Vincent Ryan");
        LdapName three = new LdapName("o=JNDITutorial");
        LdapName four = new LdapName("");

        System.out.println(one.equals(two)); // false
        System.out.println(one.startsWith(three)); // true
        System.out.println(one.endsWith(two)); // true
        System.out.println(one.startsWith(four)); // true
        System.out.println(one.endsWith(four)); // true
        System.out.println(one.endsWith(three)); // false
        System.out.println(one.isEmpty()); // false
        System.out.println(four.isEmpty()); // true
        System.out.println(four.size() == 0); // true
    } catch (InvalidNameException e) {
        e.printStackTrace();
    }
}

From source file:org.jahia.services.usermanager.ldap.LDAPUserGroupProvider.java

/**
 * Try to guess if the given dn is a user or a group
 *
 * @param dn//w w w. j a  v a 2s  . c om
 * @return
 * @throws InvalidNameException
 */
private Boolean guessUserOrGroupFromDN(String dn) throws InvalidNameException {
    Boolean isUser = null;
    final LdapName memberLdapName = LdapUtils.newLdapName(dn);
    if (memberLdapName.startsWith(new LdapName(userConfig.getUidSearchName()))) {
        // it's a user
        isUser = distinctBase ? true : null;
    } else if (memberLdapName.startsWith(new LdapName(groupConfig.getSearchName()))) {
        // it's a group
        isUser = distinctBase ? false : null;
    }
    return isUser;
}

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

private boolean nameStartsWithNameInSet(LdapName name, Set<LdapName> s1) {
    for (LdapName n : s1) {
        if (name.startsWith(n)) {
            return true;
        }//from   w w  w.java2s  . c o  m
    }
    return false;
}

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

private void removeCommonPrefixedNamesFromSets(Set<LdapName> s1, Set<LdapName> s2) {
    Set<LdapName> copyS1 = new LinkedHashSet<>(s1);
    Set<LdapName> copyS2 = new LinkedHashSet<>(s2);
    for (LdapName n1 : copyS1) {
        for (LdapName n2 : copyS2) {
            if (n1.startsWith(n2) || n2.startsWith(n1)) {
                s1.remove(n1);// w  ww . j  a  va  2 s  .c om
                s2.remove(n2);
            }
        }
    }
}

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

/**
 *
 * {@inheritDoc}/*from w w w  .ja  va 2 s  . c o  m*/
 */
@Override
public Collection<NodeDescription> getGroups(final Date modifiedSince) {
    // Work out whether the user and group trees are disjoint. This may allow us to optimize reverse DN
    // resolution.
    final LdapName groupDistinguishedNamePrefix = this.resolveDistinguishedNamePrefix(this.groupSearchBase);
    final LdapName userDistinguishedNamePrefix = this.resolveDistinguishedNamePrefix(this.userSearchBase);

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

    final String query;
    if (modifiedSince == null) {
        query = this.groupQuery;
    } else {
        final MessageFormat mf = new MessageFormat(this.groupDifferentialQuery, Locale.ENGLISH);
        query = mf.format(new Object[] { this.timestampFormat.format(modifiedSince) });
    }

    // find duplicate gid in advance
    final Set<String> groupNames = new HashSet<>();
    final Map<String, AtomicInteger> groupNameCounts = new HashMap<>();
    this.processQuery((result) -> {
        final Attribute nameAttribute = result.getAttributes().get(this.groupIdAttributeName);
        if (nameAttribute == null) {
            if (this.errorOnMissingUID) {
                final Object[] params = { result.getNameInNamespace(), this.groupIdAttributeName };
                throw new AlfrescoRuntimeException("synchronization.err.ldap.get.group.id.missing", params);
            } else {
                LOGGER.warn("Missing GID on {}", result.getNameInNamespace());
            }
        } else {
            final Collection<String> attributeValues = this.mapAttribute(nameAttribute, String.class);
            final String groupName = attributeValues.iterator().next();
            LOGGER.debug("Group DN recognized: {}", groupName);

            if (groupNames.contains(groupName)) {
                if (this.errorOnDuplicateGID) {
                    throw new AlfrescoRuntimeException("Duplicate group id found: " + groupName);
                }
                LOGGER.warn("Duplicate gid found for {} -> merging definitions", groupName);
                groupNameCounts.computeIfAbsent(groupName, (x) -> {
                    return new AtomicInteger(1);
                }).getAndIncrement();
            } else {
                groupNames.add(groupName);
            }
        }
    }, this.groupSearchBase, this.groupQuery, new String[] { this.groupIdAttributeName });

    final Supplier<InitialDirContext> contextSupplier = this.buildContextSupplier();
    final Function<InitialDirContext, Boolean> nextPageChecker = this.buildNextPageChecker();
    final Function<InitialDirContext, NamingEnumeration<SearchResult>> groupSearcher = this
            .buildGroupSearcher(query);

    final NodeMapper groupMapper = this.buildGroupMapper(disjoint, groupDistinguishedNamePrefix,
            userDistinguishedNamePrefix);
    return new PersonCollection(contextSupplier, nextPageChecker, groupSearcher, groupMapper,
            this.queryBatchSize, groupNames.size());
}

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 w w  w .j  a v a 2  s .  c om
        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: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 {/*from   w  w w  .  j  a  va 2 s .c o  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.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 {//from w w w . j  av  a 2  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 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();
}