Java Code Examples for javax.naming.directory.Attribute#add()

The following examples show how to use javax.naming.directory.Attribute#add() . 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: LdapUtil.java    From herd-mdl with Apache License 2.0 8 votes vote down vote up
/**
 * Create ldap AD group and add user to newly created AD group
 *
 * @param adGroupName ldap AD group name to create
 * @param userId      uid of existing ldap user to be added to newly created AD group
 * @throws NamingException
 */
public static void createAdGroup(String adGroupName, String userId) throws NamingException {
    DirContext ldapContext = getLdapContext(User.getLdapAdminUser());
    String groupDn = constructGroupDn(adGroupName, OU_GROUPS);
    String memberDn = constructEntryCn(userId, OU_PEOPLE);

    //Create attributes to be associated with the new group
    Attributes attrs = new BasicAttributes(true);
    Attribute objclass = new BasicAttribute("objectClass");
    objclass.add("top");
    objclass.add("groupOfNames");
    attrs.put("cn", adGroupName);
    attrs.put(objclass);
    BasicAttribute member = new BasicAttribute("member", memberDn);
    attrs.put(member);

    ldapContext.createSubcontext(groupDn, attrs);
    LOGGER.info("Created group: " + adGroupName);
}
 
Example 2
Source File: LdapConnection.java    From hop with Apache License 2.0 6 votes vote down vote up
private Attributes buildAttributes( String dn, String[] attributes, String[] values, String multValuedSeparator ) {
  Attributes attrs = new javax.naming.directory.BasicAttributes( true );
  int nrAttributes = attributes.length;
  for ( int i = 0; i < nrAttributes; i++ ) {
    if ( !Utils.isEmpty( values[ i ] ) ) {
      // We have a value
      String value = values[ i ].trim();
      if ( multValuedSeparator != null && value.indexOf( multValuedSeparator ) > 0 ) {
        Attribute attr = new javax.naming.directory.BasicAttribute( attributes[ i ] );
        for ( String attribute : value.split( multValuedSeparator ) ) {
          attr.add( attribute );
        }
        attrs.put( attr );
      } else {
        attrs.put( attributes[ i ], value );
      }
    }
  }
  return attrs;
}
 
Example 3
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetStringAttributesWhenMultiValueAttributeExists() throws Exception {
	final Attributes attrs = new BasicAttributes();
	Attribute multi = new BasicAttribute("abc");
	multi.add("123");
	multi.add("234");
	attrs.put(multi);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(attrs, null);
		}
	}
	tested = new TestableDirContextAdapter();
	String s[] = tested.getStringAttributes("abc");
	assertThat(s[0]).isEqualTo("123");
	assertThat(s[1]).isEqualTo("234");
	assertThat(s.length).isEqualTo(2);
}
 
Example 4
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testChangeMultiAttribute_AddValue() 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[] { "123", "qwe", "klytt" });

	ModificationItem[] modificationItems = tested.getModificationItems();
	assertThat(modificationItems.length).isEqualTo(1);
    assertThat(modificationItems[0].getModificationOp()).isEqualTo(DirContext.ADD_ATTRIBUTE);
	assertThat(modificationItems[0].getAttribute().get()).isEqualTo("klytt");
}
 
Example 5
Source File: DirContextAdapterTest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAttributesSortedStringSetExists() throws Exception {
	final Attributes attrs = new BasicAttributes();
	Attribute multi = new BasicAttribute("abc");
	multi.add("123");
	multi.add("234");
	attrs.put(multi);
	class TestableDirContextAdapter extends DirContextAdapter {
		public TestableDirContextAdapter() {
			super(attrs, null);
		}
	}
	tested = new TestableDirContextAdapter();
	SortedSet s = tested.getAttributeSortedStringSet("abc");
	assertThat(s).isNotNull();
	assertThat(s).hasSize(2);
	Iterator it = s.iterator();
	assertThat(it.next()).isEqualTo("123");
	assertThat(it.next()).isEqualTo("234");
}
 
Example 6
Source File: Jetel2LdapData.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 
 */
