Java 类javax.naming.directory.ModificationItem 实例源码

项目:plugin-id-ldap    文件:UserLdapRepository.java   
/**
 * Lock an user :
 * <ul>
 * <li>Clear the password to prevent new authentication</li>
 * <li>Set the disabled flag.</li>
 * </ul>
 * 
 * @param principal
 *            User requesting the lock.
 * @param user
 *            The LDAP user to disable.
 * @param isolate
 *            When <code>true</code>, the user will be isolated in addition.
 */
private void lock(final String principal, final UserOrg user, final boolean isolate) {
    if (user.getLockedBy() == null) {
        // Not yet locked
        final ModificationItem[] mods = new ModificationItem[2];
        final long timeInMillis = DateUtils.newCalendar().getTimeInMillis();
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(lockedAttribute,
                String.format("%s|%s|%s|%s|", lockedValue, timeInMillis, principal, isolate ? user.getCompany() : "")));
        mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(PASSWORD_ATTRIBUTE, null));
        template.modifyAttributes(org.springframework.ldap.support.LdapUtils.newLdapName(user.getDn()), mods);

        // Also update the disabled date
        user.setLocked(new Date(timeInMillis));
        user.setLockedBy(principal);
    }
}
项目:plugin-id-ldap    文件:GroupLdapRepository.java   
/**
 * Remove an "uniqueMember" from given group. Cache is not updated there.
 * 
 * @param uniqueMember
 *            DN of the member to remove.
 * @param group
 *            CN of the group to update. Must be normalized.
 * @return the {@link GroupOrg} where the member has just been removed from.
 */
private GroupOrg removeMember(final ResourceOrg uniqueMember, final String group) {
    final GroupOrg groupLdap = findById(group);
    if (groupLdap.getMembers().contains(uniqueMember.getId()) || groupLdap.getSubGroups().contains(uniqueMember.getId())) {
        // Not useless LDAP operation, avoid LDAP duplicate deletion
        final ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute(UNIQUE_MEMBER, uniqueMember.getDn()));
        try {
            template.modifyAttributes(org.springframework.ldap.support.LdapUtils.newLdapName(groupLdap.getDn()), mods);
        } catch (final org.springframework.ldap.AttributeInUseException aiue) {
            // Even if the membership update failed, the user does not exist anymore. A broken reference can remains
            // in LDAP, but this case is well managed.
            log.info("Unable to remove user {} from the group {} : {}", uniqueMember.getDn(), group, aiue);
        } catch (final org.springframework.ldap.SchemaViolationException sve) { // NOSONAR - Exception is logged
            // Occurs when there is a LDAP schema violation such as as last member removed
            log.warn("Unable to remove user {} from the group {}", uniqueMember.getDn(), group, sve);
            throw new ValidationJsonException("groups", "last-member-of-group", "user", uniqueMember.getId(), "group", group);
        }
    }
    return groupLdap;
}
项目:plugin-id-ldap    文件:GroupLdapRepository.java   
@Override
public void addAttributes(final String dn, final String attribute, final Collection<String> values) {
    if (values.isEmpty()) {
        // Ignore this call
        return;
    }

    // Build the modification operation
    final ModificationItem[] mods = values.stream().map(v -> new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute(attribute, v)))
            .toArray(ModificationItem[]::new);
    try {
        // Perform the addition
        template.modifyAttributes(org.springframework.ldap.support.LdapUtils.newLdapName(dn), mods);
    } catch (final org.springframework.ldap.AttributeInUseException aiue) {
        if (!aiue.getMessage().matches(".*(value #0 already exists|error code 20|ATTRIBUTE_OR_VALUE_EXISTS).*")) {
            throw aiue;
        }
        log.info("{} is already member of {}", values, dn);
    }
}
项目:sonar-activedirectory    文件:ApacheDS.java   
/**
 * This seems to be required for objectClass posixGroup.
 */
private ApacheDS activateNis() throws Exception {
  Preconditions.checkState(ldapServer.isStarted());

  Attribute disabled = new BasicAttribute("m-disabled", "TRUE");
  Attribute disabled2 = new BasicAttribute("m-disabled", "FALSE");
  ModificationItem[] mods = new ModificationItem[] {
    new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled),
    new ModificationItem(DirContext.ADD_ATTRIBUTE, disabled2)
  };

  Hashtable env = new Hashtable();
  env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
  env.put(Context.PROVIDER_URL, getUrl());

  DirContext ctx = new InitialDirContext(env);
  ctx.modifyAttributes("cn=nis,ou=schema", mods);

  return this;
}
项目:MyVirtualDirectory    文件:ServerEntryUtils.java   
/**
 * 
 * Convert a list of ModificationItemImpl to a list of 
 *
 * @param modificationImpls
 * @param atRegistry
 * @return
 * @throws LdapException
 */
