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

The following examples show how to use javax.naming.directory.DirContext#REPLACE_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_ReplaceNonExistingAttribute()
        throws NamingException {
    Attributes attributes = new BasicAttributes();

    BasicAttribute modificationAttribute = new BasicAttribute("someattr");
    modificationAttribute.add("newvalue1");
    modificationAttribute.add("newvalue2");
    ModificationItem originalItem = new ModificationItem(
            DirContext.REPLACE_ATTRIBUTE, modificationAttribute);

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

    // Verify result
    assertThat(result.getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
    Attribute resultAttribute = result.getAttribute();
    assertThat(resultAttribute.getID()).isEqualTo("someattr");
    assertThat(resultAttribute.size()).isEqualTo(0);
}
 
Example 2
Source File: Password2Ldap.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public boolean sync(UserInfo userInfo) throws Exception{
	logger.info("changePassword");
	try {
		ModificationItem[] modificationItems = new ModificationItem[1];
		modificationItems[0]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("userPassword",ReciprocalUtils.decoder(userInfo.getDecipherable())));
		
		String dn="uid="+userInfo.getUsername()+",dc=users,"+ldapUtils.getBaseDN();
		
		ldapUtils.getCtx().modifyAttributes(dn, modificationItems);
		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return true;
}
 
Example 3
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 4
Source File: LdapTemplateModifyITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testModifyAttributes_LdapName() {
	ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("description",
			"Some other description"));

	tested.modifyAttributes(LdapUtils.newLdapName(PERSON4_DN), new ModificationItem[] { item });

	verifyBoundCorrectData();
}
 
Example 5
Source File: LdapTemplateModifyITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testModifyAttributes_Plain() {
	ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("description",
			"Some other description"));

	tested.modifyAttributes(PERSON4_DN, new ModificationItem[] { item });

	verifyBoundCorrectData();
}
 
Example 6
Source File: LdapTemplateModifyITest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Test
public void testModifyAttributes_MultiValueReplace() {
	BasicAttribute attr = new BasicAttribute("description", "Some other description");
	attr.add("Another description");
	ModificationItem[] mods = new ModificationItem[1];
	mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr);

	tested.modifyAttributes(PERSON4_DN, mods);

	DirContextAdapter result = (DirContextAdapter) tested.lookup(PERSON4_DN);
	List<String> attributes = Arrays.asList(result.getStringAttributes("description"));
	assertThat(attributes).hasSize(2);
	assertThat(attributes.contains("Some other description")).isTrue();
       assertThat(attributes.contains("Another description")).isTrue();
}
 
Example 7
Source File: LDAPIdentityStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void updatePassword(LDAPObject user, String password, LDAPOperationDecorator passwordUpdateDecorator) {
    String userDN = user.getDn().toString();

    if (logger.isDebugEnabled()) {
        logger.debugf("Using DN [%s] for updating LDAP password of user", userDN);
    }

    if (getConfig().isActiveDirectory()) {
        updateADPassword(userDN, password, passwordUpdateDecorator);
        return;
    }

    try {
        if (config.useExtendedPasswordModifyOp()) {
            operationManager.passwordModifyExtended(userDN, password, passwordUpdateDecorator);
        } else {
            ModificationItem[] mods = new ModificationItem[1];
            BasicAttribute mod0 = new BasicAttribute(LDAPConstants.USER_PASSWORD_ATTRIBUTE, password);
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mod0);
            operationManager.modifyAttributes(userDN, mods, passwordUpdateDecorator);
        }
    } catch (ModelException me) {
        throw me;
    } catch (Exception e) {
        throw new ModelException("Error updating password.", e);
    }
}
 
Example 8
Source File: LDAPOperationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Modifies the given {@link Attribute} instances using the given DN. This method performs a REPLACE_ATTRIBUTE
 * operation.
 * </p>
 *
 * @param dn
 * @param attributes
 */
public void modifyAttributes(String dn,  NamingEnumeration<Attribute> attributes) {
    try {
        List<ModificationItem> modItems = new ArrayList<ModificationItem>();
        while (attributes.hasMore()) {
            ModificationItem modItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attributes.next());
            modItems.add(modItem);
        }

        modifyAttributes(dn, modItems.toArray(new ModificationItem[] {}), null);
    } catch (NamingException ne) {
        throw new ModelException("Could not modify attributes on entry from DN [" + dn + "]", ne);
    }

}
 