@Override
public void setAttribute(Attribute attr, DataField df) throws BadDataFormatException {

	/*
	 * df is null in the DataRecord. It's a real problem, 
	 * if the value is null, df is not and reply true to isNull.			 
	 */
	if (df == null) {
		throw new NullPointerException("Field " + attr.getID() + " is null.");
	} else if (df.getType() != DataFieldMetadata.BYTE_FIELD
			&& df.getType() != DataFieldMetadata.BYTE_FIELD_COMPRESSED) {
		throw new BadDataFormatException("LDAP transformation exception : Field " + attr.getID() + " is not a Byte array.");
	} else if (df.isNull()) {
		// Set Ldap Attr value to null
		attr.clear();
	} else {
		Object[] values = getvalues(df);
		for(int i = 0; i < values.length; i++) {
			Object o = values[i];
			if (!attr.add(o)) {
				throw new BadDataFormatException("LDAP transformation exception : Field " + attr.getID() + " is not a Byte array.");
			}
		}
	}
}
 
Example 7
Source File: MyUser.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public MyUser(String userId, String surName, String commonName) {
    myAttrs = new BasicAttributes(true);  // Case ignore
    Attribute oc = new BasicAttribute("objectclass");
    oc.add("inetOrgPerson");
    oc.add("organizationalPerson");
    oc.add("person");
    oc.add("top");

    Attribute sn = new BasicAttribute("sn");
    sn.add(surName);

    Attribute cn = new BasicAttribute("cn");
    cn.add(commonName);

    Attribute uid = new BasicAttribute("uid");
    uid.add(userId);

    myAttrs.put(sn);
    myAttrs.put(cn);
    myAttrs.put(uid);
    myAttrs.put(oc);

}
 
Example 8
Source File: Rdn.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Retrieves the {@link javax.naming.directory.Attributes Attributes}
 * view of the type/value mappings contained in this Rdn.
 *
 * @return  The non-null attributes containing the type/value
 *          mappings of this Rdn.
 */
public Attributes toAttributes() {
    Attributes attrs = new BasicAttributes(true);
    for (int i = 0; i < entries.size(); i++) {
        RdnEntry entry = entries.get(i);
        Attribute attr = attrs.put(entry.getType(), entry.getValue());
        if (attr != null) {
            attr.add(entry.getValue());
            attrs.put(attr);
        }
    }
    return attrs;
}
 
Example 9
Source File: Rdn.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the {@link javax.naming.directory.Attributes Attributes}
 * view of the type/value mappings contained in this Rdn.
 *
 * @return  The non-null attributes containing the type/value
 *          mappings of this Rdn.
 */
public Attributes toAttributes() {
    Attributes attrs = new BasicAttributes(true);
    for (int i = 0; i < entries.size(); i++) {
        RdnEntry entry = entries.get(i);
        Attribute attr = attrs.put(entry.getType(), entry.getValue());
        if (attr != null) {
            attr.add(entry.getValue());
            attrs.put(attr);
        }
    }
    return attrs;
}
 
Example 10
Source File: LdapName.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
Attributes toAttributes() {
    Attributes attrs = new BasicAttributes(true);
    TypeAndValue tv;
    Attribute attr;

    for (int i = 0; i < tvs.size(); i++) {
        tv = tvs.elementAt(i);
        if ((attr = attrs.get(tv.getType())) == null) {
            attrs.put(tv.getType(), tv.getUnescapedValue());
        } else {
            attr.add(tv.getUnescapedValue());
        }
    }
    return attrs;
}
 
Example 11
Source File: LdapName.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
Attributes toAttributes() {
    Attributes attrs = new BasicAttributes(true);
    TypeAndValue tv;
    Attribute attr;

    for (int i = 0; i < tvs.size(); i++) {
        tv = tvs.elementAt(i);
        if ((attr = attrs.get(tv.getType())) == null) {
            attrs.put(tv.getType(), tv.getUnescapedValue());
        } else {
            attr.add(tv.getUnescapedValue());
        }
    }
    return attrs;
}
 