public static List<Modification> convertToServerModification( List<ModificationItem> modificationItems,
    SchemaManager schemaManager ) throws LdapException
{
    if ( modificationItems != null )
    {
        List<Modification> modifications = new ArrayList<Modification>( modificationItems.size() );

        for ( ModificationItem modificationItem : modificationItems )
        {
            AttributeType attributeType = schemaManager.lookupAttributeTypeRegistry( modificationItem
                .getAttribute().getID() );
            modifications.add( toServerModification( modificationItem, attributeType ) );
        }

        return modifications;
    }
    else
    {
        return null;
    }
}
项目:MyVirtualDirectory    文件:ServerEntryUtils.java   
/**
 * 
 * Convert a list of ModificationItemImpl to a list of 
 *
 * @param modificationImpls
 * @param atRegistry
 * @return
 * @throws LdapException
 */
public static List<Modification> convertToServerModification( List<ModificationItem> modificationItems,
    SchemaManager schemaManager ) throws LdapException
{
    if ( modificationItems != null )
    {
        List<Modification> modifications = new ArrayList<Modification>( modificationItems.size() );

        for ( ModificationItem modificationItem : modificationItems )
        {
            AttributeType attributeType = schemaManager.lookupAttributeTypeRegistry( modificationItem
                .getAttribute().getID() );
            modifications.add( toServerModification( modificationItem, attributeType ) );
        }

        return modifications;
    }
    else
    {
        return null;
    }
}
项目:OEPv2    文件:ManagerLdap.java   
public void changePassord(ServiceContext serviceContext, User user, String password) throws Exception{
    long companyId = serviceContext.getCompanyId();
    Properties userMappings = getUserMappings(serviceContext.getCompanyId());
    Binding binding = getUser(companyId, user.getScreenName());
    System.out.println("bingging " + binding);
    System.out.println("Pass " + user.getPassword());
    String name = StringPool.BLANK;
    StringBuilder sb = new StringBuilder();
    LdapContext ctx = getContext(serviceContext.getCompanyId());
       sb = new StringBuilder();
    sb.append(userMappings.getProperty("screenName"));
    sb.append(StringPool.EQUAL);
    sb.append(user.getScreenName());
    sb.append(StringPool.COMMA);
    sb.append(getUsersDN(companyId));
    name = sb.toString();
    Modifications mods = Modifications.getInstance();  

    mods.addItem(userMappings.getProperty(UserConverterKeys.PASSWORD),password);
    ModificationItem[] modItems = mods.getItems();
    if (binding != null) {
        ctx.modifyAttributes(name, modItems);
    }

}
项目:OEPv2    文件:EmployeeExportToLdap.java   
public void updateLdapZimbra(LdapContext ctx ,User user,String name, Employee emp) throws NamingException{
    Modifications mods = Modifications.getInstance();
       for (int i = 0; i < 5;i++){
         mods.addItem(zimbraProperty[i][0],zimbraProperty[i][1]);
       }
       mods.addItem("zimbramaildeliveryaddress",user.getEmailAddress());

      // mods.addItem("company",user.getEmailAddress());
     //  mods.addItem("street",user.getEmailAddress());
      //.addItem("company",user.getEmailAddress());
      // mods.addItem("company",user.getEmailAddress());
    //System.out.println("My  " + mods);
       ModificationItem[] modItems = mods.getItems();
       ctx.modifyAttributes(name, modItems);
       //= getContext(serviceContext.getCompanyId());

}
项目:osa    文件:LdapManager.java   
/**
 * Function for instance_admin to reset user password 
 */
