Java Code Examples for javax.naming.directory.DirContext#REMOVE_ATTRIBUTE

The following examples show how to use javax.naming.directory.DirContext#REMOVE_ATTRIBUTE . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ModifyAttributesOperationRecorderTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCompensatingModificationItem_RemoveFullExistingAttribute()
        throws NamingException {
    BasicAttribute attribute = new BasicAttribute("someattr");
    attribute.add("value1");
    attribute.add("value2");
    Attributes attributes = new BasicAttributes();
    attributes.put(attribute);

    ModificationItem originalItem = new ModificationItem(
            DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("someattr"));

    // Perform test
    ModificationItem result = tested.getCompensatingModificationItem(
            attributes, originalItem);

    // Verify result
    assertThat(result.getModificationOp()).isEqualTo(DirContext.ADD_ATTRIBUTE);
    Attribute resultAttribute = result.getAttribute();
    assertThat(resultAttribute.getID()).isEqualTo("someattr");
    Object object = resultAttribute.get(0);
    assertThat(object).isEqualTo("value1");
    assertThat(resultAttribute.get(1)).isEqualTo("value2");
}
 
Example 2
Source File: ApacheKDCServer.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private void enableKerberoseSchema() throws DirectoryServerException {
    // check if krb5kdc is disabled
    Attributes krb5kdcAttrs;
    try {
        krb5kdcAttrs = schemaRoot.getAttributes("cn=Krb5kdc");

        boolean isKrb5KdcDisabled = false;
        if (krb5kdcAttrs.get("m-disabled") != null) {
            isKrb5KdcDisabled = "TRUE".equalsIgnoreCase((String) krb5kdcAttrs.get("m-disabled").get());
        }

        // if krb5kdc is disabled then enable it
        if (isKrb5KdcDisabled) {
            Attribute disabled = new BasicAttribute("m-disabled");
            ModificationItem[] mods =
                    new ModificationItem[]{new ModificationItem(
                            DirContext.REMOVE_ATTRIBUTE, disabled)};
            schemaRoot.modifyAttributes("cn=Krb5kdc", mods);
        }
    } catch (NamingException e) {
        String msg = "An error occurred while enabling Kerberos schema.";
        logger.error(msg, e);
        throw new DirectoryServerException(msg, e);
    }
}
 
