Example usage for javax.naming.directory Attribute get

List of usage examples for javax.naming.directory Attribute get

Introduction

In this page you can find the example usage for javax.naming.directory Attribute get.

Prototype

Object get(int ix) throws NamingException;

Source Link

Document

Retrieves the attribute value from the ordered list of attribute values.

Usage

From source file:net.spfbl.core.Core.java

private static boolean isRouteable(String hostame) {
    try {/*from w ww.jav  a 2 s.c  om*/
        Attributes attributesA = Server.getAttributesDNS(hostame, new String[] { "A" });
        Attribute attributeA = attributesA.get("A");
        if (attributeA == null) {
            Attributes attributesAAAA = Server.getAttributesDNS(hostame, new String[] { "AAAA" });
            Attribute attributeAAAA = attributesAAAA.get("AAAA");
            if (attributeAAAA != null) {
                for (int i = 0; i < attributeAAAA.size(); i++) {
                    String host6Address = (String) attributeAAAA.get(i);
                    if (SubnetIPv6.isValidIPv6(host6Address)) {
                        try {
                            InetAddress address = InetAddress.getByName(host6Address);
                            if (address.isLinkLocalAddress()) {
                                return false;
                            } else if (address.isLoopbackAddress()) {
                                return false;
                            }
                        } catch (UnknownHostException ex) {
                        }
                    } else {
                        return false;
                    }
                }
            }
        } else {
            for (int i = 0; i < attributeA.size(); i++) {
                String host4Address = (String) attributeA.get(i);
                host4Address = host4Address.trim();
                if (SubnetIPv4.isValidIPv4(host4Address)) {
                    try {
                        InetAddress address = InetAddress.getByName(host4Address);
                        if (address.isLinkLocalAddress()) {
                            return false;
                        } else if (address.isLoopbackAddress()) {
                            return false;
                        }
                    } catch (UnknownHostException ex) {
                    }
                } else {
                    return false;
                }
            }
        }
        return true;
    } catch (NamingException ex) {
        return false;
    }
}

From source file:org.springframework.ldap.core.DirContextAdapter.java