public boolean resetUserPassword(String usrDn, String pw) {
    DirContext context = null;

    try {
        context = getContext();
        Attribute userPassword = new BasicAttribute(LdapManager.PERSON_PASSWORD, hash256(pw));
        ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPassword);
        context.modifyAttributes(usrDn, mods);
        logger.info("LdapManager info: User '"+usrDn+"' password reseted by instance_admin.");
        context.close();

    } catch (NamingException e) {
        logger.error("LdapManager error: Error reseting user password, "+e);
        return false;
    }

    return true;
}
项目:teiid    文件:TestLDAPDirectQueryExecution.java   
@Test public void testUpdate() throws Exception {
      String input = "exec native('update;uid=doe,ou=people,o=teiid.org;attributes=one,two,three', 'one', 2, 3.0)"; 

      TranslationUtility util = FakeTranslationFactory.getInstance().getExampleTranslationUtility();
      Command command = util.parseCommand(input);
      ExecutionContext ec = Mockito.mock(ExecutionContext.class);
      RuntimeMetadata rm = Mockito.mock(RuntimeMetadata.class);
      LdapContext connection = Mockito.mock(LdapContext.class);
      LdapContext ctx = Mockito.mock(LdapContext.class);
      Mockito.stub(connection.lookup("")).toReturn(ctx);

      LDAPDirectCreateUpdateDeleteQueryExecution execution = (LDAPDirectCreateUpdateDeleteQueryExecution)TRANSLATOR.createExecution(command, ec, rm, connection);
execution.execute();

ArgumentCaptor<String> nameArgument = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<ModificationItem[]> modificationItemArgument = ArgumentCaptor.forClass(ModificationItem[].class);
Mockito.verify(ctx).modifyAttributes(nameArgument.capture(),modificationItemArgument.capture());

assertEquals("uid=doe,ou=people,o=teiid.org", nameArgument.getValue());
assertEquals("one", modificationItemArgument.getValue()[0].getAttribute().getID());
assertEquals("one", modificationItemArgument.getValue()[0].getAttribute().get());
assertEquals("two", modificationItemArgument.getValue()[1].getAttribute().getID());
assertEquals("2", modificationItemArgument.getValue()[1].getAttribute().get());
assertEquals("three", modificationItemArgument.getValue()[2].getAttribute().getID());
assertEquals("3.0", modificationItemArgument.getValue()[2].getAttribute().get());
  }
项目:teiid    文件:TestIQueryToLdapSearchParser.java   
@Test public void testUpdateNull() throws Exception {
      String sql = "update LdapModel.People set userid = 1, name = null where dn = 'x'"; //$NON-NLS-1$

      QueryMetadataInterface metadata = exampleLdap();

      Update query = (Update)getCommand(sql, metadata);

      LDAPExecutionFactory config = new LDAPExecutionFactory();

      LdapContext context = Mockito.mock(LdapContext.class);

      Mockito.stub(context.lookup("")).toReturn(context);

LDAPUpdateExecution lue = new LDAPUpdateExecution(query, context);

      lue.execute();
      ArgumentCaptor<ModificationItem[]> captor = ArgumentCaptor.forClass(ModificationItem[].class);
      Mockito.verify(context).modifyAttributes(ArgumentCaptor.forClass(String.class).capture(), captor.capture());
      ModificationItem[] modifications = captor.getValue();
      assertEquals(2, modifications.length);
      assertEquals("uid: 1", modifications[0].getAttribute().toString());
      assertEquals("cn: null", modifications[1].getAttribute().toString());
  }
项目:teiid    文件:TestIQueryToLdapSearchParser.java   
@Test public void testUpdateArray() throws Exception {
      String sql = "update LdapModel.People set userid = 1, vals = ('a','b') where dn = 'x'"; //$NON-NLS-1$

      QueryMetadataInterface metadata = exampleLdap();

      Update query = (Update)getCommand(sql, metadata);

      LDAPExecutionFactory config = new LDAPExecutionFactory();

      LdapContext context = Mockito.mock(LdapContext.class);

      Mockito.stub(context.lookup("")).toReturn(context);

LDAPUpdateExecution lue = new LDAPUpdateExecution(query, context);

      lue.execute();
      ArgumentCaptor<ModificationItem[]> captor = ArgumentCaptor.forClass(ModificationItem[].class);
      Mockito.verify(context).modifyAttributes(ArgumentCaptor.forClass(String.class).capture(), captor.capture());
      ModificationItem[] modifications = captor.getValue();
      assertEquals(2, modifications.length);
      assertEquals("uid: 1", modifications[0].getAttribute().toString());
      assertEquals("vals: a, b", modifications[1].getAttribute().toString());
  }
项目:carbon-identity    文件:ApacheKDCServer.java   
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);
    }
}
项目:osa    文件:LdapManager.java   
/**
 * Function for instance_admin to reset user password 
 */
