Example usage for javax.naming.directory ModificationItem getAttribute

List of usage examples for javax.naming.directory ModificationItem getAttribute

Introduction

In this page you can find the example usage for javax.naming.directory ModificationItem getAttribute.

Prototype

public Attribute getAttribute() 

Source Link

Document

Retrieves the attribute associated with this modification item.

Usage

From source file:com.springsource.insight.plugin.ldap.TestLdapContext.java

public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException {
    for (ModificationItem item : mods) {
        BasicAttributes attrs = new BasicAttributes();
        attrs.put(item.getAttribute());
        modifyAttributes(name, item.getModificationOp(), attrs);
    }/*from w  w  w  . j  ava 2s.c  o m*/
}

From source file:ca.tnt.ldaputils.impl.LdapEntry.java

/**
 * Runs the batch modifications requested through the {@link
 * ILdapEntry#modifyBatchAttribute(int, String, Object)}
 *//*w w w .ja v  a  2 s .com*/
public void modifyBatchAttributes(final String bindDN, final String bindPassword) { // BEGIN modifyBatchAttributes()
    DirContext ldapContext = null;

    if (modificationItems.size() == 0) {
        throw new IllegalStateException("No modification items for batch");
    }
    try {
        final Object[] tempModItems;
        final ModificationItem[] modItems;
        tempModItems = modificationItems.values().toArray();
        modItems = new ModificationItem[tempModItems.length];
        for (int index = 0; index < tempModItems.length; index++) { // convert to ModificationItem array
            modItems[index] = (ModificationItem) tempModItems[index];
        }

        ldapContext = manager.getConnection(bindDN, bindPassword);
        ldapContext.modifyAttributes(getDn(), modItems);

        /**
         * Update the attributes in memory
         */
        for (final ModificationItem modItem : modItems) {
            final Attribute attribute;
            attribute = modItem.getAttribute();
            updateAttribute(attribute.getID());
        }
        //            manager.reloadAttributes(this);
    } catch (NamingException namingException) {
        throw new LdapNamingException(namingException);
    } catch (Exception exception) {
        throw new LdapNamingException("error modifying attributes", exception);
    } finally {
        try {
            if (ldapContext != null) {
                ldapContext.close();
            }
        } catch (NamingException namingException) {
            manager.logNamingException(namingException);
        }

        // recreate empty batch list
        modificationItems = new LinkedHashMap();
    }
}

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

/**
 * Handle modify requests which attempt to delete the last value of the member or uniqueMember attribute of the
 * OpenLDAP groupOfNames and groupOfUniqueNames objectClass. If the modify request comprises one delete modification
 * of a reference attribute configured with an emptyValue, then first add a new reference whose ID is the empty
 * value before deleting the last value of the attribute.
 * //from   www  .  java 2  s. c o m
 * @param modifyRequest the modify request
 * @return the modified request suitable for retry or null if all preconditions are not met
 * 
 * @throws PspException if capability data in the request which must be understood is not understood
 */
protected ModifyRequest handleEmptyReferences(ModifyRequest modifyRequest) throws PspException {

    LOG.debug("Modify request before:\n{}", toXML(modifyRequest));

    // determine the pso definition name
    String entityName = modifyRequest.findOpenContentAttrValueByName(Pso.ENTITY_NAME_ATTRIBUTE);
    if (entityName == null) {
        LOG.error("Unable to determine entity " + PSPUtil.toString(modifyRequest));
        return null;
    }

    // the pso definition
    Pso psoDefinition = getPSP().getPso(getId(), entityName);
    if (psoDefinition == null) {
        LOG.error("Unable to determine provisioned object " + PSPUtil.toString(modifyRequest));
        return null;
    }

    // the original modification, should be a delete
    Modification[] modifications = modifyRequest.getModifications();
    if (modifications.length != 1) {
        LOG.debug("Only one modification is supported " + PSPUtil.toString(modifyRequest));
        return null;
    }
    Modification originalModification = modifications[0];
    if (!originalModification.getModificationMode().equals(ModificationMode.DELETE)) {
        LOG.debug("Only the delete modification mode is supported " + PSPUtil.toString(modifyRequest));
        return null;
    }

    // TODO exception

    // convert the modification into reference modifications
    List<ModificationItem> modificationItems = getReferenceMods(originalModification);
    if (modificationItems.size() != 1) {
        LOG.debug("Only one reference modification is supported " + PSPUtil.toString(modifyRequest));
        return null;
    }

    // the reference modification item
    ModificationItem modItem = modificationItems.get(0);

    // the references definition matching the reference modification
    PsoReferences refsDef = psoDefinition.getReferences(modItem.getAttribute().getID());
    if (refsDef == null) {
        LOG.debug("Unable to determine references definition " + PSPUtil.toString(modifyRequest));
        return null;
    }

    // the configured empty value
    String emptyValue = refsDef.getEmptyValue();
    if (emptyValue == null) {
        LOG.debug("An empty value is not configured for references definition '" + refsDef.getName() + "' "
                + PSPUtil.toString(modifyRequest));
        return null;
    }

    // a reference to the empty value
    Reference reference = new Reference();
    reference.setToPsoID(new PSOIdentifier(emptyValue, null, getId()));
    reference.setTypeOfReference(refsDef.getName());

    // a modification adding the reference to the empty value
    Modification newModification = new Modification();
    try {
        newModification.addCapabilityData(PSPUtil.fromReferences(Arrays.asList(new Reference[] { reference })));
    } catch (Spml2Exception e) {
        LOG.error("Unable to add reference capability data " + PSPUtil.toString(modifyRequest), e);
        return null;
    }
    newModification.setModificationMode(ModificationMode.ADD);

    // clear modifications, add the reference to the empty value, and then re-add the original modification
    modifyRequest.clearModifications();
    modifyRequest.addModification(newModification);
    modifyRequest.addModification(originalModification);

    LOG.debug("Modify request after:\n{}", toXML(modifyRequest));

    return modifyRequest;
}