Example 12
Source File: Rdn.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Retrieves the {@link javax.naming.directory.Attributes Attributes}
 * view of the type/value mappings contained in this Rdn.
 *
 * @return  The non-null attributes containing the type/value
 *          mappings of this Rdn.
 */
public Attributes toAttributes() {
    Attributes attrs = new BasicAttributes(true);
    for (int i = 0; i < entries.size(); i++) {
        RdnEntry entry = entries.get(i);
        Attribute attr = attrs.put(entry.getType(), entry.getValue());
        if (attr != null) {
            attr.add(entry.getValue());
            attrs.put(attr);
        }
    }
    return attrs;
}
 
Example 13
Source File: LdapName.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
Attributes toAttributes() {
    Attributes attrs = new BasicAttributes(true);
    TypeAndValue tv;
    Attribute attr;

    for (int i = 0; i < tvs.size(); i++) {
        tv = tvs.elementAt(i);
        if ((attr = attrs.get(tv.getType())) == null) {
            attrs.put(tv.getType(), tv.getUnescapedValue());
        } else {
            attr.add(tv.getUnescapedValue());
        }
    }
    return attrs;
}
 
Example 14
Source File: LdapUtil.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
/**
 * create ldap user with provided user id and user password
 *
 * @param user new ldap user to create
 * @throws NamingException
 */
public static void addEntry(User user) throws NamingException {
    String username = user.getUsername();

    Attribute userCn = new BasicAttribute("cn", user.getUsername());
    Attribute userSn = new BasicAttribute("sn", "null");
    Attribute uid = new BasicAttribute("uid", user.getUsername());

    Attribute uidNumber = new BasicAttribute("uidNumber", String.valueOf(listEntries() + 1));
    Attribute gidNumber = new BasicAttribute("gidNumber", String.valueOf(1001));
    Attribute homeDirectory = new BasicAttribute("homeDirectory", "/home/" + username);
    Attribute mail = new BasicAttribute("mail", username + "@" + DOMAIN_NAME);
    Attribute loginShell = new BasicAttribute("loginShell", "/bin/bash");

    Attribute userUserPassword = new BasicAttribute("userPassword", user.getPassword());
    //ObjectClass attributes
    Attribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("inetOrgPerson");
    objectClass.add("posixAccount");

    Attributes entry = new BasicAttributes();
    entry.put(userCn);
    entry.put(userSn);
    entry.put(userUserPassword);
    entry.put(objectClass);
    entry.put(uid);

    entry.put(uidNumber);
    entry.put(gidNumber);
    entry.put(homeDirectory);
    entry.put(mail);
    entry.put(loginShell);

    String ou = user.getOu() == null ? "People" : user.getOu();
    String entryDN = constructEntryCn(user.getUsername(), ou);
    DirContext ldapContext = getLdapContext(User.getLdapAdminUser());
    ldapContext.createSubcontext(entryDN, entry);
    LOGGER.info("Added Entry :" + entryDN);
}
 
Example 15
Source File: Rdn.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Retrieves the {@link javax.naming.directory.Attributes Attributes}
 * view of the type/value mappings contained in this Rdn.
 *
 * @return  The non-null attributes containing the type/value
 *          mappings of this Rdn.
 */
public Attributes toAttributes() {
    Attributes attrs = new BasicAttributes(true);
    for (int i = 0; i < entries.size(); i++) {
        RdnEntry entry = entries.get(i);
        Attribute attr = attrs.put(entry.getType(), entry.getValue());
        if (attr != null) {
            attr.add(entry.getValue());
            attrs.put(attr);
        }
    }
    return attrs;
}
 