public boolean resetUserPassword(String usrDn, String pw) {
    DirContext context = null;

    try {
        context = getContext();
        Attribute userPassword = new BasicAttribute(LdapManager.PERSON_PASSWORD, hash256(pw));
        ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPassword);
        context.modifyAttributes(usrDn, mods);
        logger.info("LdapManager info: User '"+usrDn+"' password reseted by instance_admin.");
        context.close();

    } catch (NamingException e) {
        logger.error("LdapManager error: Error reseting user password, "+e);
        return false;
    }

    return true;
}
项目:jeffaschenk-commons    文件:IRRChangeLogRestoreServiceReaderThread.java   
/**
 * setupModifications, Setup Bulk Modificationitem from incoming Attributes Object.
 *
 * @param _modtype    Modifcation Type.
 * @param _entryattrs Incoming attributes to be placed into Modificationitem Queue.
 * @throws idxIRRException for any specific IRR unrecoverable errors during function.
 * @throws Exception       for any unrecoverable errors during function.
 */
private void setupModifications(int _modtype, Attributes _entryattrs)
        throws Exception, idxIRRException {

    // **********************************************
    // Check incoming Parameters.
    if (_entryattrs == null) {
        return;
    }

    // **********************************************************
    // Process the incoming Attributes into the Modification Set.
    for (NamingEnumeration ea = _entryattrs.getAll(); ea.hasMore(); ) {
        Attribute attr = (Attribute) ea.next();
        CURRENT_MODLIST.addLast(new ModificationItem(_modtype, attr));
    } // End of For Loop.

    // **********************************************
    // Return
    return;
}
项目:cn1    文件:ldapURLContext.java   
public void modifyAttributes(Name name, ModificationItem[] modificationItems)
        throws NamingException {
    if (!(name instanceof CompositeName)) {
        // jndi.26=URL context can't accept non-composite name: {0}
        throw new InvalidNameException(Messages.getString("jndi.26", name)); //$NON-NLS-1$
    }

    if (name.size() == 1) {
        modifyAttributes(name.get(0), modificationItems);
        return;
    }
    DirContext context = getContinuationContext(name);

    try {
        context.modifyAttributes(name.getSuffix(1), modificationItems);
        return;
    } finally {
        context.close();
    }

}
项目:cn1    文件:AttributeModificationExceptionTest.java   
public void testToString() {
    log.setMethod("testToString()");
    String str;

    AttributeModificationException ex = new AttributeModificationException(
            "sample message");
    str = ex.toString();
    assertTrue(str.indexOf("sample message") >= 0);
    assertFalse(str.indexOf("sample id") >= 0);
    assertFalse(str.indexOf("sample value") >= 0);

    ModificationItem items[] = new ModificationItem[] { new ModificationItem(
            DirContext.ADD_ATTRIBUTE, new BasicAttribute("sample id",
                    "sample value")), };

    ex.setUnexecutedModifications(items);
    str = ex.toString();
    assertTrue(str.indexOf("sample message") >= 0);
    assertTrue(str.indexOf("sample id") >= 0);
    assertTrue(str.indexOf("sample value") >= 0);
}
项目:cn1    文件:AttributeModificationExceptionTest.java   
public void testSetUnexecutedModifications() throws InvalidNameException {
    AttributeModificationException ex1 = new AttributeModificationException(
            "Test 1");
    AttributeModificationException ex2 = new AttributeModificationException(
            "Test 2");
    Name name = new CompositeName("TestSetUnexecutedModifications");
    ex1.setRemainingName(name);
    ex1.setRootCause(ex2);
    ModificationItem[] items = {
            new ModificationItem(DirContext.ADD_ATTRIBUTE,
                    new BasicAttribute("test1")),
            new ModificationItem(DirContext.ADD_ATTRIBUTE,
                    new BasicAttribute("test2")), };
    ex1.setUnexecutedModifications(items);
    assertTrue(ex1.toString(false).equals(ex1.toString()));
    assertTrue(ex1.toString(true).equals(ex1.toString()));
}
项目:marmotta    文件:LdapAuthProvider.java   
@Override
public boolean updatePassword(UserAccount login, String newPasswd) {
    if (login == null) return false;
    String username = login.getLogin();
    log.trace("changePassword called for account: {}", username);

    ModificationItem[] mod = new ModificationItem[1];
    Attribute attr = new BasicAttribute("userpassword", newPasswd);
    mod[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr);

    final String dn = configurationService.getStringConfiguration(CONF_DN, "{login}")
            .replaceAll(Pattern.quote("{login}"), username);
    try {
        // ctx.modifyAttributes(dn, mod);
        // log.info("LDAP-Passwd update for {} successful ({})", username, dn);
        // return true;
    } catch (Exception e) {
        log.info("LDAP-Passwd update for {} failed ({})", username, dn);
    }
    log.warn("LDAP-Passwd update not implemented");
    return false;
}
项目:read-open-source-code    文件:LDAPConnection.java   
public int update(String dn, String[] attributes, String[] values, boolean checkEntry) throws KettleException {
  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 KettleException(BaseMessages.getString(PKG, "LDAPConnection.Error.Deleting.NameNotFound", dn), n);
    }
    return STATUS_SKIPPED;
  } catch (Exception e) {
    throw new KettleException(BaseMessages.getString(PKG, "LDAPConnection.Error.Update", dn), e);
  }
}
项目:nextop-client    文件:ldapURLContext.java   
public void modifyAttributes(Name name, ModificationItem[] modificationItems)
        throws NamingException {
    if (!(name instanceof CompositeName)) {
        // jndi.26=URL context can't accept non-composite name: {0}
        throw new InvalidNameException(Messages.getString("jndi.26", name)); //$NON-NLS-1$
    }

    if (name.size() == 1) {
        modifyAttributes(name.get(0), modificationItems);
        return;
    }
    DirContext context = getContinuationContext(name);

    try {
        context.modifyAttributes(name.getSuffix(1), modificationItems);
        return;
    } finally {
        context.close();
    }

}
项目:spring-ldap    文件:ModifyAttributesOperationRecorderTest.java   
@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);
}
项目:spring-ldap    文件:ModifyAttributesOperationRecorderTest.java   
@Test
public void testGetCompensatingModificationItem_AddExistingAttribute()
        throws NamingException {
    BasicAttribute attribute = new BasicAttribute("someattr");
    attribute.add("value1");
    attribute.add("value2");
    Attributes attributes = new BasicAttributes();
    attributes.put(attribute);

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

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

    // Verify result
    assertThat(result.getModificationOp()).isEqualTo(DirContext.REPLACE_ATTRIBUTE);
    Attribute resultAttribute = result.getAttribute();
    assertThat(resultAttribute.getID()).isEqualTo("someattr");
    assertThat(result.getAttribute().get(0)).isEqualTo("value1");
    assertThat(result.getAttribute().get(1)).isEqualTo("value2");
}
项目:spring-ldap    文件:ModifyAttributesOperationRecorderTest.java   
@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");
}
项目:spring-ldap    文件:DirContextAdapterTest.java   
@Test
public void testRemoveDnAttributeSyntacticallyEqual() throws NamingException {
    BasicAttributes attributes = new BasicAttributes();
    attributes.put("uniqueMember", "cn=john doe,OU=company");

    DirContextAdapter tested = new DirContextAdapter(attributes, LdapUtils.newLdapName("cn=administrators, ou=groups"));
    tested.setUpdateMode(true);

    tested.removeAttributeValue("uniqueMember", LdapUtils.newLdapName("cn=john doe, ou=company"));
    ModificationItem[] modificationItems = tested.getModificationItems();
    assertThat(modificationItems.length).isEqualTo(1);

    ModificationItem modificationItem = modificationItems[0];
    assertThat(modificationItem.getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
    assertThat(modificationItem.getAttribute().getID()).isEqualTo("uniqueMember");
}
项目:freeVM    文件:AttributeModificationExceptionTest.java   
public void testSetUnexecutedModifications() throws InvalidNameException {
    AttributeModificationException ex1 = new AttributeModificationException(
            "Test 1");
    AttributeModificationException ex2 = new AttributeModificationException(
            "Test 2");
    Name name = new CompositeName("TestSetUnexecutedModifications");
    ex1.setRemainingName(name);
    ex1.setRootCause(ex2);
    ModificationItem[] items = {
            new ModificationItem(DirContext.ADD_ATTRIBUTE,
                    new BasicAttribute("test1")),
            new ModificationItem(DirContext.ADD_ATTRIBUTE,
                    new BasicAttribute("test2")), };
    ex1.setUnexecutedModifications(items);
    assertTrue(ex1.toString(false).equals(ex1.toString()));
    assertTrue(ex1.toString(true).equals(ex1.toString()));
}
项目:spring-ldap    文件:DirContextAdapterTest.java   
@Test
public void testChangeMultiAttributeOrderDoesMatter() throws Exception {
    final Attributes fixtureAttrs = new BasicAttributes();
    Attribute multi = new BasicAttribute("abc");
    multi.add("123");
    multi.add("qwe");
    fixtureAttrs.put(multi);
    class TestableDirContextAdapter extends DirContextAdapter {
        public TestableDirContextAdapter() {
            super(fixtureAttrs, null);
            setUpdateMode(true);
        }
    }
    tested = new TestableDirContextAdapter();
    assertThat(tested.isUpdateMode()).isTrue();
    tested.setAttributeValues("abc", new String[] { "qwe", "123" }, true);

    // change
    ModificationItem[] mods = tested.getModificationItems();
    assertThat(mods.length).isEqualTo(1);
    assertThat(mods[0].getModificationOp()).isEqualTo(DirContext.REPLACE_ATTRIBUTE);
    Attribute attr = mods[0].getAttribute();
    assertThat(attr.get(0)).isEqualTo("qwe");
    assertThat(attr.get(1)).isEqualTo("123");
}
项目:freeVM    文件:ldapURLContext.java   
public void modifyAttributes(Name name, ModificationItem[] modificationItems)
        throws NamingException {
    if (!(name instanceof CompositeName)) {
        // jndi.26=URL context can't accept non-composite name: {0}
        throw new InvalidNameException(Messages.getString("jndi.26", name)); //$NON-NLS-1$
    }

    if (name.size() == 1) {
        modifyAttributes(name.get(0), modificationItems);
        return;
    }
    DirContext context = getContinuationContext(name);

    try {
        context.modifyAttributes(name.getSuffix(1), modificationItems);
        return;
    } finally {
        context.close();
    }

}
项目:spring-ldap    文件:DirContextAdapterTest.java   
@Test
public void testRemoveAttributeValueInUpdateModeSameAndOtherValueExistsInOrigAttrs()
        throws NamingException {
    BasicAttribute basicAttribute = new BasicAttribute("abc");
    basicAttribute.add("123");
    basicAttribute.add("321");
    tested.setAttribute(basicAttribute);
    tested.setUpdateMode(true);

    // Perform test
    tested.removeAttributeValue("abc", "123");

    ModificationItem[] modificationItems = tested.getModificationItems();
    assertThat(modificationItems.length).isEqualTo(1);
    Attribute modificationAttribute = modificationItems[0].getAttribute();
    assertThat(modificationAttribute.getID()).isEqualTo("abc");
    assertThat(modificationAttribute.size()).isEqualTo(1);
    assertThat(modificationAttribute.get()).isEqualTo("123");
    assertThat(modificationItems[0].getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
}
项目:spring-ldap    文件:DirContextAdapterTest.java   
@Test
public void testNoChangeMultiAttributeOrderDoesNotMatter() throws Exception {
    final Attributes fixtureAttrs = new BasicAttributes();
    Attribute multi = new BasicAttribute("abc");
    multi.add("123");
    multi.add("qwe");
    fixtureAttrs.put(multi);
    class TestableDirContextAdapter extends DirContextAdapter {
        public TestableDirContextAdapter() {
            super(fixtureAttrs, null);
            setUpdateMode(true);
        }
    }
    tested = new TestableDirContextAdapter();
    tested.setAttributeValues("abc", new String[] { "qwe", "123" });

    ModificationItem[] mods = tested.getModificationItems();
    assertThat(mods.length).isEqualTo(0);
    String[] modNames = tested.getNamesOfModifiedAttributes();
    assertThat(modNames.length).isEqualTo(0);
}
项目:freeVM    文件:AttributeModificationExceptionTest.java   
public void testToString() {
    log.setMethod("testToString()");
    String str;

    AttributeModificationException ex = new AttributeModificationException(
            "sample message");
    str = ex.toString();
    assertTrue(str.indexOf("sample message") >= 0);
    assertFalse(str.indexOf("sample id") >= 0);
    assertFalse(str.indexOf("sample value") >= 0);

    ModificationItem items[] = new ModificationItem[] { new ModificationItem(
            DirContext.ADD_ATTRIBUTE, new BasicAttribute("sample id",
                    "sample value")), };

    ex.setUnexecutedModifications(items);
    str = ex.toString();
    assertTrue(str.indexOf("sample message") >= 0);
    assertTrue(str.indexOf("sample id") >= 0);
    assertTrue(str.indexOf("sample value") >= 0);
}
项目:spring-ldap    文件:LdapTemplateTest.java   
@Test
public void testUpdateWithIdSpecified() throws NamingException {
    when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock);
    when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock);
    LdapName expectedName = LdapUtils.newLdapName("ou=someOu");

    ModificationItem[] expectedModificationItems = new ModificationItem[0];
    DirContextOperations ctxMock = mock(DirContextOperations.class);
    when(ctxMock.getDn()).thenReturn(expectedName);
    when(ctxMock.isUpdateMode()).thenReturn(true);
    when(ctxMock.getModificationItems()).thenReturn(expectedModificationItems);

    Object expectedObject = new Object();
    when(odmMock.getId(expectedObject)).thenReturn(expectedName);
    when(odmMock.getCalculatedId(expectedObject)).thenReturn(null);

    when(dirContextMock.lookup(expectedName)).thenReturn(ctxMock);

    tested.update(expectedObject);

    verify(odmMock, never()).setId(expectedObject, expectedName);
    verify(odmMock).mapToLdapDataEntry(expectedObject, ctxMock);
    verify(dirContextMock).modifyAttributes(expectedName, expectedModificationItems);

    verify(dirContextMock, times(2)).close();
}
项目:projectforge-webapp    文件:LdapDao.java   
/**
 * Helper method for appending modification item(s) to a given list. At least one entry will be added if no attrValue is given.
 * @param list
 * @param attrId
 * @param attrValues If null then a null-value will be assumed. If more than one string is given, multiple modification items will be
 *          added.
 * @return
 */
