Example usage for javax.naming.directory Attribute add

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

Introduction

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

Prototype

boolean add(Object attrVal);

Source Link

Document

Adds a new value to the attribute.

Usage

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

/***************************************************************************
 * Collect all the values from the table (Arguments), using this create the
 * Attributes, this will create the Attributes for the User
 * defined TestCase for Add Test//  w  ww  .  j  av  a 2s  .com
 *
 * @return The Attributes
 **************************************************************************/
private Attributes getUserAttributes() {
    Attributes attrs = new BasicAttributes(true);
    Attribute attr;

    for (JMeterProperty jMeterProperty : getArguments()) {
        Argument item = (Argument) jMeterProperty.getObjectValue();
        attr = attrs.get(item.getName());
        if (attr == null) {
            attr = getBasicAttribute(item.getName(), item.getValue());
        } else {
            attr.add(item.getValue());
        }
        attrs.put(attr);
    }
    return attrs;
}

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

public void setAttributeValues(String name, Object[] values, boolean orderMatters) {
    Attribute a = new BasicAttribute(name, orderMatters);

    for (int i = 0; values != null && i < values.length; i++) {
        a.add(values[i]);
    }//  w w w . j  a va 2  s .  c o m

    // only change the original attribute if not in update mode
    if (!updateMode && values != null && values.length > 0) {
        // don't save empty arrays
        originalAttrs.put(a);
    }

    // possible to set an already existing attribute to an empty array
    if (updateMode && isChanged(name, values, orderMatters)) {
        updatedAttrs.put(a);
    }
}

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

public void addAttributeValue(String name, Object value, boolean addIfDuplicateExists) {
    if (!updateMode && value != null) {
        Attribute attr = originalAttrs.get(name);
        if (attr == null) {
            originalAttrs.put(name, value);
        } else {/*from   w w  w  . jav a2  s.co m*/
            attr.add(value);
        }
    } else if (updateMode) {
        Attribute attr = updatedAttrs.get(name);
        if (attr == null) {
            if (originalAttrs.get(name) == null) {
                // No match in the original attributes -
                // add a new Attribute to updatedAttrs
                updatedAttrs.put(name, value);
            } else {
                // The attribute exists in the original attributes - clone
                // that and add the new entry to it
                attr = (Attribute) originalAttrs.get(name).clone();
                if (addIfDuplicateExists || !attr.contains(value)) {
                    attr.add(value);
                }
                updatedAttrs.put(attr);
            }
        } else {
            attr.add(value);
        }
    }
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java

@Override
@SuppressWarnings("unchecked")
public void updateEntry(DocumentModel docModel) {
    checkPermission(SecurityConstants.WRITE);
    List<String> updateList = new ArrayList<String>();
    List<String> referenceFieldList = new LinkedList<String>();

    try {//from ww w  .j  ava  2  s.c om
        for (String fieldName : schemaFieldMap.keySet()) {
            if (!docModel.getPropertyObject(schemaName, fieldName).isDirty()) {
                continue;
            }
            if (getDirectory().isReference(fieldName)) {
                referenceFieldList.add(fieldName);
            } else {
                updateList.add(fieldName);
            }
        }

        if (!isReadOnlyEntry(docModel) && !updateList.isEmpty()) {
            Attributes attrs = new BasicAttributes();
            SearchResult ldapEntry = getLdapEntry(docModel.getId());
            if (ldapEntry == null) {
                throw new DirectoryException(docModel.getId() + " not found");
            }
            Attributes oldattrs = ldapEntry.getAttributes();
            String dn = ldapEntry.getNameInNamespace();
            Attributes attrsToDel = new BasicAttributes();
            for (String f : updateList) {
                Object value = docModel.getProperty(schemaName, f);
                String backendField = getDirectory().getFieldMapper().getBackendField(f);
                if (LDAPDirectory.DN_SPECIAL_ATTRIBUTE_KEY.equals(backendField)) {
                    // skip special LDAP DN field that is readonly
                    log.warn(String.format("field %s is mapped to read only DN field: ignored", f));
                    continue;
                }
                if (value == null || value.equals("")) {
                    Attribute objectClasses = oldattrs.get("objectClass");
                    Attribute attr;
                    if (getMandatoryAttributes(objectClasses).contains(backendField)) {
                        attr = new BasicAttribute(backendField);
                        // XXX: this might fail if the mandatory attribute
                        // is typed integer for instance
                        attr.add(" ");
                        attrs.put(attr);
                    } else if (oldattrs.get(backendField) != null) {
                        attr = new BasicAttribute(backendField);
                        attr.add(oldattrs.get(backendField).get());
                        attrsToDel.put(attr);
                    }
                } else if (f.equals(getPasswordField())) {
                    // The password has been updated, it has to be encrypted
                    Attribute attr = new BasicAttribute(backendField);
                    attr.add(PasswordHelper.hashPassword((String) value, passwordHashAlgorithm));
                    attrs.put(attr);
                } else {
                    attrs.put(getAttributeValue(f, value));
                }
            }

            if (log.isDebugEnabled()) {
                log.debug(String.format("LDAPSession.updateEntry(%s): LDAP modifyAttributes dn='%s' "
                        + "mod_op='REMOVE_ATTRIBUTE' attr='%s' [%s]", docModel, dn, attrsToDel, this));
            }
            dirContext.modifyAttributes(dn, DirContext.REMOVE_ATTRIBUTE, attrsToDel);

            if (log.isDebugEnabled()) {
                log.debug(String.format("LDAPSession.updateEntry(%s): LDAP modifyAttributes dn='%s' "
                        + "mod_op='REPLACE_ATTRIBUTE' attr='%s' [%s]", docModel, dn, attrs, this));
            }
            dirContext.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, attrs);
        }

        // update reference fields
        for (String referenceFieldName : referenceFieldList) {
            List<Reference> references = directory.getReferences(referenceFieldName);
            if (references.size() > 1) {
                // not supported
            } else {
                Reference reference = references.get(0);
                List<String> targetIds = (List<String>) docModel.getProperty(schemaName, referenceFieldName);
                reference.setTargetIdsForSource(docModel.getId(), targetIds);
            }
        }
    } catch (NamingException e) {
        handleException(e, "updateEntry failed:");
    }
    getDirectory().invalidateCaches();
}