Example 9
Source File: LdapConnection.java    From hop with Apache License 2.0 5 votes vote down vote up
public int update( String dn, String[] attributes, String[] values, boolean checkEntry ) throws HopException {
  try {
    int nrAttributes = attributes.length;
    ModificationItem[] mods = new ModificationItem[ nrAttributes ];
    for ( int i = 0; i < nrAttributes; i++ ) {
      // Define attribute
      Attribute mod = new BasicAttribute( attributes[ i ], values[ i ] );
      if ( log.isDebug() ) {
        log
          .logDebug( BaseMessages.getString( PKG, "LdapConnection.Update.Attribute", attributes[ i ], values[ i ] ) );
      }
      // Save update action on attribute
      mods[ i ] = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, mod );
    }
    // We have all requested attribute
    // let's update now
    getInitialContext().modifyAttributes( dn, mods );
    return STATUS_UPDATED;
  } catch ( NameNotFoundException n ) {
    // The entry is not found
    if ( checkEntry ) {
      throw new HopException(
        BaseMessages.getString( PKG, "LdapConnection.Error.Deleting.NameNotFound", dn ), n );
    }
    return STATUS_SKIPPED;
  } catch ( Exception e ) {
    throw new HopException( BaseMessages.getString( PKG, "LdapConnection.Error.Update", dn ), 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 writeStringAttribute( final String entryDN, final String attributeName, final Set<String> values, final boolean overwrite )
        throws ChaiUnavailableException, ChaiOperationException
{
    activityPreCheck();
    getInputValidator().writeStringAttribute( entryDN, attributeName, values, overwrite );


    // Create the ModificationItem
    final ModificationItem[] modificationItem = new ModificationItem[values.size()];

    int loopCounter = 0;
    for ( final String value : values )
    {
        // Create a BasicAttribute for the object.
        final BasicAttribute attributeToReplace = new BasicAttribute( attributeName, value );

        // Determine the modification type, if replace, only replace on the first attribute, the rest just get added.
        final int modType = ( loopCounter == 0 && overwrite ) ? DirContext.REPLACE_ATTRIBUTE : DirContext.ADD_ATTRIBUTE;

        // Populate the ModificationItem object with the flag & the attribute to replace.
        modificationItem[loopCounter] = new ModificationItem( modType, attributeToReplace );
        loopCounter++;
    }

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

    // Modify the Attributes.
    try
    {
        ldapConnection.modifyAttributes( addJndiEscape( entryDN ), modificationItem );
    }
    catch ( NamingException e )
    {
        LOGGER.trace( "error during write of attribute '" + attributeName + "', error: " + e.getMessage() );
        convertNamingException( e );
    }
}
 
Example 11
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 12
Source File: JNDIProviderImpl.java    From ldapchai with GNU Lesser General Public License v2.1 4 votes vote down vote up
public final void writeStringAttributes(
        final String entryDN,
        final Map<String, String> attributeValueProps,
        final boolean overwrite,
        final BasicControl[] controls
)
        throws ChaiUnavailableException, ChaiOperationException
{
    activityPreCheck();
    getInputValidator().writeStringAttributes( entryDN, attributeValueProps, overwrite );

    // Determine the modification type, if replace, only replace on the first attribute, the rest just get added.
    final int modType = overwrite ? DirContext.REPLACE_ATTRIBUTE : DirContext.ADD_ATTRIBUTE;

    // Create the ModificationItem
    final List<ModificationItem> modificationItems = new ArrayList<>();
    for ( final Map.Entry<String, String> entry : attributeValueProps.entrySet() )
    {
        // Create a BasicAttribute for the object.
        final BasicAttribute attributeToReplace = new BasicAttribute( entry.getKey(), entry.getValue() );

        // Populate the ModificationItem object with the flag & the attribute to replace.
        modificationItems.add( new ModificationItem( modType, attributeToReplace ) );
    }

    // convert to array
    final ModificationItem[] modificationItemArray = modificationItems.toArray( new ModificationItem[modificationItems.size()] );

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

    // Modify the Attributes.
    try
    {
        ldapConnection.modifyAttributes( addJndiEscape( entryDN ), modificationItemArray );
    }
    catch ( NamingException e )
    {
        convertNamingException( e );
    }
}
 
Example 13
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 14
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 15
Source File: LdapManager.java    From fess with Apache License 2.0 4 votes vote down vote up
protected void modifyReplaceEntry(final List<ModificationItem> modifyList, final String name, final String value) {
    final Attribute attr = new BasicAttribute(name, value);
    final ModificationItem mod = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr);
    modifyList.add(mod);
}
 
Example 16
Source File: UserInfo2Ldap.java    From MaxKey with Apache License 2.0 4 votes vote down vote up
@Override
public boolean update(UserInfo userInfo) throws Exception{
	logger.info("update");
	try {
		SearchControls constraints = new SearchControls();
		constraints.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(&(objectClass=inetOrgPerson)(uid="+userInfo.getUsername()+"))", constraints);
		if (results == null || !results.hasMore()) {
			return create(loadUser(userInfo));
		}
		
		ModificationItem[] modificationItems = new ModificationItem[10];
		modificationItems[0]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("displayName",userInfo.getDisplayName()));
		modificationItems[1]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("cn",userInfo.getDisplayName()));
		modificationItems[2]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("givenName",userInfo.getGivenName()));
		modificationItems[3]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("sn",userInfo.getFamilyName()));
		
		modificationItems[4]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("mobile",userInfo.getWorkPhoneNumber()==null?"":userInfo.getWorkPhoneNumber()));
		modificationItems[5]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("mail",userInfo.getWorkEmail()==null?"":userInfo.getWorkEmail()));
		
		modificationItems[6]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("employeeNumber",userInfo.getEmployeeNumber()==null?"":userInfo.getEmployeeNumber()));
		modificationItems[7]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("ou",userInfo.getDepartment()==null?"":userInfo.getDepartment()));
		modificationItems[8]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("departmentNumber",userInfo.getDepartmentId()==null?"":userInfo.getDepartmentId()));
		modificationItems[9]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("title",userInfo.getJobTitle()==null?"":userInfo.getJobTitle()));
		
		String managerDn="uid=dummy";
		if(userInfo.getManagerId()==null||userInfo.getManagerId().equals("")){

		}else{
			UserInfo queryManager=new UserInfo();
			queryManager.setId(userInfo.getManagerId());
			UserInfo manager=loadUser(queryManager);
			managerDn="uid="+manager.getUsername()+",dc=users,"+ldapUtils.getBaseDN();
		}
		modificationItems[9]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("manager",managerDn));

		
		
		String dn="uid="+userInfo.getUsername()+",dc=users,"+ldapUtils.getBaseDN();
		
		ldapUtils.getCtx().modifyAttributes(dn, modificationItems);
		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return true;
	
}
 