private void collectModifications(Attribute originalAttr, Attribute changedAttr, List modificationList)
        throws NamingException {

    Attribute originalClone = (Attribute) originalAttr.clone();
    Attribute addedValuesAttribute = new BasicAttribute(originalAttr.getID());

    for (int i = 0; i < changedAttr.size(); i++) {
        Object attributeValue = changedAttr.get(i);
        if (!originalClone.remove(attributeValue)) {
            addedValuesAttribute.add(attributeValue);
        }//from  ww w.  j  a  v  a 2 s  .  c  om
    }

    // We have now traversed and removed all values from the original that
    // were also present in the new values. The remaining values in the
    // original must be the ones that were removed.
    if (originalClone.size() > 0) {
        modificationList.add(new ModificationItem(DirContext.REMOVE_ATTRIBUTE, originalClone));
    }

    if (addedValuesAttribute.size() > 0) {
        modificationList.add(new ModificationItem(DirContext.ADD_ATTRIBUTE, addedValuesAttribute));
    }
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Obtains the roles for the given user.
 *
 * @param username the user name to fetch user data.
 * @return the list of roles to which the user is associated to.
 * @throws NamingException LDAP error obtaining roles fro the given user
 * @throws IOException //from  www . j  a  v a  2 s . c om
 */
protected String[] selectRolesByUsername(String username) throws NamingException, IOException {
    List userRoles = new ArrayList();

    InitialLdapContext ctx = null;
    try {
        ctx = createLdapInitialContext(getUseBindCredentials());
    } catch (NamingException e) {
        if (getUseBindCredentials()) {
            // in case we are using virtual identity store
            return (String[]) userRoles.toArray(new String[userRoles.size()]);
        } else {
            throw e;
        }
    }

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    String rolesCtxDN = getRolesCtxDN();

    // Search for any roles associated with the user
    if (rolesCtxDN != null) {

        // The attribute where user DN is stored in roles :
        String uidAttributeID = getUidAttributeID();
        if (uidAttributeID == null)
            uidAttributeID = "uniquemember";

        // The attribute that identifies the role name 
        String roleAttrName = getRoleAttributeID();
        if (roleAttrName == null)
            roleAttrName = "roles";

        String userDN;
        if ("UID".equals(getRoleMatchingMode())) {
            // Use User ID to match the role
            userDN = username;
        } else {
            // Default behaviour: Match the role using the User DN, not just the username :
            userDN = selectUserDN(username);
        }

        if (userDN != null) {
            if (logger.isDebugEnabled())
                logger.debug("Searching Roles for user '" + userDN + "' in Uid attribute name '"
                        + uidAttributeID + "'");

            try {
                if (userDN.contains("\\")) {
                    logger.debug("Escaping '\\' character");
                    userDN = userDN.replace("\\", "\\\\\\");
                }

                NamingEnumeration answer = ctx.search(rolesCtxDN, "(&(" + uidAttributeID + "=" + userDN + "))",
                        getSearchControls());

                if (logger.isDebugEnabled())
                    logger.debug("Search Name:  " + rolesCtxDN);

                if (logger.isDebugEnabled())
                    logger.debug("Search Filter:  (&(" + uidAttributeID + "=" + userDN + "))");

                if (!answer.hasMore())
                    logger.info("No role where found for user " + username);

                while (answer.hasMore()) {
                    SearchResult sr = (SearchResult) answer.next();
                    Attributes attrs = sr.getAttributes();
                    Attribute roles = attrs.get(roleAttrName);
                    for (int r = 0; r < roles.size(); r++) {
                        Object value = roles.get(r);
                        String roleName = null;
                        // The role attribute value is the role name
                        roleName = value.toString();

                        if (roleName != null) {
                            if (logger.isDebugEnabled())
                                logger.debug("Saving role '" + roleName + "' for user '" + username + "'");
                            userRoles.add(roleName);
                        }
                    }
                }
            } catch (NamingException e) {
                if (logger.isDebugEnabled())
                    logger.debug("Failed to locate roles", e);
            }
        }
    }
    // Close the context to release the connection
    if (tls != null) {
        tls.close();
    }
    ctx.close();
    return (String[]) userRoles.toArray(new String[userRoles.size()]);
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationCreate(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        String result = null;//from  w  w w  .j  a va  2 s. co  m
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Create attribute: " + a.getID());
            NamingEnumeration values;
            try {
                values = a.getAll();
            } catch (NamingException e1) {
                storeLdapException(e1, prc);
                throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1);
            }
            while (values.hasMoreElements()) {
                Attributes partialAttrs = new BasicAttributes();
                Attribute singleValuedAttribute;
                String id = a.getID();
                Object value = values.nextElement();
                if (log.isDebugEnabled()) {
                    if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) {
                        log.debug("Create value: ***");
                    } else {
                        log.debug("Create value: " + value);
                    }
                }
                if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) {
                    singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value));
                } else {
                    singleValuedAttribute = new BasicAttribute(id, value);
                }
                partialAttrs.put(singleValuedAttribute);
                DirContext dirContext = null;
                try {
                    dirContext = getDirContext(paramValueMap);
                    dirContext.modifyAttributes(entryName, DirContext.ADD_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   20 LDAP_TYPE_OR_VALUE_EXISTS Indicates that the attribute value specified in a modify or add operation already exists as a value for that attribute.
                    // Sun:
                    //   [LDAP: error code 20 - Attribute Or Value Exists]
                    if (e.getMessage().startsWith("[LDAP: error code 20 - ")) {
                        if (log.isDebugEnabled())
                            log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                        result = DEFAULT_RESULT_CREATE_OK;
                    } else {
                        storeLdapException(e, prc);
                        throw new SenderException(
                                "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]",
                                e);
                    }
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        if (result != null) {
            return result;
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            if (unicodePwd) {
                Enumeration enumeration = attrs.getIDs();
                while (enumeration.hasMoreElements()) {
                    String id = (String) enumeration.nextElement();
                    if ("unicodePwd".equalsIgnoreCase(id)) {
                        Attribute attr = attrs.get(id);
                        for (int i = 0; i < attr.size(); i++) {
                            attr.set(i, encodeUnicodePwd(attr.get(i)));
                        }
                    }
                }
            }
            dirContext = getDirContext(paramValueMap);
            dirContext.bind(entryName, null, attrs);
            return DEFAULT_RESULT;
        } catch (NamingException e) {
            // if (log.isDebugEnabled()) log.debug("Exception in operation [" + getOperation()+ "] entryName ["+entryName+"]", e);
            if (log.isDebugEnabled())
                log.debug("Exception in operation [" + getOperation() + "] entryName [" + entryName + "]: "
                        + e.getMessage());
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   68 LDAP_ALREADY_EXISTS Indicates that the add operation attempted to add an entry that already exists, or that the modify operation attempted to rename an entry to the name of an entry that already exists.
            // Sun:
            //   [LDAP: error code 68 - Entry Already Exists]
            if (e.getMessage().startsWith("[LDAP: error code 68 - ")) {
                return DEFAULT_RESULT_CREATE_OK;
            } else {
                storeLdapException(e, prc);
                throw new SenderException(e);
            }
        } finally {
            closeDirContext(dirContext);
        }
    }

}

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java

