Example usage for javax.naming.ldap LdapName getRdn

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

Introduction

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

Prototype

public Rdn getRdn(int posn) 

Source Link

Document

Retrieves an RDN of this LDAP name as an Rdn.

Usage

From source file:jenkins.security.plugins.ldap.FromUserRecordLDAPGroupMembershipStrategy.java

@Override
public GrantedAuthority[] getGrantedAuthorities(LdapUserDetails ldapUser) {
    List<GrantedAuthority> result = new ArrayList<GrantedAuthority>();
    Attributes attributes = ldapUser.getAttributes();
    final String attributeName = getAttributeName();
    Attribute attribute = attributes == null ? null : attributes.get(attributeName);
    if (attribute != null) {
        try {/*from  w  ww.  j  a v a2  s. co m*/
            for (Object value : Collections.list(attribute.getAll())) {
                String groupName = String.valueOf(value);
                try {
                    LdapName dn = new LdapName(groupName);
                    groupName = String.valueOf(dn.getRdn(dn.size() - 1).getValue());
                } catch (InvalidNameException e) {
                    LOGGER.log(Level.FINEST, "Expected a Group DN but found: {0}", groupName);
                }
                result.add(new GrantedAuthorityImpl(groupName));
            }
        } catch (NamingException e) {
            LogRecord lr = new LogRecord(Level.FINE,
                    "Failed to retrieve member of attribute ({0}) from LDAP user details");
            lr.setThrown(e);
            lr.setParameters(new Object[] { attributeName });
            LOGGER.log(lr);
        }

    }
    return result.toArray(new GrantedAuthority[result.size()]);
}

From source file:edu.acu.cs.spring.security.cas.userdetails.GrantedAuthorityFromMemberOfAssertionAttributeUserDetailsService.java

private void convertObjectAndAddGrantedAuthorityToList(final Object o,
        final List<GrantedAuthority> grantedAuthorities) {
    if (o instanceof String) {
        final String memberOfString = (String) o;
        try {/*from  w ww  .j av a 2s  . c  om*/
            LdapName name = new LdapName(memberOfString);
            if (name.size() > 0) {
                String value = name.getRdn(name.size() - 1).getValue().toString();
                if (this.convertToUpperCase) {
                    value = value.toUpperCase();
                }
                if (this.convertSpacesToUnderscores) {
                    value = value.replace(' ', '_');
                }
                grantedAuthorities.add(new SimpleGrantedAuthority(rolePrefix + value));
            }
        } catch (InvalidNameException e) {
            logger.warn("Couldn't convert \"" + memberOfString + "\" to an LdapName", e);
        }
    }
}

From source file:org.apache.syncope.core.sync.LDAPDomainSyncActions.java

@Override
public <T extends AbstractAttributableTO> SyncDelta beforeCreate(SyncResultsHandler srh, SyncDelta sd, T t)
        throws JobExecutionException {

    if (!ObjectClass.ACCOUNT_NAME.equals(sd.getObject().getObjectClass().toString())) {
        if (t != null) {
            LOG.debug("CREATION OF A NEW USER");
            String rdn = "/";
            ConnectorObject conn = sd.getObject();

            try {
                LdapName dn = new LdapName(conn.getAttributeByName(Name.NAME).getValue().toString()
                        .replace("[", "").replace("]", ""));
                if (dn.size() == 4) {
                    rdn = dn.getRdn(2).getValue().toString();
                } else {
                    rdn = "/";
                }//www .jav a 2s .com
            } catch (InvalidNameException ex) {
                LOG.error("ERROR CONSTRUCTING LDAP DN FROM NAME ATTRIBUTE: ".concat(ex.getMessage()));
            }
            //Creation of new attribute to assign to new user in Syncope
            AttributeTO domain = new AttributeTO();
            domain.setSchema("domain");
            domain.addValue(rdn);
            t.addAttribute(domain);
        } else {
            LOG.error("SUBJECT OF SYNCHRONIZATION IS NULL");
        }
    }
    return sd;
}

From source file:ldap.SearchUtility.java

/**
 * This is a utility method for turning a list of LdapNames into a list
 * of Strings, being the final RDN value.  E.g.
 * ou=Computer Networks Division,ou=COMPUTERS AND INFORMATION GROUP,ou=DIRECTORS OFFICE AREA,ou=isac,dc=isro,dc=dos,c=au
 * would become simply "Computer Networks Division".
 * @param elementNames//w  w w.  j  a  va2 s.c  om
 * @return a list of the same order and size as that passed in, but giving only the final String RDN value.
 */