Example 3
Source File: Group2Ldap.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public boolean deleteMember(GroupMember groupMember)  throws Exception{
	try {
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(cn="+groupMember.getGroupName()+")", constraints);
		if (results == null || !results.hasMore()) {
			return true;
		}
		
		String uniqueMember="uid="+groupMember.getMemberName()+",dc=users,"+ldapUtils.getBaseDN();
		ModificationItem[] modificationItems = new ModificationItem[1];
		modificationItems[0]=new ModificationItem(DirContext.REMOVE_ATTRIBUTE,new BasicAttribute("uniqueMember",uniqueMember));
		
		String dn="cn="+groupMember.getGroupName()+",dc=groups,"+ldapUtils.getBaseDN();
		logger.debug("dn : "+dn);
		logger.debug("uniqueMember : "+uniqueMember);
		ldapUtils.getCtx().modifyAttributes(dn, modificationItems);
		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return true;
}
 
Example 4
Source File: ldapConnection.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public void modify() throws AttributeModificationException, NamingException{
  //Get a reference to a directory context
  int modType;
  // decode the modification type to one which the context will understand
  switch (modifyType){
    case ldapConnection.MODIFY_REPLACE: // attributes require name=value pairs
      modType = DirContext.REPLACE_ATTRIBUTE;
      break;
    
    case ldapConnection.MODIFY_ADD:
      modType = DirContext.ADD_ATTRIBUTE; // attributes require name=value pairs
      break;

    case ldapConnection.MODIFY_DELETE:
      modType = DirContext.REMOVE_ATTRIBUTE; // attributes require names only
      break;
    default:
      modType = DirContext.REPLACE_ATTRIBUTE;

  }// switch

  DirContext ctx = new InitialDirContext(env);
  Attributes attributes = processAttributes();
  ctx.modifyAttributes(dn, modType, attributes);
  ctx.close();

}
 
Example 5
Source File: ModifyAttributesOperationRecorderTest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetCompensatingModificationItem_RemoveTwoAttributeValues()
        throws NamingException {
    BasicAttribute attribute = new BasicAttribute("someattr");
    attribute.add("value1");
    attribute.add("value2");
    attribute.add("value3");
    Attributes attributes = new BasicAttributes();
    attributes.put(attribute);

    BasicAttribute modificationAttribute = new BasicAttribute("someattr");
    modificationAttribute.add("value1");
    modificationAttribute.add("value2");
    ModificationItem originalItem = new ModificationItem(
            DirContext.REMOVE_ATTRIBUTE, modificationAttribute);

    // Perform test
    ModificationItem result = tested.getCompensatingModificationItem(
            attributes, originalItem);

    // Verify result
    assertThat(result.getModificationOp()).isEqualTo(DirContext.ADD_ATTRIBUTE);
    Attribute resultAttribute = result.getAttribute();
    assertThat(resultAttribute.getID()).isEqualTo("someattr");
    Object object = resultAttribute.get(0);
    assertThat(object).isEqualTo("value1");
    assertThat(resultAttribute.get(1)).isEqualTo("value2");
}
 
Example 6
Source File: LdapSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
private String performOperationChangeUnicodePwd(String entryName, IPipeLineSession session, Map paramValueMap) throws SenderException, ParameterException {
	ModificationItem[] modificationItems = new ModificationItem[2];
	modificationItems[0] = new ModificationItem(
			DirContext.REMOVE_ATTRIBUTE,
			new BasicAttribute("unicodePwd", encodeUnicodePwd(paramValueMap.get("oldPassword"))));
	modificationItems[1] = new ModificationItem(
			DirContext.ADD_ATTRIBUTE,
			new BasicAttribute("unicodePwd", encodeUnicodePwd(paramValueMap.get("newPassword"))));
	DirContext dirContext = null;
	try{
		dirContext = getDirContext(paramValueMap);
		dirContext.modifyAttributes(entryName, modificationItems);
		return DEFAULT_RESULT_CHANGE_UNICODE_PWD_OK;
	} catch(NamingException e) {
		// https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
		//   19 LDAP_CONSTRAINT_VIOLATION Indicates that the attribute value specified in a modify, add, or modify DN operation violates constraints placed on the attribute. The constraint can be one of size or content (string only, no binary).
		// AD:
		//   [LDAP: error code 19 - 0000052D: AtrErr: DSID-03191041, #1...
		if(e.getMessage().startsWith("[LDAP: error code 19 - ") ) {
			if (log.isDebugEnabled()) log.debug("Operation [" + getOperation()+ "] old password doesn't match or new password doesn't comply with policy for: " + entryName);
			return DEFAULT_RESULT_CHANGE_UNICODE_PWD_NOK;
		} else {
			storeLdapException(e, session);
			throw new SenderException("Exception in operation [" + getOperation()+ "] entryName ["+entryName+"]", e);
		}
	} finally {
		closeDirContext(dirContext);
	}
}
 
Example 7
Source File: ServerEntryUtils.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a ModificationItem to an instance of a ServerModification object
 *
 * @param modificationImpl the modification instance to convert
 * @param attributeType the associated attributeType
 * @return a instance of a ServerModification object
 */
private static Modification toServerModification( ModificationItem modificationImpl, AttributeType attributeType )
    throws LdapException
{
    ModificationOperation operation;

    switch ( modificationImpl.getModificationOp() )
    {
        case DirContext.REMOVE_ATTRIBUTE:
            operation = ModificationOperation.REMOVE_ATTRIBUTE;
            break;

        case DirContext.REPLACE_ATTRIBUTE:
            operation = ModificationOperation.REPLACE_ATTRIBUTE;
            break;

        case DirContext.ADD_ATTRIBUTE:
        default:
            operation = ModificationOperation.ADD_ATTRIBUTE;
            break;

    }

    Modification modification = new DefaultModification(
        operation,
        ServerEntryUtils.toServerAttribute( modificationImpl.getAttribute(), attributeType ) );

    return modification;

}
 
Example 8
Source File: LDAPUserStoreManager.java    From msf4j with Apache License 2.0 5 votes vote down vote up
public void removeUser(String username, String groupName) throws NamingException {

        try {
            ModificationItem[] mods = new ModificationItem[1];
            Attribute mod = new BasicAttribute("member", getUserDN(username));
            mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, mod);
            context.modifyAttributes(getGroupDN(groupName), mods);
        } catch (NoSuchAttributeException e) {
            // If user is not assigned, ignore the error
        }
    }
 