From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java

/**
 * Converts spml modifications to jndi modifications.
 * //w w  w  . ja va  2s  .  com
 * @param modification the spml modification
 * @return the jndi modifications
 * @throws PspException if a psp error occurs
 */
protected List<ModificationItem> getDsmlMods(Modification modification) throws PspException {
    List<ModificationItem> mods = new ArrayList<ModificationItem>();

    for (Object object : modification.getOpenContentElements(DSMLModification.class)) {
        DSMLModification dsmlModification = (DSMLModification) object;

        Attribute attribute = new BasicAttribute(dsmlModification.getName());

        DSMLValue[] dsmlValues = dsmlModification.getValues();
        for (DSMLValue dsmlValue : dsmlValues) {
            // for example, when <dsmlValue><dsmlValue/> and op is a replace
            if (!DatatypeHelper.isEmpty(dsmlValue.getValue())) {
                attribute.add(dsmlValue.getValue());
            }
        }

        int op = -1;
        if (dsmlModification.getOperation().equals(ModificationMode.ADD)) {
            op = DirContext.ADD_ATTRIBUTE;
        } else if (dsmlModification.getOperation().equals(ModificationMode.DELETE)) {
            op = DirContext.REMOVE_ATTRIBUTE;
        } else if (dsmlModification.getOperation().equals(ModificationMode.REPLACE)) {
            op = DirContext.REPLACE_ATTRIBUTE;
        } else {
            throw new PspException("Unknown dsml modification operation : " + dsmlModification.getOperation());
        }

        mods.add(new ModificationItem(op, attribute));
    }

    return mods;
}

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);
        }/*  ww  w  .j ava  2s .  co  m*/
    }

    // 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.nuxeo.ecm.directory.ldap.LDAPSession.java

