Example usage for javax.naming.directory Attribute getID

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

Introduction

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

Prototype

String getID();

Source Link

Document

Retrieves the id of this attribute.

Usage

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

/**
 * Gets the values of a repeating attribute that may have range restriction options. If an attribute is range
 * restricted, it will appear in the attribute set with a ";range=i-j" option, where i and j indicate the start and
 * end index, and j is '*' if it is at the end.
 *
 * @param attributes//from  w  w  w  .  j  ava  2  s  .c  om
 *            the attributes
 * @param attributeName
 *            the attribute name
 * @return the range restricted attribute
 * @throws javax.naming.NamingException
 *             the naming exception
 */
private Attribute getRangeRestrictedAttribute(Attributes attributes, String attributeName)
        throws NamingException {
    Attribute unrestricted = attributes.get(attributeName);
    if (unrestricted != null) {
        return unrestricted;
    }
    NamingEnumeration<? extends Attribute> i = attributes.getAll();
    String searchString = attributeName.toLowerCase() + ';';
    while (i.hasMore()) {
        Attribute attribute = i.next();
        if (attribute.getID().toLowerCase().startsWith(searchString)) {
            return attribute;
        }
    }
    return null;
}

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

private String performOperationDelete(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        String result = null;/*  w w w  .  j  av  a  2 s  . co  m*/
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Delete 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("Delete value: ***");
                    } else {
                        log.debug("Delete 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.REMOVE_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   16 LDAP_NO_SUCH_ATTRIBUTE Indicates that the attribute specified in the modify or compare operation does not exist in the entry.
                    //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
                    // Sun:
                    //   [LDAP: error code 16 - No Such Attribute...
                    //   [LDAP: error code 32 - No Such Object...
                    // AD:
                    //   [LDAP: error code 16 - 00002085: AtrErr: DSID-03151F03, #1...
                    if (e.getMessage().startsWith("[LDAP: error code 16 - ")
                            || e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                        if (log.isDebugEnabled())
                            log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                        result = DEFAULT_RESULT_DELETE;
                    } 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 {
            dirContext = getDirContext(paramValueMap);
            dirContext.unbind(entryName);
            return DEFAULT_RESULT;
        } catch (NamingException e) {
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
            // Sun:
            //   [LDAP: error code 32 - No Such Object...
            if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                if (log.isDebugEnabled())
                    log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                return DEFAULT_RESULT_DELETE;
            } else {
                storeLdapException(e, prc);
                throw new SenderException(
                        "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e);
            }
        } finally {
            closeDirContext(dirContext);
        }
    }
}

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

protected XmlBuilder attributesToXml(Attributes atts) throws NamingException {
    XmlBuilder attributesElem = new XmlBuilder("attributes");

    NamingEnumeration all = atts.getAll();
    while (all.hasMore()) {
        Attribute attribute = (Attribute) all.next();
        XmlBuilder attributeElem = new XmlBuilder("attribute");
        attributeElem.addAttribute("name", attribute.getID());
        if (attribute.size() == 1 && attribute.get() != null) {
            attributeElem.addAttribute("value", attribute.get().toString());
        } else {/*from   w  ww . ja va 2  s .com*/
            NamingEnumeration values = attribute.getAll();
            while (values.hasMore()) {
                Object value = values.next();
                XmlBuilder itemElem = new XmlBuilder("item");
                itemElem.addAttribute("value", value.toString());
                attributeElem.addSubElement(itemElem);
            }
        }
        attributesElem.addSubElement(attributeElem);
    }
    return attributesElem;
}

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  v a2s  .  c  o 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:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationUpdate(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    String entryNameAfter = entryName;
    if (paramValueMap != null) {
        String newEntryName = (String) paramValueMap.get("newEntryName");
        if (newEntryName != null && StringUtils.isNotEmpty(newEntryName)) {
            if (log.isDebugEnabled())
                log.debug("newEntryName=[" + newEntryName + "]");
            DirContext dirContext = null;
            try {
                dirContext = getDirContext(paramValueMap);
                dirContext.rename(entryName, newEntryName);
                entryNameAfter = newEntryName;
            } catch (NamingException e) {
                String msg;//from w  w  w.java  2s  .com
                // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
                // Sun:
                //   [LDAP: error code 32 - No Such Object...
                if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                    msg = "Operation [" + getOperation() + "] failed - wrong entryName [" + entryName + "]";
                } else {
                    msg = "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]";
                }
                storeLdapException(e, prc);
                throw new SenderException(msg, e);
            } finally {
                closeDirContext(dirContext);
            }
        }
    }

    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Update 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("Update value: ***");
                    } else {
                        log.debug("Update 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(entryNameAfter, DirContext.REPLACE_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    String msg;
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
                    // Sun:
                    //   [LDAP: error code 32 - No Such Object...
                    if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                        msg = "Operation [" + getOperation() + "] failed - wrong entryName [" + entryNameAfter
                                + "]";
                    } else {
                        msg = "Exception in operation [" + getOperation() + "] entryName [" + entryNameAfter
                                + "]";
                    }
                    //result = DEFAULT_RESULT_UPDATE_NOK;
                    storeLdapException(e, prc);
                    throw new SenderException(msg, e);
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            dirContext = getDirContext(paramValueMap);
            //dirContext.rename(newEntryName, oldEntryName);
            //result = DEFAULT_RESULT;
            dirContext.rename(entryName, entryName);
            return "<LdapResult>Deze functionaliteit is nog niet beschikbaar - naam niet veranderd.</LdapResult>";
        } catch (NamingException e) {
            // 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 - ")) {
                storeLdapException(e, prc);
                throw new SenderException(e);
            }
            return DEFAULT_RESULT_CREATE_NOK;
        } finally {
            closeDirContext(dirContext);
        }
    }
}

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

