下面列出了javax.naming.directory.Attribute#add ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
@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);
}
/**
*
*/
@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.");
}
}
}
}
/**
* 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);
}
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);
}
@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");
}
@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");
}
/**
* 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;
}
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;
}
/**
* 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;
}
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);
}
}
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;
}
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;
}
/**
* 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;
}
/**
* 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);
}
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;
}
/**
* 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;
}
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;
}
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;
}
/**
* 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;
}