@SuppressWarnings("unchecked")
protected Attribute getAttributeValue(String fieldName, Object value) throws DirectoryException {
    Attribute attribute = new BasicAttribute(getDirectory().getFieldMapper().getBackendField(fieldName));
    Field field = schemaFieldMap.get(fieldName);
    if (field == null) {
        String message = String.format("Invalid field name '%s' for directory '%s' with schema '%s'", fieldName,
                directory.getName(), directory.getSchema());
        throw new DirectoryException(message);
    }//from w w  w.j a  va 2s  . co m
    Type type = field.getType();
    String typeName = type.getName();

    if ("string".equals(typeName)) {
        attribute.add(value);
    } else if ("integer".equals(typeName) || "long".equals(typeName)) {
        attribute.add(value.toString());
    } else if (type.isListType()) {
        Collection<String> valueItems;
        if (value instanceof String[]) {
            valueItems = Arrays.asList((String[]) value);
        } else if (value instanceof Collection) {
            valueItems = (Collection<String>) value;
        } else {
            throw new DirectoryException(String.format("field %s with value %s does not match type %s",
                    fieldName, value.toString(), type.getName()));
        }
        for (String item : valueItems) {
            attribute.add(item);
        }
    } else if ("date".equals(typeName)) {
        Calendar cal = (Calendar) value;
        Date date = cal.getTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
        dateFormat.setTimeZone(new SimpleTimeZone(0, "Z"));
        attribute.add(dateFormat.format(date));
    } else if ("content".equals(typeName)) {
        try {
            attribute.add(((Blob) value).getByteArray());
        } catch (IOException e) {
            throw new DirectoryException("Failed to get ByteArray value", e);
        }
    } else {
        throw new DirectoryException("Field type not supported in directories: " + typeName);
    }

    return attribute;
}

From source file:openscim.restful.server.resources.group.ldap.LdapGroupResource.java

@Override
public Response createGroup(UriInfo uriInfo, Group group) {
    // check the ldap template has been setup correctly
    if (ldapTemplate != null) {
        // create the mapper if it doesn't already exists
        if (mapper == null)
            mapper = new GroupAttributesMapper(properties);

        // build the group dn
        String dn = group.getId();
        if (properties
                .getProperty(GroupAttributesMapper.CONCEAL_GROUP_DNS,
                        GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)
                .equalsIgnoreCase(GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)) {
            // utilise ldap formated dn
            dn = properties.getProperty(GroupAttributesMapper.GID_ATTRIBUTE,
                    GroupAttributesMapper.DEFAULT_GID_ATTRIBUTE) + "=" + group.getId() + ","
                    + properties.getProperty(GroupAttributesMapper.GROUP_BASEDN,
                            GroupAttributesMapper.DEFAULT_GROUP_BASEDN);
        }//from   w w  w .java 2s.  co m

        try {
            try {
                // retrieve the group
                Group lookedGroup = (Group) ldapTemplate.lookup(dn, mapper);

                // check if the group was found
                if (lookedGroup != null) {
                    // user already exists            
                    return ResourceUtilities.buildErrorResponse(HttpStatus.CONFLICT,
                            HttpStatus.CONFLICT.getMessage() + ": Resource " + dn + " already exists");
                }
            } catch (Exception nException) {
                // group not found, do nothing
            }

            Attributes groupAttributes = new BasicAttributes();

            // get the objectclasses
            String objectclasses = properties.getProperty(GroupAttributesMapper.GROUP_OBJECTCLASS_ATTRIBUTE,
                    GroupAttributesMapper.DEFAULT_GROUP_OBJECTCLASS_ATTRIBUTE);

            // set the objectclass of the group
            Scanner scanner = new Scanner(objectclasses);
            scanner.useDelimiter(",");
            while (scanner.hasNext()) {
                groupAttributes.put("objectclass", scanner.next());
            }

            // set the gid
            String gidAtttributeName = properties.getProperty(GroupAttributesMapper.GID_ATTRIBUTE,
                    GroupAttributesMapper.DEFAULT_GID_ATTRIBUTE);
            groupAttributes.put(gidAtttributeName, group.getId());

            // get the member attribute name
            String memberAtttributeName = properties.getProperty(GroupAttributesMapper.MEMBER_ATTRIBUTE,
                    GroupAttributesMapper.DEFAULT_MEMBER_ATTRIBUTE);

            // set the members
            Attribute memberAttribute = new BasicAttribute(memberAtttributeName);
            if (group.getAny() instanceof List) {
                List members = (List) group.getAny();
                for (Object object : members) {
                    if (object instanceof PluralAttribute) {
                        PluralAttribute member = (PluralAttribute) object;
                        String uid = member.getValue();

                        // build the user dn
                        String userdn = uid;
                        if (properties.getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS, "true")
                                .equalsIgnoreCase("true")) {
                            // utilise ldap formated dn
                            userdn = properties.getProperty(UserAttributesMapper.UID_ATTRIBUTE,
                                    UserAttributesMapper.DEFAULT_UID_ATTRIBUTE) + "=" + uid + ","
                                    + properties.getProperty(UserAttributesMapper.ACCOUNT_BASEDN,
                                            UserAttributesMapper.DEFAULT_ACCOUNT_BASEDN);
                        }

                        memberAttribute.add(userdn);
                    }
                }
            }
            groupAttributes.put(memberAttribute);

            // create the group
            ldapTemplate.bind(dn, null, groupAttributes);

            // determine the url of the new resource
            URI location = new URI("/Group/" + dn);
            if (properties
                    .getProperty(GroupAttributesMapper.CONCEAL_GROUP_DNS,
                            GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)
                    .equalsIgnoreCase(GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)) {
                location = new URI("/User/" + group.getId());
            }

            // group stored successfully, return the group            
            return Response.created(location).entity(group).build();
        } catch (URISyntaxException usException) {
            // problem generating entity location
            logger.error("problem generating entity location");

            // return a server error
            return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR,
                    HttpStatus.NOT_IMPLEMENTED.getMessage()
                            + ": Service Provider problem generating entity location");
        } catch (Exception nException) {
            // problem creating group
            logger.error("problem creating group");

            // return a server error
            return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR,
                    HttpStatus.NOT_IMPLEMENTED.getMessage() + ": Service Provider problem creating group");
        }
    } else {
        // ldap not configured
        logger.error("ldap not configured");

        // return a server error
        return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR,
                HttpStatus.NOT_IMPLEMENTED.getMessage()
                        + ": Service Provider group ldap repository not configured");
    }
}