Example 9
Source File: JNDIProviderImpl.java    From ldapchai with GNU Lesser General Public License v2.1 5 votes vote down vote up
@LdapOperation
@ModifyOperation
public final void replaceStringAttribute( final String entryDN, final String attributeName, final String oldValue, final String newValue )
        throws ChaiUnavailableException, ChaiOperationException
{
    activityPreCheck();
    getInputValidator().replaceStringAttribute( entryDN, attributeName, oldValue, newValue );

    // Create the ModificationItem
    final ModificationItem[] mods = new ModificationItem[2];

    // Mark the flag to remover the existing attribute.
    mods[0] = new ModificationItem( DirContext.REMOVE_ATTRIBUTE, new BasicAttribute( attributeName, oldValue ) );

    // Mark the flag to add the new attribute
    mods[1] = new ModificationItem( DirContext.ADD_ATTRIBUTE, new BasicAttribute( attributeName, newValue ) );

    // get ldap connection
    final LdapContext ldapConnection = getLdapConnection();

    // Modify the Attributes.
    try
    {
        ldapConnection.modifyAttributes( addJndiEscape( entryDN ), mods );
    }
    catch ( NamingException e )
    {
        convertNamingException( e );
    }
}
 
Example 10
Source File: JNDIProviderImpl.java    From ldapchai with GNU Lesser General Public License v2.1 5 votes vote down vote up
@LdapOperation
@ModifyOperation
public final void deleteStringAttributeValue( final String entryDN, final String attributeName, final String attributeValue )
        throws ChaiUnavailableException, ChaiOperationException
{
    activityPreCheck();
    getInputValidator().deleteStringAttributeValue( entryDN, attributeName, attributeValue );

    // Create a BasicAttribute for the object.
    final BasicAttribute attributeToReplace = new BasicAttribute( attributeName, attributeValue );

    // Create the ModificationItem
    final ModificationItem[] modificationItem = new ModificationItem[1];

    // Populate the ModificationItem object with the flag & the attribute to replace.
    modificationItem[0] = new ModificationItem( DirContext.REMOVE_ATTRIBUTE, attributeToReplace );

    // Modify the Attributes.
    final LdapContext ldapConnection = getLdapConnection();
    try
    {
        ldapConnection.modifyAttributes( addJndiEscape( entryDN ), modificationItem );
    }
    catch ( NamingException e )
    {
        convertNamingException( e );
    }
}
 