protected void createAndAddModificationItems(final List<ModificationItem> list, final String attrId, final String... attrValues)
{
  if (attrValues == null) {
    list.add(createModificationItem(attrId, null));
    return;
  }
  boolean added = false;
  for (final String attrValue : attrValues) {
    if (StringUtils.isEmpty(attrValue) == true && added == true) {
      continue;
    }
    final String val = StringUtils.isEmpty(attrValue) == true ? null : attrValue;
    if (added == false) {
      list.add(createModificationItem(DirContext.REPLACE_ATTRIBUTE, attrId, val));
      added = true;
    } else {
      list.add(createModificationItem(DirContext.ADD_ATTRIBUTE, attrId, val));
    }
  }
}
项目:spring-ldap    文件:DirContextAdapterTest.java   
@Test
public void testChangeAttribute() throws Exception {
    final Attributes fixtureAttrs = new BasicAttributes();
    fixtureAttrs.put(new BasicAttribute("abc", "123"));
    class TestableDirContextAdapter extends DirContextAdapter {
        public TestableDirContextAdapter() {
            super(fixtureAttrs, null);
            setUpdateMode(true);
        }
    }
    tested = new TestableDirContextAdapter();
    tested.setAttributeValue("abc", "234"); // change

    ModificationItem[] mods = tested.getModificationItems();
    assertThat(mods.length).isEqualTo(1);
    assertThat(mods[0].getModificationOp()).isEqualTo(DirContext.REPLACE_ATTRIBUTE);
    Attribute attr = mods[0].getAttribute();
    assertThat((String) attr.getID()).isEqualTo("abc");
    assertThat((String) attr.get()).isEqualTo("234");
}
项目:projectforge-webapp    文件:LdapDao.java   
public void modify(final DirContext ctx, final T obj, final List<ModificationItem> modificationItems) throws NamingException
{
  final Object id = getId(obj);
  // The dn is may-be changed, so find the original dn by id:
  final T origObject = findById(ctx, id, obj.getOrganizationalUnit());
  if (origObject == null) {
    throw new RuntimeException("Object with id "
        + id
        + " not found in search base '"
        + StringHelper.listToString(",", obj.getOrganizationalUnit())
        + "'. Can't modify the object: "
        + obj);
  }
  final String dn = origObject.getDn();
  log.info("Modify attributes of " + getObjectClass() + ": " + dn + ": " + getLogInfo(obj));
  final ModificationItem[] items = modificationItems.toArray(new ModificationItem[modificationItems.size()]);
  ctx.modifyAttributes(dn, items);
  // Don't move object.
  // if (obj.getDn() != null && StringUtils.equals(dn, obj.getDn()) == false) {
  // log.info("DN of object is changed from '" + dn + "' to '" + obj.getDn());
  // ctx.rename(dn, obj.getDn());
  // }
}
项目:projectforge-webapp    文件:LdapUserDao.java   
public void changePassword(final LdapUser user, final String oldPassword, final String newPassword)
{
  log.info("Change password for " + getObjectClass() + ": " + buildDn(null, user));
  final List<ModificationItem> modificationItems = new ArrayList<ModificationItem>();
  if (oldPassword != null) {
    modificationItems.add(new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("userPassword", oldPassword)));
    modificationItems.add(new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("userPassword", newPassword)));
  } else {
    modificationItems.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userPassword", newPassword)));
  }
  if (isSambaAccountsConfigured() == true && user.getSambaSIDNumber() != null) {
    final String sambaNTPassword = SmbEncrypt.NTUNICODEHash(newPassword);
    modificationItems.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("sambaNTPassword", sambaNTPassword)));
  }
  // Perform the update
  modify(user, modificationItems);
}
项目:spring-ldap    文件:ModifyAttributesOperationExecutorTest.java   
@Test
public void testCommit() {
    ModificationItem[] expectedCompensatingItems = new ModificationItem[0];
    ModificationItem[] expectedActualItems = new ModificationItem[0];

    Name expectedDn = LdapUtils.newLdapName("cn=john doe");

    ModifyAttributesOperationExecutor tested = new ModifyAttributesOperationExecutor(ldapOperationsMock,
            expectedDn, expectedActualItems, expectedCompensatingItems);

    // No operation here
       verifyNoMoreInteractions(ldapOperationsMock);

    // Perform test
    tested.commit();
}
项目:ldap2rest    文件:LdapModificationUtils.java   
/**
 * Ajoute un ModificationItem à la liste <code>modificationItems</code>
 * Si la valeur <code>value</code> est null
 *  alors aucune modification n'est appliquée
 * Si la valeur est vide
 *  alors une suppression est appliqué
 * Sinon
 *  une modification est appliqué
 * 
 * @param modificationItems
 * @param attributeName
 * @param value
 */