From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java

@Override
public void doSetUserClaimValue(String userName, String claimURI, String value, String profileName)
        throws UserStoreException {
    // get the LDAP Directory context
    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // search the relevant user entry by user name
    String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(null);

    NamingEnumeration<SearchResult> returnedResultList = null;
    String returnedUserEntry = null;

    try {//from  w  w w. j  a  va 2 s .c  o  m

        returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter,
                searchControls);
        // assume only one user is returned from the search
        // TODO:what if more than one user is returned
        returnedUserEntry = returnedResultList.next().getName();
    } catch (NamingException e) {
        String errorMessage = "Results could not be retrieved from the directory context for user : "
                + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(returnedResultList);
    }

    try {
        Attributes updatedAttributes = new BasicAttributes(true);
        // if there is no attribute for profile configuration in LDAP, skip
        // updating it.
        // get the claimMapping related to this claimURI
        String attributeName = getClaimAtrribute(claimURI, userName, null);

        if ("CN".equals(attributeName)) {
            subDirContext = (DirContext) dirContext.lookup(userSearchBase);
            subDirContext.rename(returnedUserEntry, "CN=" + value);
            return;
        }

        Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);
        /* if updated attribute value is null, remove its values. */
        if (EMPTY_ATTRIBUTE_STRING.equals(value)) {
            currentUpdatedAttribute.clear();
        } else {
            String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR);
            if (claimSeparator != null && !claimSeparator.trim().isEmpty()) {
                userAttributeSeparator = claimSeparator;
            }
            if (value.contains(userAttributeSeparator)) {
                StringTokenizer st = new StringTokenizer(value, userAttributeSeparator);
                while (st.hasMoreElements()) {
                    String newVal = st.nextElement().toString();
                    if (newVal != null && newVal.trim().length() > 0) {
                        currentUpdatedAttribute.add(newVal.trim());
                    }
                }
            } else {
                currentUpdatedAttribute.add(value);
            }
        }
        updatedAttributes.put(currentUpdatedAttribute);

        // update the attributes in the relevant entry of the directory
        // store

        subDirContext = (DirContext) dirContext.lookup(userSearchBase);
        subDirContext.modifyAttributes(returnedUserEntry, DirContext.REPLACE_ATTRIBUTE, updatedAttributes);

    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        String errorMessage = "Error in obtaining claim mapping for user : " + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } catch (NamingException e) {
        handleException(e, userName);
    } finally {
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }

}