From source file:ca.tnt.ldaputils.impl.LdapEntry.java

/**
 * Please note, the preferred method is to call setXXXX() where XXXX is the
 * attribute name, followed by save()./*from   w  ww.ja v  a2 s .  c o m*/
 * <p/>
 * This sets a batch attribute.  This means that it will be added to a queue
 * for changing LDAP.  You can modify the same attribute multiple times,
 * assuming LDAP supports multivalued attributes for that attribute. You are
 * then required to call modifyBatchAttributes(), which will actually do the
 * operations requested.
 * <p/>
 * You should call this one or more times per attribute, followed by
 * modifyBatchAttributes().
 * <p/>
 * Each time you call this method, for the same attribute, you should
 * specify the same operation, otherwise you will get an
 * IllegalArgumentException, with an appropriate error message.
 *
 * @param operation one of ADD_ATTRIBUTE, REPLACE_ATTRIBUTE,
 *                  REMOVE_ATTRIBUTE
 * @param attribute the name of the attribute
 * @param value     the value of the attribute
 *
 * @see #ADD_ATTRIBUTE ADD_ATTRIBUTE
 * @see #REPLACE_ATTRIBUTE REPLACE_ATTRIBUTE
 * @see #REMOVE_ATTRIBUTE REMOVE_ATTRIBUTE
 */
public void modifyBatchAttribute(final int operation, final String attribute, final Object value) {
    final Attribute newAttribute;
    ModificationItem modItem;
    final int mod_op;

    switch (operation) {
    case ADD_ATTRIBUTE:
        mod_op = DirContext.ADD_ATTRIBUTE;
        break;
    case REPLACE_ATTRIBUTE:
        mod_op = DirContext.REPLACE_ATTRIBUTE;
        break;
    case REMOVE_ATTRIBUTE:
        mod_op = DirContext.REMOVE_ATTRIBUTE;
        break;
    default:
        mod_op = DirContext.ADD_ATTRIBUTE;
    }

    modItem = (ModificationItem) modificationItems.get(attribute);
    if (modItem == null) { // first time we are doing something with this attribute
        newAttribute = new BasicAttribute(attribute, value);
        modItem = new ModificationItem(mod_op, newAttribute);
    } else { // we will add it to the attribute values for this attribute
        if (modItem.getModificationOp() != mod_op) { // make sure they aren't changing their mind on which op
            throw new IllegalArgumentException(
                    "error, operation does not match previous batch items for this attribute");
        }

        modItem.getAttribute().add(value);
    }
    modified = true;
    modificationItems.put(attribute, modItem);
}

From source file:org.apache.directory.studio.connection.core.io.api.DirectoryApiConnectionWrapper.java

/**
 * Converts modification items.//from w w  w.j  a va  2  s . c  o  m
 *
 * @param modificationItems
 *      an array of modification items
 * @return
 *      an array of converted modifications
 * @throws LdapInvalidAttributeValueException 
 */
private Modification[] convertModificationItems(ModificationItem[] modificationItems)
        throws LdapInvalidAttributeValueException {
    if (modificationItems != null) {
        List<Modification> modifications = new ArrayList<>();

        for (ModificationItem modificationItem : modificationItems) {
            Modification modification = new DefaultModification();

            modification.setAttribute(AttributeUtils.toApiAttribute(modificationItem.getAttribute()));
            modification.setOperation(convertModificationOperation(modificationItem.getModificationOp()));
            modifications.add(modification);
        }

        return modifications.toArray(new Modification[0]);
    } else {
        return null;
    }
}

From source file:org.fao.geonet.kernel.security.ldap.LdapUserDetailsManager.java