Example 17
Source File: UserInfo2Activedirectory.java    From MaxKey with Apache License 2.0 4 votes vote down vote up
@Override
public boolean update(UserInfo userInfo) throws Exception{
	try {
		String dn=null;
		SearchControls searchControls = new SearchControls();
		searchControls.setSearchScope(ldapUtils.getSearchScope());
		NamingEnumeration<SearchResult> results = ldapUtils.getConnection()
				.search(ldapUtils.getBaseDN(), "(sAMAccountName="+userInfo.getUsername()+")", searchControls);
		if (results == null || !results.hasMore()) {
			return create(loadUser(userInfo));
		}
		
		SearchResult sr = (SearchResult) results.next();
		dn =sr.getNameInNamespace();
		
		ModificationItem[] modificationItems = new ModificationItem[8];
		//modificationItems[0]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("displayName",userInfo.getDisplayName()));
		//modificationItems[1]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("cn",userInfo.getDisplayName()));
		//modificationItems[2]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("givenName",userInfo.getGivenName()));
		//modificationItems[3]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("sn",userInfo.getFamilyName()));
		
		modificationItems[0]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("mobile",userInfo.getWorkPhoneNumber()==null?"00000000000":userInfo.getWorkPhoneNumber()));
		modificationItems[1]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("mail",userInfo.getWorkEmail()==null?"[email protected]":userInfo.getWorkEmail()));
		
		modificationItems[2]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("employeeNumber",userInfo.getEmployeeNumber()==null?"default":userInfo.getEmployeeNumber()));
		modificationItems[3]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("ou",userInfo.getDepartment()==null?"default":userInfo.getDepartment()));
		
		modificationItems[4]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("department",userInfo.getDepartmentId()==null?"default":userInfo.getDepartment()));
		modificationItems[5]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("departmentNumber",userInfo.getDepartmentId()==null?"default":userInfo.getDepartmentId()));
		modificationItems[6]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("title",userInfo.getJobTitle()==null?"default":userInfo.getJobTitle()));
		
		String managerDn="CN=dummy,"+ldapUtils.getBaseDN();
		if(userInfo.getManagerId()==null||userInfo.getManagerId().equals("")){

		}else{
			UserInfo queryManager=new UserInfo();
			queryManager.setId(userInfo.getManagerId());
			UserInfo manager=loadUser(queryManager);
			SearchControls managerSearchControls = new SearchControls();
			managerSearchControls.setSearchScope(ldapUtils.getSearchScope());
			NamingEnumeration<SearchResult> managerResults = ldapUtils.getConnection()
					.search(ldapUtils.getBaseDN(), "(sAMAccountName="+manager.getUsername()+")", managerSearchControls);
			if (managerResults == null || !managerResults.hasMore()) {
				
			}else{
				SearchResult managerSr = (SearchResult) managerResults.next();
				managerDn =managerSr.getNameInNamespace();
			}
		}
		
		modificationItems[7]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("manager",managerDn));
		
		
		ldapUtils.getCtx().modifyAttributes(dn, modificationItems);
		
		if(userInfo.getDepartmentId()!=null&&
				!userInfo.getDepartmentId().equals("")){
			//get organization dn
			SearchControls orgSearchControls = new SearchControls();
			orgSearchControls.setSearchScope(ldapUtils.getSearchScope());
			NamingEnumeration<SearchResult> orgResults = ldapUtils.getConnection()
					.search(ldapUtils.getBaseDN(), "(&(objectClass=organizationalUnit)(description="+userInfo.getDepartmentId()+"))", orgSearchControls);
			String orgRdn="";
			if (orgResults == null || !orgResults.hasMore()) {
				orgRdn=ldapUtils.getBaseDN();
			}else{
				SearchResult orgSearchResult = (SearchResult) orgResults.next();
				orgRdn =orgSearchResult.getNameInNamespace();
			}
			
			//String newDn="CN="+userInfo.getDisplayName()+","+orgRdn;
			String newDn="CN="+userInfo.getUsername()+","+orgRdn;
			
			if(!dn.equals(newDn)){
				logger.debug("oldDn : "+dn);
				logger.debug("newDn : "+newDn);
				ldapUtils.getCtx().rename(dn, newDn);
			}
		}
		
		ldapUtils.close();
	} catch (NamingException e) {
		e.printStackTrace();
	}
	return true;
}
 