protected void importGroups(LDAPImportContext ldapImportContext, Attributes userAttributes, User user)
        throws Exception {

    Properties groupMappings = ldapImportContext.getGroupMappings();

    String groupMappingsUser = groupMappings.getProperty("user");

    Set<Long> newUserGroupIds = new LinkedHashSet<>();

    LDAPServerConfiguration ldapServerConfiguration = _ldapServerConfigurationProvider
            .getConfiguration(ldapImportContext.getCompanyId(), ldapImportContext.getLdapServerId());

    if (Validator.isNotNull(groupMappingsUser) && ldapServerConfiguration.groupSearchFilterEnabled()) {

        String baseDN = ldapServerConfiguration.baseDN();

        StringBundler sb = new StringBundler(9);

        sb.append(StringPool.OPEN_PARENTHESIS);
        sb.append(StringPool.AMPERSAND);

        String groupSearchFilter = ldapServerConfiguration.groupSearchFilter();

        LDAPUtil.validateFilter(groupSearchFilter, "LDAPServerConfiguration.groupSearchFilter");

        sb.append(groupSearchFilter);/*ww w. j a  v  a2s.  com*/

        sb.append(StringPool.OPEN_PARENTHESIS);
        sb.append(groupMappingsUser);
        sb.append(StringPool.EQUAL);

        Binding binding = _portalLDAP.getUser(ldapImportContext.getLdapServerId(),
                ldapImportContext.getCompanyId(), user.getScreenName(), user.getEmailAddress());

        String fullUserDN = binding.getNameInNamespace();

        sb.append(escapeValue(fullUserDN));

        sb.append(StringPool.CLOSE_PARENTHESIS);
        sb.append(StringPool.CLOSE_PARENTHESIS);

        byte[] cookie = new byte[0];

        while (cookie != null) {
            List<SearchResult> searchResults = new ArrayList<>();

            String groupMappingsGroupName = GetterUtil.getString(groupMappings.getProperty("groupName"));

            groupMappingsGroupName = StringUtil.toLowerCase(groupMappingsGroupName);

            cookie = _portalLDAP.searchLDAP(ldapImportContext.getCompanyId(),
                    ldapImportContext.getLdapContext(), cookie, 0, baseDN, sb.toString(),
                    new String[] { groupMappingsGroupName }, searchResults);

            for (SearchResult searchResult : searchResults) {
                String fullGroupDN = searchResult.getNameInNamespace();

                newUserGroupIds = importGroup(ldapImportContext, fullGroupDN, user, newUserGroupIds);
            }
        }
    } else {
        Properties userMappings = ldapImportContext.getUserMappings();

        String userMappingsGroup = userMappings.getProperty("group");

        if (Validator.isNull(userMappingsGroup)) {
            if (_log.isInfoEnabled()) {
                _log.info("Skipping group import because no mappings for LDAP "
                        + "groups were specified in user mappings " + userMappings);
            }

            return;
        }

        Attribute userGroupAttribute = userAttributes.get(userMappingsGroup);

        if (userGroupAttribute == null) {
            return;
        }

        for (int i = 0; i < userGroupAttribute.size(); i++) {
            String fullGroupDN = (String) userGroupAttribute.get(i);

            newUserGroupIds = importGroup(ldapImportContext, fullGroupDN, user, newUserGroupIds);
        }
    }

    addUserGroupsNotAddedByLDAPImport(user.getUserId(), newUserGroupIds);

    Set<Long> oldUserGroupIds = new LinkedHashSet<>();

    List<UserGroup> oldUserGroups = _userGroupLocalService.getUserUserGroups(user.getUserId());

    for (UserGroup oldUserGroup : oldUserGroups) {
        oldUserGroupIds.add(oldUserGroup.getUserGroupId());
    }

    if (!oldUserGroupIds.equals(newUserGroupIds)) {
        long[] userGroupIds = ArrayUtil.toLongArray(newUserGroupIds);

        _userGroupLocalService.setUserUserGroups(user.getUserId(), userGroupIds);
    }
}