public void updateUser(UserDetails user) {
    DistinguishedName dn = usernameMapper.buildDn(user.getUsername());

    logger.debug("Updating user '" + user.getUsername() + "' with DN '" + dn + "'");

    List<GrantedAuthority> authorities = getUserAuthorities(dn, user.getUsername());

    DirContextAdapter ctx = loadUserAsContext(dn, user.getUsername());
    ctx.setUpdateMode(true);/*from  w  ww . j  ava 2 s. c  om*/
    copyToContext(user, ctx);

    // Remove the objectclass attribute from the list of mods (if present).
    List<ModificationItem> mods = new LinkedList<ModificationItem>(Arrays.asList(ctx.getModificationItems()));
    ListIterator<ModificationItem> modIt = mods.listIterator();

    while (modIt.hasNext()) {
        ModificationItem mod = (ModificationItem) modIt.next();
        Attribute a = mod.getAttribute();
        if ("objectclass".equalsIgnoreCase(a.getID())) {
            modIt.remove();
        }
    }

    template.modifyAttributes(dn, mods.toArray(new ModificationItem[mods.size()]));

    // template.rebind(dn, ctx, null);
    // Remove the old authorities and replace them with the new one
    removeAuthorities(dn, authorities);
    addAuthorities(dn, user.getAuthorities());
}

From source file:org.lsc.jndi.JndiServices.java

/**
 * Return the modificationItems in the javax.naming.directory.Attributes
 * format./*  w w w . ja  v  a 2 s  . c o m*/
 *
 * @param modificationItems
 *                the modification items list
 * @param forgetEmpty
 *                if specified, empty attributes will not be converted
 * @return the formatted attributes
 */
private Attributes getAttributes(final List<ModificationItem> modificationItems, final boolean forgetEmpty) {
    Attributes attrs = new BasicAttributes();
    for (ModificationItem mi : modificationItems) {
        if (!(forgetEmpty && mi.getAttribute().size() == 0)) {
            attrs.put(mi.getAttribute());
        }
    }
    return attrs;
}

From source file:org.projectforge.business.ldap.LdapDao.java

/**
 * @param ctx//from  w ww  .  j  a v  a 2 s .  co  m
 * @param ouBase If organizational units are given by the given obj then this parameter will be ignored, otherwise
 *          this is the ou where the new object will be inserted.
 * @param obj
 * @param args
 * @throws NamingException
 */
public void create(final DirContext ctx, final String ouBase, final T obj, final Object... args)
        throws NamingException {
    final String dn = buildDn(ouBase, obj);
    log.info("Create " + getObjectClass() + ": " + dn + ": " + getLogInfo(obj));
    final Attributes attrs = new BasicAttributes();
    final List<ModificationItem> modificationItems = getModificationItems(new ArrayList<ModificationItem>(),
            obj);
    modificationItems.add(createModificationItem(DirContext.ADD_ATTRIBUTE, "objectClass", getObjectClass()));
    final String[] additionalObjectClasses = getAdditionalObjectClasses(obj);
    if (additionalObjectClasses != null) {
        for (final String objectClass : additionalObjectClasses) {
            modificationItems.add(createModificationItem(DirContext.ADD_ATTRIBUTE, "objectClass", objectClass));
        }
    }
    for (final ModificationItem modItem : modificationItems) {
        final Attribute attr = modItem.getAttribute();
        LdapUtils.putAttribute(attrs, attr.getID(), (String) attr.get());
    }
    LdapUtils.putAttribute(attrs, "cn", LdapUtils.escapeCommonName(obj.getCommonName()));
    onBeforeBind(dn, attrs, args);
    ctx.bind(dn, null, attrs);
}

From source file:org.springframework.security.ldap.userdetails.LdapUserDetailsManager.java

public void updateUser(UserDetails user) {
    DistinguishedName dn = usernameMapper.buildDn(user.getUsername());

    logger.debug("Updating user '" + user.getUsername() + "' with DN '" + dn + "'");

    List<GrantedAuthority> authorities = getUserAuthorities(dn, user.getUsername());

    DirContextAdapter ctx = loadUserAsContext(dn, user.getUsername());
    ctx.setUpdateMode(true);//from   w  w w . j a  va 2 s .  co m
    copyToContext(user, ctx);

    // Remove the objectclass attribute from the list of mods (if present).
    List<ModificationItem> mods = new LinkedList<>(Arrays.asList(ctx.getModificationItems()));
    ListIterator<ModificationItem> modIt = mods.listIterator();

    while (modIt.hasNext()) {
        ModificationItem mod = (ModificationItem) modIt.next();
        Attribute a = mod.getAttribute();
        if ("objectclass".equalsIgnoreCase(a.getID())) {
            modIt.remove();
        }
    }

    template.modifyAttributes(dn, mods.toArray(new ModificationItem[mods.size()]));

    // template.rebind(dn, ctx, null);
    // Remove the old authorities and replace them with the new one
    removeAuthorities(dn, authorities);
    addAuthorities(dn, user.getAuthorities());
}