Example 16
Source File: LDAPServerStoreManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private Attribute getChangePasswordAttribute(Attribute oldPasswordAttribute, Object oldCredential,
                                             Object newPassword)
        throws DirectoryServerManagerException {

    String passwordHashMethod = null;
    // when admin changes other user passwords he do not have to provide
    // the old password.
    if (oldCredential != null) {
        // here it is only possible to have one password, if there are more
        // every one should match with the given old password

        try {
            NamingEnumeration passwords = oldPasswordAttribute.getAll();

            if (passwords.hasMore()) {
                byte[] byteArray = (byte[]) passwords.next();
                String password = new String(byteArray, StandardCharsets.UTF_8);

                if (password.startsWith("{")) {
                    passwordHashMethod = password.substring(password.indexOf("{") + 1, password.indexOf("}"));
                }

                if (!password.equals(getPasswordToStore((String) oldCredential, passwordHashMethod))) {
                    throw new DirectoryServerManagerException("Old password does not match");
                }
            }
        } catch (NamingException e) {
            log.error("Unable to retrieve old password details.", e);
            throw new DirectoryServerManagerException("Could not find old password details");
        }
    }

    Attribute passwordAttribute = new BasicAttribute(LDAPServerManagerConstants.LDAP_PASSWORD);
    passwordAttribute.add(getPasswordToStore((String) newPassword, passwordHashMethod));

    return passwordAttribute;

}
 
Example 17
Source File: LdapName.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
Attributes toAttributes() {
    Attributes attrs = new BasicAttributes(true);
    TypeAndValue tv;
    Attribute attr;

    for (int i = 0; i < tvs.size(); i++) {
        tv = tvs.elementAt(i);
        if ((attr = attrs.get(tv.getType())) == null) {
            attrs.put(tv.getType(), tv.getUnescapedValue());
        } else {
            attr.add(tv.getUnescapedValue());
        }
    }
    return attrs;
}
 
Example 18
Source File: LdapFormatter.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void fillFromMap(Attributes attrs, MapDataField field){
	Map<String,CloverString> map= field.getValue(CloverString.class);
	
	for(Map.Entry<String,CloverString> entry: map.entrySet()){
		Attribute attr = new BasicAttribute(entry.getKey());
		attr.add( new Object[] { entry.getValue().toString() });
		attrs.put(attr);
	}
	
}
 
Example 19
Source File: Rdn.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Retrieves the {@link javax.naming.directory.Attributes Attributes}
 * view of the type/value mappings contained in this Rdn.
 *
 * @return  The non-null attributes containing the type/value
 *          mappings of this Rdn.
 */
public Attributes toAttributes() {
    Attributes attrs = new BasicAttributes(true);
    for (int i = 0; i < entries.size(); i++) {
        RdnEntry entry = entries.get(i);
        Attribute attr = attrs.put(entry.getType(), entry.getValue());
        if (attr != null) {
            attr.add(entry.getValue());
            attrs.put(attr);
        }
    }
    return attrs;
}
 
Example 20
Source File: LDAPServerStoreManager.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private Attribute getChangePasswordAttribute(Attribute oldPasswordAttribute, Object oldCredential,
                                             Object newPassword)
        throws DirectoryServerManagerException {

    String passwordHashMethod = null;
    // when admin changes other user passwords he do not have to provide
    // the old password.
    if (oldCredential != null) {
        // here it is only possible to have one password, if there are more
        // every one should match with the given old password

        try {
            NamingEnumeration passwords = oldPasswordAttribute.getAll();

            if (passwords.hasMore()) {
                byte[] byteArray = (byte[]) passwords.next();
                String password = new String(byteArray, StandardCharsets.UTF_8);

                if (password.startsWith("{")) {
                    passwordHashMethod = password.substring(password.indexOf("{") + 1, password.indexOf("}"));
                }

                if (!password.equals(getPasswordToStore((String) oldCredential, passwordHashMethod))) {
                    throw new DirectoryServerManagerException("Old password does not match");
                }
            }
        } catch (NamingException e) {
            log.error("Unable to retrieve old password details.", e);
            throw new DirectoryServerManagerException("Could not find old password details");
        }
    }

    Attribute passwordAttribute = new BasicAttribute(LDAPServerManagerConstants.LDAP_PASSWORD);
    passwordAttribute.add(getPasswordToStore((String) newPassword, passwordHashMethod));

    return passwordAttribute;

}