From source file:no.feide.moria.directory.backend.JNDIBackend.java

/**
 * Retrieves a list of attributes from an element.
 * @param ldap//from www . ja  v a 2s. co m
 *            A prepared LDAP context. Cannot be <code>null</code>.
 * @param rdn
 *            The relative DN (to the DN in the LDAP context
 *            <code>ldap</code>). Cannot be <code>null</code>.
 * @param attributes
 *            The requested attribute's names. Also indirectly referenced
 *            attributes on the form
 *            <code>someReferenceAttribute:someIndirectAttribute</code>,
 *            where the DN in the reference attribute
 *            <code>someReferenceAttribute</code> is followed to look up
 *            <code>someIndirectAttribute</code> from another element.
 * @return The requested attributes (<code>String</code> names and
 *         <code>String[]</code> values), if they did exist in the
 *         external backend. Otherwise returns those attributes that could
 *         actually be read, this may be an empty <code>HashMap</code>.
 *         Returns an empty <code>HashMap</code> if
 *         <code>attributes</code> is <code>null</code> or an empty
 *         array. Note that attribute values are mapped to
 *         <code>String</code> using ISO-8859-1.
 * @throws BackendException
 *             If unable to read the attributes from the backend.
 * @throws NullPointerException
 *             If <code>ldap</code> or <code>rdn</code> is
 *             <code>null</code>.
 * @see javax.naming.directory.InitialDirContext#getAttributes(java.lang.String,
 *      java.lang.String[])
 */