From source file:openscim.restful.server.resources.group.ldap.LdapGroupResource.java

@Override
public Response updateGroup(UriInfo uriInfo, String gid, Group group) {
    // check the ldap template has been setup correctly
    if (ldapTemplate != null) {
        // create the mapper if it doesn't already exists
        if (mapper == null)
            mapper = new GroupAttributesMapper(properties);

        // build the group dn
        String dn = gid;/*  w ww.  ja v a  2s  . c o m*/
        if (properties
                .getProperty(GroupAttributesMapper.CONCEAL_GROUP_DNS,
                        GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)
                .equalsIgnoreCase(GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)) {
            // utilise ldap formated dn
            dn = properties.getProperty(GroupAttributesMapper.GID_ATTRIBUTE,
                    GroupAttributesMapper.DEFAULT_GID_ATTRIBUTE) + "=" + gid + ","
                    + properties.getProperty(GroupAttributesMapper.GROUP_BASEDN,
                            GroupAttributesMapper.DEFAULT_GROUP_BASEDN);
        }

        try {
            // retrieve the group
            Group lookedupGroup = (Group) ldapTemplate.lookup(dn, mapper);

            // check if the group was found
            if (lookedupGroup == null) {
                // user not found, return an error message
                return ResourceUtilities.buildErrorResponse(HttpStatus.NOT_FOUND,
                        "Resource " + dn + " not found");
            }

            List<ModificationItem> items = new ArrayList<ModificationItem>();

            // build a gid modification
            //if(group.getId() != null)
            //{
            //   // get the gid attribute name
            //   String gidAtttributeName = GroupAttributesMapper.DEFAULT_GID_ATTRIBUTE;
            //   if(properties.containsKey(GroupAttributesMapper.GID_ATTRIBUTE)) gidAtttributeName = properties.getProperty(GroupAttributesMapper.GID_ATTRIBUTE);
            //   
            //   Attribute uidAttribute = new BasicAttribute(gidAtttributeName, group.getId());            
            //   ModificationItem uidItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, uidAttribute);
            //   items.add(uidItem);
            //}

            // get the member attribute name
            String memberAtttributeName = properties.getProperty(GroupAttributesMapper.MEMBER_ATTRIBUTE,
                    GroupAttributesMapper.DEFAULT_MEMBER_ATTRIBUTE);

            // set the members
            if (group.getAny() instanceof List) {
                List members = (List) group.getAny();
                Attribute memberAttribute = new BasicAttribute(memberAtttributeName);
                for (Object object : members) {
                    if (object instanceof PluralAttribute) {
                        PluralAttribute member = (PluralAttribute) object;
                        String uid = member.getValue();

                        // build the user dn
                        String userdn = uid;
                        if (properties
                                .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS,
                                        UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)
                                .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) {
                            // utilise ldap formated dn
                            userdn = properties.getProperty(UserAttributesMapper.UID_ATTRIBUTE,
                                    UserAttributesMapper.DEFAULT_UID_ATTRIBUTE) + "=" + uid + ","
                                    + properties.getProperty(UserAttributesMapper.ACCOUNT_BASEDN,
                                            UserAttributesMapper.DEFAULT_ACCOUNT_BASEDN);
                        }

                        memberAttribute.add(userdn);
                    }
                }
                ModificationItem memberItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                        memberAttribute);
                items.add(memberItem);
            }

            // update the user password
            ModificationItem[] itemsArray = items.toArray(new ModificationItem[items.size()]);
            ldapTemplate.modifyAttributes(dn, itemsArray);

            // password changed successfully
            return Response.status(HttpStatus.NO_CONTENT.getCode()).build();
        } catch (Exception nException) {
            logger.debug("Resource " + dn + " not found");
            logger.debug(nException);

            // group not found, return an error message
            return ResourceUtilities.buildErrorResponse(HttpStatus.NOT_FOUND, "Resource " + dn + " not found");
        }
    } else {
        // ldap not configured
        logger.error("ldap not configured");

        // return a server error
        return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR,
                HttpStatus.NOT_IMPLEMENTED.getMessage()
                        + ": Service Provider group ldap repository not configured");
    }
}