public List<String> convertLdapNamesToStrings(List<LdapName> elementNames) {
    List<String> elements = new ArrayList<String>(elementNames.size());
    for (LdapName name : elementNames)
        elements.add(name.getRdn(name.size() - 1).getValue().toString());
    return elements;
}

From source file:org.apache.syncope.core.sync.LDAPDomainSyncActions.java

@Transactional(readOnly = true)
@Override//  w ww  . jav  a  2  s.  c o m
public <T extends AbstractAttributableTO, K extends AbstractAttributableMod> SyncDelta beforeUpdate(
        SyncResultsHandler srh, SyncDelta sd, T t, K k) throws JobExecutionException {

    if (!ObjectClass.ACCOUNT_NAME.equals(sd.getObject().getObjectClass().toString())) {

        if (t != null) {
            SyncopeUser user = userDAO.find(t.getId());

            if (user != null && !user.isSuspended()) {

                ConnectorObject conn = sd.getObject();
                // Get dn of current user to be updated on Syncope 
                LdapName dnOnSyncope = resolveDnOnSyncope(user, srh);
                try {
                    LdapName dn = new LdapName(conn.getAttributeByName(Name.NAME).getValue().toString()
                            .replace("[", "").replace("]", ""));
                    // Check if dn on Syncope and dn on Ldap are the same, if so returns
                    if (dnOnSyncope.compareTo(dn) != 0) {
                        String rdn;
                        if (dn.size() == 4) {
                            rdn = dn.getRdn(2).getValue().toString();
                        } else {
                            rdn = "/";
                        }
                        //Creation of new attribute to assign to new user in Syncope
                        AttributeMod attr = new AttributeMod();
                        attr.setSchema("domain");
                        attr.addValueToBeAdded(rdn);
                        k.addAttributeToBeUpdated(attr);
                    } else {
                        LOG.info("NO CHANGES APPLIED TO DOMAIN ATTRIBUTE");
                        return sd;
                    }
                } catch (InvalidNameException ex) {
                    LOG.error("ERROR CONSTRUCTING LDAP DN FROM NAME ATTRIBUTE: ".concat(ex.getMessage()));
                }
            } else {
                LOG.error("USER WITH ID: " + t.getId() + " DOESN'T EXIST OR IS SUSPENDED ON SYNCOPE ");
            }
        } else {
            LOG.error("SUBJECT OF SYNCHRONIZATION IS NULL");
        }
    }
    return sd;
}

From source file:nu.yona.server.device.rest.DeviceController.java

@PostConstruct
private void setSslRootCertificateCn() {
    try {/*w  ww  . j  a v a  2  s  . c  o  m*/
        LdapName name = new LdapName(sslRootCertificate.getIssuerX500Principal().getName());
        DeviceResource.setSslRootCertificateCn(name.getRdn(0).getValue().toString());
    } catch (InvalidNameException e) {
        throw YonaException.unexpected(e);
    }
}

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;
    }//  w  w w. j  a v a  2  s.co  m

    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:ldap.SearchUtility.java

/**
 * This parses the name, and adds 'fake' attributes corresponding to the structure types list.
 * @param entry//ww w . j  a  v a2  s .  co  m
 */
private void fillInSyntheticAttributes(Entry entry) {
    LdapName name = entry.getName();

    int size = name.size();
    int maxTypeSize = structureTypes.size();
    //for (int i=Config.SEARCH_BASE_DN_SIZE-1; i<size; i++)
    for (int i = LdapConstants.ldapSearchBaseDnSize - 1; i < size; i++) {
        String value = name.getRdn(i).getValue().toString();
        //int typeIndex = i - Config.SEARCH_BASE_DN_SIZE + 1;
        int typeIndex = i - LdapConstants.ldapSearchBaseDnSize + 1;
        if (typeIndex < maxTypeSize) {
            String typeName = structureTypes.get(typeIndex);
            if (entry.get(typeName) == null)
                entry.put(typeName, value);
            else
                logger.info("WARNING: Type Name '" + typeName + "' clashes with existing attribute - skipping");
        } else // if we're here, we've run out of defined elements.
        {
            logger.info("WARNING: Type elements out of range in name " + name);
        }

    }
}

From source file:nu.yona.server.subscriptions.rest.UserController.java

@PostConstruct
private void setSslRootCertificateCn() // YD-544
{
    try {//from ww w  . j av  a  2  s .  c  om
        LdapName name = new LdapName(sslRootCertificate.getIssuerX500Principal().getName());
        UserResource.setSslRootCertificateCn(name.getRdn(0).getValue().toString());
    } catch (InvalidNameException e) {
        throw YonaException.unexpected(e);
    }
}

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 {/* w w  w  .  j  a va2s  .  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);
    }
}