private HashMap<String, String[]> getAttributes(final InitialLdapContext ldap, final String rdn,
        final String[] attributes) throws BackendException {

    // Sanity checks.
    if (ldap == null)
        throw new NullPointerException("LDAP context cannot be NULL");
    if (rdn == null)
        throw new NullPointerException("RDN cannot be NULL");
    if ((attributes == null) || (attributes.length == 0))
        return new HashMap<String, String[]>();

    // Used to remember attributes to be read through references later on.
    Hashtable<String, Vector> attributeReferences = new Hashtable<String, Vector>();

    // Strip down request, resolving references and removing duplicates.
    Vector<String> strippedAttributeRequest = new Vector<String>();
    for (int i = 0; i < attributes.length; i++) {
        int indexOfSplitCharacter = attributes[i]
                .indexOf(DirectoryManagerBackend.ATTRIBUTE_REFERENCE_SEPARATOR);
        if (indexOfSplitCharacter == -1) {

            // A regular attribute request.
            if (!strippedAttributeRequest.contains(attributes[i]))
                strippedAttributeRequest.add(attributes[i]);

        } else {

            // A referenced attribute request.
            final String referencingAttribute = attributes[i].substring(0, indexOfSplitCharacter);
            if (!strippedAttributeRequest.contains(referencingAttribute))
                strippedAttributeRequest.add(referencingAttribute);

            // Add to list of attributes to be read through each reference.
            if (!attributeReferences.containsKey(referencingAttribute)) {

                // Add new reference.
                Vector<String> referencedAttribute = new Vector<String>();
                referencedAttribute.add(attributes[i].substring(indexOfSplitCharacter + 1));
                attributeReferences.put(referencingAttribute, referencedAttribute);

            } else {

                // Update existing reference.
                Vector<String> referencedAttribute = attributeReferences.get(referencingAttribute);
                if (!referencedAttribute.contains(attributes[i].substring(indexOfSplitCharacter + 1)))
                    referencedAttribute.add(attributes[i].substring(indexOfSplitCharacter + 1));

            }

        }

    }

    // The context provider URL and DN, for later logging.
    String url = "unknown backend";
    String dn = "unknown dn";

    // Get the attributes from an already initialized LDAP connection.
    Attributes rawAttributes = null;
    try {

        // Remember the URL and bind DN, for later logging.
        final Hashtable environment = ldap.getEnvironment();
        url = (String) environment.get(Context.PROVIDER_URL);
        dn = (String) environment.get(Context.SECURITY_PRINCIPAL);

        // Get the attributes.
        rawAttributes = ldap.getAttributes(rdn, strippedAttributeRequest.toArray(new String[] {}));

    } catch (NameNotFoundException e) {

        // Successful authentication but missing user element; no attributes
        // returned and the event is logged.
        log.logWarn("No LDAP element found (DN was '" + dn + "')", mySessionTicket);
        rawAttributes = new BasicAttributes();

    } catch (NamingException e) {
        String a = new String();
        for (int i = 0; i < attributes.length; i++)
            a = a + attributes[i] + ", ";
        throw new BackendException("Unable to read attribute(s) '" + a.substring(0, a.length() - 2) + "' from '"
                + rdn + "' on '" + url + "'", e);
    }

    // Translate retrieved attributes from Attributes to HashMap.
    HashMap<String, String[]> convertedAttributes = new HashMap<String, String[]>();
    for (int i = 0; i < attributes.length; i++) {

        // Did we get any attribute back at all?
        final String requestedAttribute = attributes[i];
        Attribute rawAttribute = rawAttributes.get(requestedAttribute);
        if (rawAttribute == null) {

            // Attribute was not returned.
            log.logDebug("Requested attribute '" + requestedAttribute + "' not found on '" + url + "'",
                    mySessionTicket);

        } else {

            // Map the attribute values to String[].
            ArrayList<String> convertedAttributeValues = new ArrayList<String>(rawAttribute.size());
            for (int j = 0; j < rawAttribute.size(); j++) {
                try {

                    // We either have a String or a byte[].
                    String convertedAttributeValue = null;
                    try {

                        // Encode String.
                        convertedAttributeValue = new String(((String) rawAttribute.get(j)).getBytes(),
                                DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET);
                    } catch (ClassCastException e) {

                        // Encode byte[] to String.
                        convertedAttributeValue = new String(Base64.encodeBase64((byte[]) rawAttribute.get(j)),
                                DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET);

                    }
                    convertedAttributeValues.add(convertedAttributeValue);

                } catch (NamingException e) {
                    throw new BackendException("Unable to read attribute value of '" + rawAttribute.getID()
                            + "' from '" + url + "'", e);
                } catch (UnsupportedEncodingException e) {
                    throw new BackendException(
                            "Unable to use " + DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET + " encoding",
                            e);
                }
            }
            convertedAttributes.put(requestedAttribute, convertedAttributeValues.toArray(new String[] {}));

        }

    }

    // Follow references to look up any indirectly referenced attributes.
    Enumeration<String> keys = attributeReferences.keys();
    while (keys.hasMoreElements()) {

        // Do we have a reference? 
        final String referencingAttribute = keys.nextElement();
        final String[] referencingValues = convertedAttributes.get(referencingAttribute);
        if (referencingValues == null) {

            // No reference was found in this attribute.
            log.logDebug("Found no DN references in attribute '" + referencingAttribute + "'", mySessionTicket);

        } else {

            // One (or more) references was found in this attribute.
            if (referencingValues.length > 1)
                log.logDebug("Found " + referencingValues.length + " DN references in attribute '"
                        + referencingAttribute + "'; ignoring all but first", mySessionTicket);
            log.logDebug("Following reference '" + referencingValues[0] + "' found in '" + referencingAttribute
                    + "' to look up attribute(s) '" + attributeReferences.get(referencingAttribute).toString(),
                    mySessionTicket);
            String providerURL = null; // To be used later.
            try {

                // Follow the reference.
                providerURL = (String) ldap.getEnvironment().get(Context.PROVIDER_URL);
                providerURL = providerURL.substring(0, providerURL.lastIndexOf("/") + 1) + referencingValues[0];
                ldap.addToEnvironment(Context.PROVIDER_URL, providerURL);

            } catch (NamingException e) {
                throw new BackendException("Unable to update provider URL in LDAP environment", e);
            }

            // Add any referenced attributes returned.
            HashMap additionalAttributes = getAttributes(ldap, providerURL,
                    (String[]) attributeReferences.get(referencingAttribute).toArray(new String[] {}));
            Iterator i = additionalAttributes.keySet().iterator();
            while (i.hasNext()) {
                String attributeName = (String) i.next();
                convertedAttributes.put(referencingAttribute
                        + DirectoryManagerBackend.ATTRIBUTE_REFERENCE_SEPARATOR + attributeName,
                        (String[]) additionalAttributes.get(attributeName));
            }

        }

    }

    return convertedAttributes;

}

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 .  j a  va 2  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:fedora.server.security.servletfilters.ldap.FilterLdap.java