/**
 * Does a case-insensitive search for the given value in an attribute.
 *
 * @param attribute//  w  ww .j  a  v a 2 s  .c o  m
 *            the attribute
 * @param value
 *            the value to search for
 * @return <code>true</code>, if the value was found
 * @throws NamingException
 *             if there is a problem accessing the attribute values
 */
protected boolean hasAttributeValue(final Attribute attribute, final String value) throws NamingException {
    if (attribute != null) {
        final NamingEnumeration<?> values = attribute.getAll();
        while (values.hasMore()) {
            final Object mappedValue = this.mapAttributeValue(attribute.getID(), values.next());
            if (mappedValue instanceof String && value.equalsIgnoreCase((String) mappedValue)) {
                return true;
            }
        }
    }
    return false;
}

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

protected Collection<Object> mapAttribute(final Attribute attribute) throws NamingException {
    Collection<Object> values;
    if (attribute.isOrdered()) {
        values = new ArrayList<>();
    } else {/*from   www. ja  v a  2  s  .co  m*/
        values = new HashSet<>();
    }
    final NamingEnumeration<?> allAttributeValues = attribute.getAll();
    while (allAttributeValues.hasMore()) {
        final Object next = allAttributeValues.next();
        final Object mappedValue = this.mapAttributeValue(attribute.getID(), next);
        values.add(mappedValue);
    }

    LOGGER.debug("Mapped value of {} to {}", attribute, values);

    return values;
}

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

protected <T> Collection<T> mapAttribute(final Attribute attribute, final Class<T> expectedValueClass)
        throws NamingException {
    Collection<T> values;//from  w  w  w . j av  a2s.  c  om
    if (attribute.isOrdered()) {
        values = new ArrayList<>();
    } else {
        values = new HashSet<>();
    }
    final NamingEnumeration<?> allAttributeValues = attribute.getAll();
    while (allAttributeValues.hasMore()) {
        final Object next = allAttributeValues.next();
        final Object mappedValue = this.mapAttributeValue(attribute.getID(), next);
        final T value = DefaultTypeConverter.INSTANCE.convert(expectedValueClass, mappedValue);
        values.add(value);
    }

    LOGGER.debug("Mapped value of {} to {}", attribute, values);

    return values;
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * Check whether this is the last/only user in this group.
 *
 * @param userDN DN of the User.//w  ww .j a v  a 2s  .  co m
 * @param groupEntry SearchResult Representing the Group.
 * @return true if user is the only one in role, false otherwise.
 */
protected boolean isOnlyUserInRole(String userDN, SearchResult groupEntry) throws UserStoreException {
    boolean isOnlyUserInRole = false;
    try {
        Attributes groupAttributes = groupEntry.getAttributes();
        if (groupAttributes != null) {
            NamingEnumeration attributes = groupAttributes.getAll();
            while (attributes.hasMoreElements()) {
                Attribute memberAttribute = (Attribute) attributes.next();
                String memberAttributeName = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
                String attributeID = memberAttribute.getID();
                if (memberAttributeName.equals(attributeID)) {
                    if (memberAttribute.size() == 1 && userDN.equals(memberAttribute.get())) {
                        return true;
                    }
                }

            }

            attributes.close();

        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while looping through attributes set of group: "
                + groupEntry.getNameInNamespace();
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
    return isOnlyUserInRole;
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * Check whether user is in the group by searching through its member attributes.
 *
 * @param userDN DN of the User whose existence in the group is searched.
 * @param groupEntry SearchResult representation of the Group.
 * @return true if the user exists in the role, false otherwise.
 * @throws UserStoreException If an error occurs while retrieving data.
 *///  w  w  w.  j av  a  2s . c o m
protected boolean isUserInRole(String userDN, SearchResult groupEntry) throws UserStoreException {
    boolean isUserInRole = false;
    try {
        Attributes groupAttributes = groupEntry.getAttributes();
        if (groupAttributes != null) {
            // get group's returned attributes
            NamingEnumeration attributes = groupAttributes.getAll();
            // loop through attributes
            while (attributes.hasMoreElements()) {
                Attribute memberAttribute = (Attribute) attributes.next();
                String memberAttributeName = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
                if (memberAttributeName.equalsIgnoreCase(memberAttribute.getID())) {
                    // loop through attribute values
                    for (int i = 0; i < memberAttribute.size(); i++) {
                        if (userDN.equalsIgnoreCase((String) memberAttribute.get(i))) {
                            return true;
                        }
                    }
                }

            }
            attributes.close();
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while looping through attributes set of group: "
                + groupEntry.getNameInNamespace();
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
    return isUserInRole;
}