public static void addMoficicationItemRemoveIfBlankElseReplace(List<ModificationItem> modificationItems, String attributeName, String value, String previousValue){
    if (value != null){
        if (StringUtils.isBlank(value)){
            if (StringUtils.isNotBlank(previousValue)){
                modificationItems.add(new ModificationItem(
                            DirContext.REMOVE_ATTRIBUTE, 
                            new BasicAttribute(attributeName)));
            }
            //Sinon, on ne fait rien: on veut remplacer du vide pas du vide...

        }
        else{
            modificationItems.add(new ModificationItem(
                    DirContext.REPLACE_ATTRIBUTE, 
                    new BasicAttribute(attributeName, value)));
        }
    }
}
项目:spring-ldap    文件:DirContextAdapterTest.java   
@Test
public void testChangeMultiAttribute_RemoveTwoValues() throws Exception {
    final Attributes fixtureAttrs = new BasicAttributes();
    Attribute multi = new BasicAttribute("abc");
    multi.add("123");
    multi.add("qwe");
    multi.add("rty");
    fixtureAttrs.put(multi);
    class TestableDirContextAdapter extends DirContextAdapter {
        public TestableDirContextAdapter() {
            super(fixtureAttrs, null);
            setUpdateMode(true);
        }
    }
    tested = new TestableDirContextAdapter();
    assertThat(tested.isUpdateMode()).isTrue();
    tested.setAttributeValues("abc", new String[] { "123" });

    ModificationItem[] modificationItems = tested.getModificationItems();
    assertThat(modificationItems.length).isEqualTo(1);
    assertThat(modificationItems[0].getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
    assertThat(modificationItems[0].getAttribute().get(0)).isEqualTo("qwe");
    assertThat(modificationItems[0].getAttribute().get(1)).isEqualTo("rty");
}
项目:plugin-id-ldap    文件:UserLdapRepository.java   
@Override
public void unlock(final UserOrg user) {
    if (user.getIsolated() == null && user.getLockedBy() != null) {
        // Need to be unlocked
        final ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute(lockedAttribute));
        template.modifyAttributes(org.springframework.ldap.support.LdapUtils.newLdapName(user.getDn()), mods);

        // Also clear the disabled state from cache
        user.setLocked(null);
        user.setLockedBy(null);
    }
}