private void getAttributes(Attributes attributes, Map map) throws Throwable {
    String m = FilterSetup.getFilterNameAbbrev(FILTER_NAME) + " getAttributes() ";
    log.debug(m + ">");
    try {//from w w  w.jav a  2  s.co  m
        for (String key : ATTRIBUTES2RETURN) {
            log.debug(m + "looking for return attribute==" + key);
            Attribute attribute = attributes.get(key);
            if (attribute == null) {
                log.error(m + "null object...continue to next attr sought");
                continue;
            }
            if (GROUPS_NAME != null && !"".equals(GROUPS_NAME)) {
                key = GROUPS_NAME;
                log.debug(m + "values collected and interpreted as groups==" + key);
            }
            Set values;
            if (map.containsKey(key)) {
                log.debug(m + "already a value-set for attribute==" + key);
                values = (Set) map.get(key);
            } else {
                log.debug(m + "making+storing a value-set for attribute==" + key);
                values = new HashSet();
                map.put(key, values);
            }
            int size = attribute.size();
            log.debug(m + "object with n==" + size);
            for (int j = 0; j < size; j++) {
                Object o = attribute.get(j);
                values.add(o);
                log.debug(m + "added value==" + o.toString() + ", class==" + o.getClass().getName());
            }
        }
    } finally {
        log.debug(m + "<");
    }
}

From source file:org.liveSense.auth.ldap.LdapAuthenticationHandler.java

/**
 * Copy LDAP user properties to JCR User properties
 * @param ldapUser//from   w  w w  .j av  a 2s  . c  om
 */