Example 18
Source File: ServerEntryUtils.java    From MyVirtualDirectory with Apache License 2.0 4 votes vote down vote up
public static List<Modification> toServerModification( ModificationItem[] modifications,
    SchemaManager schemaManager ) throws LdapException
{
    if ( modifications != null )
    {
        List<Modification> modificationsList = new ArrayList<Modification>();

        for ( ModificationItem modification : modifications )
        {
            String attributeId = modification.getAttribute().getID();
            String id = stripOptions( attributeId );
            Set<String> options = getOptions( attributeId );

            // -------------------------------------------------------------------
            // DIRSERVER-646 Fix: Replacing an unknown attribute with no values 
            // (deletion) causes an error
            // -------------------------------------------------------------------

            // TODO - after removing JNDI we need to make the server handle 
            // this in the codec

            if ( !schemaManager.getAttributeTypeRegistry().contains( id )
                && modification.getAttribute().size() == 0
                && modification.getModificationOp() == DirContext.REPLACE_ATTRIBUTE )
            {
                continue;
            }

            // -------------------------------------------------------------------
            // END DIRSERVER-646 Fix
            // -------------------------------------------------------------------

            // TODO : handle options
            AttributeType attributeType = schemaManager.lookupAttributeTypeRegistry( id );
            modificationsList.add( toServerModification( modification, attributeType ) );
        }

        return modificationsList;
    }
    else
    {
        return null;
    }
}
 
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: ServerEntryUtils.java    From MyVirtualDirectory with Apache License 2.0 4 votes vote down vote up
public static List<Modification> toServerModification( ModificationItem[] modifications,
    SchemaManager schemaManager ) throws LdapException
{
    if ( modifications != null )
    {
        List<Modification> modificationsList = new ArrayList<Modification>();

        for ( ModificationItem modification : modifications )
        {
            String attributeId = modification.getAttribute().getID();
            String id = stripOptions( attributeId );
            Set<String> options = getOptions( attributeId );

            // -------------------------------------------------------------------
            // DIRSERVER-646 Fix: Replacing an unknown attribute with no values 
            // (deletion) causes an error
            // -------------------------------------------------------------------

            // TODO - after removing JNDI we need to make the server handle 
            // this in the codec

            if ( !schemaManager.getAttributeTypeRegistry().contains( id )
                && modification.getAttribute().size() == 0
                && modification.getModificationOp() == DirContext.REPLACE_ATTRIBUTE )
            {
                continue;
            }

            // -------------------------------------------------------------------
            // END DIRSERVER-646 Fix
            // -------------------------------------------------------------------

            // TODO : handle options
            AttributeType attributeType = schemaManager.lookupAttributeTypeRegistry( id );
            modificationsList.add( toServerModification( modification, attributeType ) );
        }

        return modificationsList;
    }
    else
    {
        return null;
    }
}