Example 11
Source File: Group2Ldap.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public boolean update(Groups group)  throws Exception{
	logger.info("update");
	try {
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(cn="+group.getName()+")", constraints);
		String oldDn="";
		String rdn="";
		if (results == null || !results.hasMore()) {
			return create(group);
		}else{
			SearchResult sr = (SearchResult) results.next();
			oldDn =sr.getNameInNamespace();
			String[] dnSplit=oldDn.split(",");
			rdn=oldDn.substring(oldDn.indexOf(","), oldDn.length());
			
			String groupName=dnSplit[0].split("=")[1];
			if(group.getName()!=groupName){
				String newDn="cn="+group.getName()+","+rdn;
				ldapUtils.getCtx().rename(oldDn, newDn);
				ModificationItem[] modificationItems = new ModificationItem[1];
				modificationItems[0]=new ModificationItem(DirContext.REMOVE_ATTRIBUTE,new BasicAttribute("cn",groupName));
				ldapUtils.getCtx().modifyAttributes(newDn, modificationItems);
			}
		}
		
		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return true;
}
 
Example 12
Source File: Organization2Ldap.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public boolean update(Organizations organization)  throws Exception{
	logger.info("update");
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(&(objectClass=organizationalUnit)(description="+organization.getId()+"))", constraints);
		String oldDn="";
		String rdn="";
		if (results == null || !results.hasMore()) {
			return create(organization);
		}else{
			SearchResult sr = (SearchResult) results.next();
			oldDn =sr.getNameInNamespace();
			String[] dnSplit=oldDn.split(",");
			rdn=oldDn.substring(oldDn.indexOf(",")+1, oldDn.length());
			
			String ouName=dnSplit[0].split("=")[1];
			if(organization.getName()!=ouName){
				String newDn="ou="+organization.getName()+","+rdn;
				logger.debug("oldDn : "+oldDn);
				logger.debug("newDn : "+newDn);
				ldapUtils.getCtx().rename(oldDn, newDn);
				ModificationItem[] modificationItems = new ModificationItem[1];
				modificationItems[0]=new ModificationItem(DirContext.REMOVE_ATTRIBUTE,new BasicAttribute("ou",ouName));
				//modificationItems[1]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("name",organization.getName()));
				//modificationItems[2]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("id",organization.getId()));
				//modificationItems[3]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("porgname",organization.getpName()));
				//modificationItems[4]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("porgid",organization.getpId()));
				ldapUtils.getCtx().modifyAttributes(newDn, modificationItems);
			}
		}
		
		ldapUtils.close();
	
	return super.update(organization);
}
 
Example 13
Source File: Group2Activedirectory.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public boolean deleteMember(GroupMember groupMember)  throws Exception{
	try {
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(cn="+groupMember.getGroupName()+")", constraints);
		if (results == null || !results.hasMore()) {
			return true;
		}
		
		String uniqueMember="";
		SearchControls memberSearchControls = new SearchControls();
		memberSearchControls.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> memberResults = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(sAMAccountName="+groupMember.getMemberName()+")", memberSearchControls);
		if (memberResults == null || !memberResults.hasMore()) {
			
		}else{
			SearchResult memberSr = (SearchResult) memberResults.next();
			uniqueMember =memberSr.getNameInNamespace();
			logger.debug("uniqueMember : "+uniqueMember);
			ModificationItem[] modificationItems = new ModificationItem[1];
			modificationItems[0]=new ModificationItem(DirContext.REMOVE_ATTRIBUTE,new BasicAttribute("member",uniqueMember));
			
			String dn="cn="+groupMember.getGroupName()+",cn=groups,"+ldapUtils.getBaseDN();
			
			ldapUtils.getCtx().modifyAttributes(dn, modificationItems);
		}

		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return true;
}
 
Example 14
Source File: Group2Activedirectory.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public boolean update(Groups group)  throws Exception{
	logger.info("update");
	try {
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(cn="+group.getName()+")", constraints);
		String oldDn="";
		String rdn="";
		if (results == null || !results.hasMore()) {
			return create(group);
		}else{
			SearchResult sr = (SearchResult) results.next();
			oldDn =sr.getNameInNamespace();
			String[] dnSplit=oldDn.split(",");
			rdn=oldDn.substring(oldDn.indexOf(","), oldDn.length());
			
			String groupName=dnSplit[0].split("=")[1];
			if(group.getName()!=groupName){
				String newDn="cn="+group.getName()+","+rdn;
				ldapUtils.getCtx().rename(oldDn, newDn);
				ModificationItem[] modificationItems = new ModificationItem[1];
				modificationItems[0]=new ModificationItem(DirContext.REMOVE_ATTRIBUTE,new BasicAttribute("cn",groupName));
				ldapUtils.getCtx().modifyAttributes(newDn, modificationItems);
			}
		}
		
		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return true;
}
 
Example 15
Source File: ServerEntryUtils.java    From MyVirtualDirectory with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a ModificationItem to an instance of a ServerModification object
 *
 * @param modificationImpl the modification instance to convert
 * @param attributeType the associated attributeType
 * @return a instance of a ServerModification object
 */
private static Modification toServerModification( ModificationItem modificationImpl, AttributeType attributeType )
    throws LdapException
{
    ModificationOperation operation;

    switch ( modificationImpl.getModificationOp() )
    {
        case DirContext.REMOVE_ATTRIBUTE:
            operation = ModificationOperation.REMOVE_ATTRIBUTE;
            break;

        case DirContext.REPLACE_ATTRIBUTE:
            operation = ModificationOperation.REPLACE_ATTRIBUTE;
            break;

        case DirContext.ADD_ATTRIBUTE:
        default:
            operation = ModificationOperation.ADD_ATTRIBUTE;
            break;

    }

    Modification modification = new DefaultModification(
        operation,
        ServerEntryUtils.toServerAttribute( modificationImpl.getAttribute(), attributeType ) );

    return modification;

}
 
Example 16
Source File: LdifReader.java    From scriptella-etl with Apache License 2.0 4 votes vote down vote up
/**
 * Parse a modify change type.
 * <p/>
 * The grammar is : <changerecord> ::= "changetype:" FILL "modify" SEP
 * <mod-spec> <mod-specs-e> <mod-spec> ::= "add:" <mod-val> | "delete:"
 * <mod-val-del> | "replace:" <mod-val> <mod-specs-e> ::= <mod-spec>
 * <mod-specs-e> | e <mod-val> ::= FILL ATTRIBUTE-DESCRIPTION SEP
 * ATTRVAL-SPEC <attrval-specs-e> "-" SEP <mod-val-del> ::= FILL
 * ATTRIBUTE-DESCRIPTION SEP <attrval-specs-e> "-" SEP <attrval-specs-e> ::=
 * ATTRVAL-SPEC <attrval-specs> | e *
 *
 * @param entry The entry to feed
 * @param iter  The lines
 */
private void parseModify(Entry entry, Iterator iter) {
    int state = MOD_SPEC;
    String modified = null;
    int modification = 0;

    // The following flag is used to deal with empty modifications
    boolean isEmptyValue = true;

    while (iter.hasNext()) {
        String line = (String) iter.next();
        String lowerLine = line.toLowerCase();

        if (lowerLine.startsWith("-")) {
            if (state != ATTRVAL_SPEC_OR_SEP) {
                throw new LdifParseException("Bad modify separator", line);
            } else {
                if (isEmptyValue) {
                    // Update the entry
                    entry.addModificationItem(modification, modified, null);
                }

                state = MOD_SPEC;
                isEmptyValue = true;
                continue;
            }
        } else if (lowerLine.startsWith("add:")) {
            if ((state != MOD_SPEC) && (state != ATTRVAL_SPEC)) {
                throw new LdifParseException("Bad modify state", line);
            }

            modified = line.substring("add:".length()).trim();
            modification = DirContext.ADD_ATTRIBUTE;

            state = ATTRVAL_SPEC;
        } else if (lowerLine.startsWith("delete:")) {
            if ((state != MOD_SPEC) && (state != ATTRVAL_SPEC)) {
                throw new LdifParseException("Bad modify state", line);
            }

            modified = line.substring("delete:".length()).trim();
            modification = DirContext.REMOVE_ATTRIBUTE;

            state = ATTRVAL_SPEC_OR_SEP;
        } else if (lowerLine.startsWith("replace:")) {
            if ((state != MOD_SPEC) && (state != ATTRVAL_SPEC)) {
                throw new LdifParseException("Bad modify state", line);
            }

            modified = line.substring("replace:".length()).trim();
            modification = DirContext.REPLACE_ATTRIBUTE;

            state = ATTRVAL_SPEC_OR_SEP;
        } else {
            if ((state != ATTRVAL_SPEC) && (state != ATTRVAL_SPEC_OR_SEP)) {
                throw new LdifParseException("Bad modify state", line);
            }

            // A standard AttributeType/AttributeValue pair
            int colonIndex = line.indexOf(':');

            String attributeType = line.substring(0, colonIndex);

            if (!attributeType.equals(modified)) {
                throw new LdifParseException("Bad modify attribute", line);
            }

            // We should *not* have a DN twice
            if (attributeType.equals("dn")) {
                throw new LdifParseException("A ldif entry should not have two DN", line);
            }

            Object attributeValue = parseValue(line, colonIndex);

            // Update the entry
            entry.addModificationItem(modification, attributeType, attributeValue);
            isEmptyValue = false;

            state = ATTRVAL_SPEC_OR_SEP;
        }
    }
}
 
Example 17
Source File: Entry.java    From scriptella-etl with Apache License 2.0 4 votes vote down vote up
/**
 * Dumps the modifications
 */
private String dumpModificationItems()
{
    StringBuffer sb = new StringBuffer();

    for (ModificationItem modif : modificationList) {
        sb.append("            Operation: ");

        switch (modif.getModificationOp()) {
            case DirContext.ADD_ATTRIBUTE :
                sb.append("ADD\n");
                break;

            case DirContext.REMOVE_ATTRIBUTE :
                sb.append("REMOVE\n");
                break;

            case DirContext.REPLACE_ATTRIBUTE :
                sb.append("REPLACE \n");
                break;
        }

        Attribute attribute = modif.getAttribute();

        sb.append("                Attribute: ").append(attribute.getID()).append('\n');

        if (attribute.size() != 0) {
            try {
                for (NamingEnumeration values = attribute.getAll(); values.hasMoreElements();) {
                    Object value = values.nextElement();

                    if (value instanceof String) {
                        sb.append("                ").append((String) value).append('\n');
                    } else {
                        sb.append("                ").append(Utils.dumpBytes((byte[]) value)).append('\n');
                    }
                }
            }
            catch (NamingException ne) {
                return "";
            }
        }
    }

    return sb.toString();
}
 
Example 18
Source File: LdapManager.java    From fess with Apache License 2.0 4 votes vote down vote up
protected void modifyDeleteEntry(final List<ModificationItem> modifyList, final String name, final Object value) {
    final Attribute attr = new BasicAttribute(name, value);
    final ModificationItem mod = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attr);
    modifyList.add(mod);
}
 
Example 19
Source File: ModifyAttributesOperationRecorder.java    From spring-ldap with Apache License 2.0 4 votes vote down vote up
/**
 * Get a ModificationItem to use for rollback of the supplied modification.
 * 
 * @param originalAttributes
 *            All Attributes of the target DN that are affected of any of
 *            the ModificationItems.
 * @param modificationItem
 *            the ModificationItem to create a rollback item for.
 * @return A ModificationItem to use for rollback of the supplied
 *         ModificationItem.
 */
protected ModificationItem getCompensatingModificationItem(
        Attributes originalAttributes, ModificationItem modificationItem) {
    Attribute modificationAttribute = modificationItem.getAttribute();
    Attribute originalAttribute = originalAttributes
            .get(modificationAttribute.getID());

    if (modificationItem.getModificationOp() == DirContext.REMOVE_ATTRIBUTE) {
        if (modificationAttribute.size() == 0) {
            // If the modification attribute size it means that the
            // Attribute should be removed entirely - we should store a
            // ModificationItem to restore all present values for rollback.
            return new ModificationItem(DirContext.ADD_ATTRIBUTE,
                    (Attribute) originalAttribute.clone());
        } else {
            // The rollback modification will be to re-add the removed
            // attribute values.
            return new ModificationItem(DirContext.ADD_ATTRIBUTE,
                    (Attribute) modificationAttribute.clone());
        }
    } else if (modificationItem.getModificationOp() == DirContext.REPLACE_ATTRIBUTE) {
        if (originalAttribute != null) {
            return new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    (Attribute) originalAttribute.clone());
        } else {
            // The attribute doesn't previously exist - the rollback
            // operation will be to remove the attribute.
            return new ModificationItem(DirContext.REMOVE_ATTRIBUTE,
                    new BasicAttribute(modificationAttribute.getID()));
        }
    } else {
        // An ADD_ATTRIBUTE operation
        if (originalAttribute == null) {
            // The attribute doesn't previously exist - the rollback
            // operation will be to remove the attribute.
            return new ModificationItem(DirContext.REMOVE_ATTRIBUTE,
                    new BasicAttribute(modificationAttribute.getID()));
        } else {
            // The attribute does exist before - we should store the
            // previous value and it should be used for replacing in
            // rollback.
            return new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    (Attribute) originalAttribute.clone());
        }
    }
}
 
Example 20
Source File: LDAPOperationManager.java    From keycloak with Apache License 2.0 2 votes vote down vote up
/**
 * <p>
 * Removes the given {@link Attribute} instance using the given DN. This method performs a REMOVE_ATTRIBUTE
 * operation.
 * </p>
 *
 * @param dn
 * @param attribute
 */
public void removeAttribute(String dn, Attribute attribute) {
    ModificationItem[] mods = new ModificationItem[]{new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attribute)};
    modifyAttributes(dn, mods, null);
}