private void updateUserAttributes(Session session, LdapUser ldapUser, Authorizable user) {
    // Collecting attribute names
    try {
        for (Iterator e = user.getPropertyNames(); e.hasNext();) {
            user.removeProperty((String) e.next());
        }

        for (NamingEnumeration<? extends Attribute> ae = ldapUser.getAttributes().getAll(); ae.hasMore();) {
            Attribute attr = ae.next();
            log.info("Attribute: " + attr.getID());
            // multi value attribute
            if (attr.size() > 1) {
                Value[] props = new Value[attr.size()];
                int i = 0;
                for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
                    Object o = e.next();
                    if (o instanceof String)
                        props[i] = session.getValueFactory().createValue((String) o);
                    i++;
                }
                user.setProperty(attr.getID(), props);
            } else {
                if (attr.get(0) instanceof String)
                    user.setProperty(attr.getID(), session.getValueFactory().createValue((String) attr.get(0)));
            }
        }
    } catch (Exception e) {
        log.error("Could not update user attributes", e);
    }

}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java

private Privilege convertLdapGroupToOrgPriv(SearchResult sr) throws NamingException, IllegalAccessException {
    Privilege vOrgPrivilege = null;//from ww  w .ja v  a2s .c  om
    String vCnPrivileg = null, vPrivEntryDN = null, vOrgEntryDN = null;
    PrivilegeEnum vPrivilege;
    Attribute vAttr;
    String vMemberRef;
    String[] vStrs;
    if (sr != null) {
        try {
            // -- Beispiel fr entryDN:
            // Organisationeles Privileg:
            // cn=ddb_ingest,o=99900189,o=00001475,dc=ddb,dc=iais,dc=fraunhofer,dc=de
            // construct privileges
            vCnPrivileg = (String) sr.getAttributes().get(Constants.ldap_ddbPrivilege_Cn).get();
            vPrivilege = this.mapToPrivilege(sr.getAttributes(), Constants.ldap_ddbPrivilege_Cn);
            // vPrivEntryDN = (vAttr = sr.getAttributes().get("entryDN")) !=
            // null ? String.valueOf(vAttr.get()) : null; //
            // organizationName
            vPrivEntryDN = sr.getNameInNamespace(); // liefert das gleiche
            // wie oben...
            if ((vPrivilege != null) && (vPrivEntryDN != null)) {
                // vOrgEntryDN =
                // vPrivEntryDN.substring(vPrivEntryDN.indexOf(",") + 1,
                // vPrivEntryDN.indexOf(",dc") );
                vOrgEntryDN = vPrivEntryDN.substring(vPrivEntryDN.indexOf(",") + 1);
                vOrgPrivilege = new Privilege(vPrivilege);
                vAttr = sr.getAttributes().get(Constants.ldap_ddbPrivilege_Member);
                for (int i = 0; i < vAttr.size(); i++) {
                    if (((vMemberRef = String.valueOf(vAttr.get(i))) != null) && (vMemberRef.length() > 0)) {
                        if (((vStrs = vMemberRef.split(",")).length >= 1)
                                && ((vStrs = vStrs[0].split("=")).length == 2)
                                && (vStrs[0].trim().equalsIgnoreCase(Constants.ldap_ddbPerson_Id))) {
                            vOrgPrivilege.add(vStrs[1].trim());
                        }
                    }
                }
            } else {
                LOG.log(Level.WARNING, "Ein fehlerhaftes Privileg: Privileg: ''{0}'', Privileg-Entry: ''{1}''.",
                        new Object[] { vCnPrivileg, vPrivEntryDN });
            }
        } catch (NamingException ex) {
            LOG.log(Level.SEVERE, "CnPrivileg: '" + vCnPrivileg + "', PrivEntryDN: '" + vPrivEntryDN
                    + "', OrgEntryDN: '" + vOrgEntryDN + "'");
            throw ex;
        }
    }
    return vOrgPrivilege;
}