下面列出了怎么用javax.naming.directory.BasicAttribute的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testChangeMultiAttribute_SameValue() 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" });
ModificationItem[] modificationItems = tested.getModificationItems();
assertThat(modificationItems.length).isEqualTo(0);
}
public static Context getURLContext(
String scheme, Hashtable<?,?> environment)
throws NamingException {
return new DnsContext("", null, new Hashtable<String,String>()) {
public Attributes getAttributes(String name, String[] attrIds)
throws NamingException {
return new BasicAttributes() {
public Attribute get(String attrID) {
BasicAttribute ba = new BasicAttribute(attrID);
ba.add("1 1 99 b.com.");
ba.add("0 0 88 a.com."); // 2nd has higher priority
return ba;
}
};
}
};
}
public static Context getURLContext(
String scheme, Hashtable<?,?> environment)
throws NamingException {
return new DnsContext("", null, new Hashtable<String,String>()) {
public Attributes getAttributes(String name, String[] attrIds)
throws NamingException {
return new BasicAttributes() {
public Attribute get(String attrID) {
BasicAttribute ba = new BasicAttribute(attrID);
ba.add("1 1 99 b.com.");
ba.add("0 0 88 a.com."); // 2nd has higher priority
return ba;
}
};
}
};
}
public static Context getURLContext(
String scheme, Hashtable<?,?> environment)
throws NamingException {
return new DnsContext("", null, new Hashtable<String,String>()) {
public Attributes getAttributes(String name, String[] attrIds)
throws NamingException {
return new BasicAttributes() {
public Attribute get(String attrID) {
BasicAttribute ba = new BasicAttribute(attrID);
ba.add("1 1 99 b.com.");
ba.add("0 0 88 a.com."); // 2nd has higher priority
return ba;
}
};
}
};
}
@Test
public void testRemoveOneOfSeveralDnAttributeSyntacticallyEqual() throws NamingException {
BasicAttributes attributes = new BasicAttributes();
BasicAttribute attribute = new BasicAttribute("uniqueMember", "cn=john doe,OU=company");
attribute.add("cn=jane doe, ou=company");
attributes.put(attribute);
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");
assertThat(modificationItem.getAttribute().get()).isEqualTo("cn=john doe,OU=company");
}
/**
* Test a conversion of an attributes from a LDIF file
* @throws org.apache.directory.api.ldap.model.ldif.LdapLdifException
*/
@Test
public void testConvertAttributesfromLdif() throws LdapException, LdapLdifException
{
Attributes attributes = new BasicAttributes( true );
Attribute oc = new BasicAttribute( "objectclass" );
oc.add( "top" );
oc.add( "person" );
oc.add( "inetorgPerson" );
attributes.put( oc );
attributes.put( "cn", "Saarbrucken" );
attributes.put( "sn", "test" );
String ldif = LdifUtils.convertToLdif( attributes, ( Dn ) null, 15 );
Attributes result = LdifUtils.getJndiAttributesFromLdif( ldif );
assertEquals( attributes, result );
}
private LDAPInitialDirContextFactoryImpl getMockedLDAPSearchResult(boolean withEmail) throws NamingException
{
@SuppressWarnings("unchecked")
NamingEnumeration<SearchResult> mockedNamingEnumeration = mock(NamingEnumeration.class);
when(mockedNamingEnumeration.hasMore()).thenReturn(true).thenReturn(false);
BasicAttributes attributes = new BasicAttributes();
attributes.put(new BasicAttribute("sAMAccountName", "U1"));
attributes.put(new BasicAttribute("givenName", "U1"));
if (withEmail)
{
attributes.put(new BasicAttribute("mail", "[email protected]"));
}
SearchResult mockedSearchResult = new SearchResult("CN:U1", null, attributes);
mockedSearchResult.setNameInNamespace("CN:U1");
when(mockedNamingEnumeration.next()).thenReturn(mockedSearchResult);
InitialDirContext mockedInitialDirContext = mock(InitialDirContext.class);
when(mockedInitialDirContext.search((String)any(), anyString(), any(SearchControls.class))).thenReturn(mockedNamingEnumeration);
LDAPInitialDirContextFactoryImpl mockedLdapInitialDirContextFactory = mock(LDAPInitialDirContextFactoryImpl.class);
when(mockedLdapInitialDirContextFactory.getDefaultIntialDirContext(0)).thenReturn(mockedInitialDirContext);
return mockedLdapInitialDirContextFactory;
}
@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");
}
@Test
public void testRemoveMultiAttribute() throws Exception {
final Attributes fixtureAttrs = new BasicAttributes();
Attribute abc = new BasicAttribute("abc");
abc.add("123");
abc.add("456");
fixtureAttrs.put(abc);
class TestableDirContextAdapter extends DirContextAdapter {
public TestableDirContextAdapter() {
super(fixtureAttrs, null);
setUpdateMode(true);
}
}
tested = new TestableDirContextAdapter();
tested.setUpdateMode(true);
tested.setAttributeValues("abc", new String[] {});
ModificationItem[] mods = tested.getModificationItems();
assertThat(mods.length).isEqualTo(1);
assertThat(mods[0].getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
Attribute attr = mods[0].getAttribute();
assertThat((String) attr.getID()).isEqualTo("abc");
assertThat(attr.size()).isEqualTo(0);
}
public static Context getURLContext(
String scheme, Hashtable<?,?> environment)
throws NamingException {
return new DnsContext("", null, new Hashtable<String,String>()) {
public Attributes getAttributes(String name, String[] attrIds)
throws NamingException {
return new BasicAttributes() {
public Attribute get(String attrID) {
BasicAttribute ba = new BasicAttribute(attrID);
ba.add("1 1 99 b.com.");
ba.add("0 0 88 a.com."); // 2nd has higher priority
return ba;
}
};
}
};
}
@Test
public void testAddAttribute_Multivalue() 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("def", new String[] { "kalle", "klytt" });
ModificationItem[] modificationItems = tested.getModificationItems();
assertThat(modificationItems.length).isEqualTo(1);
assertThat(modificationItems[0].getAttribute().getID()).isEqualTo("def");
}
@Test
public void testNoChangeMultiAttribute() 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" });
ModificationItem[] mods = tested.getModificationItems();
assertThat(mods.length).isEqualTo(0);
String[] modNames = tested.getNamesOfModifiedAttributes();
assertThat(modNames.length).isEqualTo(0);
}
public static Context getURLContext(
String scheme, Hashtable<?,?> environment)
throws NamingException {
return new DnsContext("", null, new Hashtable<String,String>()) {
public Attributes getAttributes(String name, String[] attrIds)
throws NamingException {
return new BasicAttributes() {
public Attribute get(String attrID) {
BasicAttribute ba = new BasicAttribute(attrID);
ba.add("1 1 99 b.com.");
ba.add("0 0 88 a.com."); // 2nd has higher priority
return ba;
}
};
}
};
}
@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 testAddAttributeValueInUpdateModeAttributeWhenOtherValueExistsInOrigAttrs()
throws NamingException {
tested.setAttribute(new BasicAttribute("abc", "321"));
tested.setUpdateMode(true);
// Perform test
tested.addAttributeValue("abc", "123");
Attributes attrs = tested.getAttributes();
assertThat(attrs.get("abc")).isNotNull();
ModificationItem[] modificationItems = tested.getModificationItems();
assertThat(modificationItems.length).isEqualTo(1);
Attribute attribute = modificationItems[0].getAttribute();
assertThat(attribute.size()).isEqualTo(1);
assertThat(attribute.getID()).isEqualTo("abc");
assertThat(attribute.get()).isEqualTo("123");
}
private BasicAttribute createBinaryBasicAttribute(String attrName, Set<String> attrValue) {
BasicAttribute attr = new BasicAttribute(attrName);
for (String value : attrValue) {
if (value == null || value.trim().length() == 0) {
value = LDAPConstants.EMPTY_ATTRIBUTE_VALUE;
}
try {
byte[] bytes = Base64.decode(value);
attr.add(bytes);
} catch (IOException ioe) {
logger.warnf("Wasn't able to Base64 decode the attribute value. Ignoring attribute update. Attribute: %s, Attribute value: %s", attrName, attrValue);
}
}
return attr;
}
@Test
public void testGetCompensatingModificationItem_AddNonExistingAttribute()
throws NamingException {
Attributes attributes = new BasicAttributes();
BasicAttribute modificationAttribute = new BasicAttribute("someattr");
modificationAttribute.add("newvalue1");
modificationAttribute.add("newvalue2");
ModificationItem originalItem = new ModificationItem(
DirContext.ADD_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);
}
@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;
}
@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);
}
@Test
public void testCollectAttributeValues() {
String expectedAttributeName = "someAttribute";
BasicAttribute expectedAttribute = new BasicAttribute(expectedAttributeName);
expectedAttribute.add("value1");
expectedAttribute.add("value2");
BasicAttributes attributes = new BasicAttributes();
attributes.put(expectedAttribute);
LinkedList list = new LinkedList();
LdapUtils.collectAttributeValues(attributes, expectedAttributeName, list);
assertThat(list).hasSize(2);
assertThat(list.get(0)).isEqualTo("value1");
assertThat(list.get(1)).isEqualTo("value2");
}
@Test
public void testSubjectMatterExpertContactDetailsMapper() throws Exception
{
// Create a subject matter expert contact details mapper.
SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper subjectMatterExpertContactDetailsMapper =
new SubjectMatterExpertDaoImpl.SubjectMatterExpertContactDetailsMapper(LDAP_ATTRIBUTE_USER_FULL_NAME, LDAP_ATTRIBUTE_USER_JOB_TITLE,
LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS, LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER);
// Create attributes object with ignoreCase flag set to "true".
BasicAttributes attributes = new BasicAttributes(true);
// Populate the attributes with predefined set of results.
attributes.put(new BasicAttribute(LDAP_ATTRIBUTE_USER_FULL_NAME, USER_FULL_NAME));
attributes.put(new BasicAttribute(LDAP_ATTRIBUTE_USER_JOB_TITLE, USER_JOB_TITLE));
attributes.put(new BasicAttribute(LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS, USER_EMAIL_ADDRESS));
attributes.put(new BasicAttribute(LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER, USER_TELEPHONE_NUMBER));
// Map the results.
List<SubjectMatterExpertContactDetails> result = Collections.singletonList(subjectMatterExpertContactDetailsMapper.mapFromAttributes(attributes));
// Validate the results.
assertEquals(
Collections.singletonList(new SubjectMatterExpertContactDetails(USER_FULL_NAME, USER_JOB_TITLE, USER_EMAIL_ADDRESS, USER_TELEPHONE_NUMBER)),
result);
}
public static Context getURLContext(
String scheme, Hashtable<?,?> environment)
throws NamingException {
return new DnsContext("", null, new Hashtable<String,String>()) {
public Attributes getAttributes(String name, String[] attrIds)
throws NamingException {
return new BasicAttributes() {
public Attribute get(String attrID) {
BasicAttribute ba = new BasicAttribute(attrID);
ba.add("1 1 99 b.com.");
ba.add("0 0 88 a.com."); // 2nd has higher priority
return ba;
}
};
}
};
}
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);
}
}
private void updateADPassword(String userDN, String password, LDAPOperationDecorator passwordUpdateDecorator) {
try {
// Replace the "unicdodePwd" attribute with a new value
// Password must be both Unicode and a quoted string
String newQuotedPassword = "\"" + password + "\"";
byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
BasicAttribute unicodePwd = new BasicAttribute("unicodePwd", newUnicodePassword);
List<ModificationItem> modItems = new ArrayList<ModificationItem>();
modItems.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, unicodePwd));
operationManager.modifyAttributes(userDN, modItems.toArray(new ModificationItem[] {}), passwordUpdateDecorator);
} catch (ModelException me) {
throw me;
} catch (Exception e) {
throw new ModelException(e);
}
}
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);
}
protected void saveCertificate(X509Certificate cert, String dn, Map<String, String> appAttrs) {
Attributes attribs = new BasicAttributes();
attribs.put(new BasicAttribute(ATTR_OBJECT_CLASS, ldapConfig.getCertObjectClass()));
attribs.put(new BasicAttribute(ldapConfig.getAttrUID(), cert.getSubjectX500Principal().getName()));
attribs.put(new BasicAttribute(ldapConfig.getAttrIssuerID(), cert.getIssuerX500Principal().getName()));
attribs.put(new BasicAttribute(ldapConfig.getAttrSerialNumber(), cert.getSerialNumber().toString(16)));
addConstantAttributes(ldapConfig.getConstAttrNamesCSV(), ldapConfig.getConstAttrValuesCSV(), attribs);
if (appAttrs != null && !appAttrs.isEmpty()) {
for (Map.Entry<String, String> entry : appAttrs.entrySet()) {
attribs.put(new BasicAttribute(entry.getKey(), entry.getValue()));
}
}
try {
attribs.put(new BasicAttribute(ldapConfig.getAttrCrtBinary(), cert.getEncoded()));
ldapSearch.bind(dn, attribs);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
@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");
}
public void createIfNotExist(final String ou, final String description, final String... organizationalUnits)
{
new LdapTemplate(ldapConnector) {
@Override
protected Object call() throws NameNotFoundException, Exception
{
final String path = LdapUtils.getOu(ou, organizationalUnits);
if (doesExist(ctx, ou, organizationalUnits) == true) {
log.info(OBJECT_CLASS + " does already exist (OK): " + path);
return null;
}
log.info("Create " + OBJECT_CLASS + ": " + path);
final Attributes attrs = new BasicAttributes();
final BasicAttribute ocattr = new BasicAttribute("objectclass");
ocattr.add("top");
ocattr.add(OBJECT_CLASS);
attrs.put(ocattr);
LdapUtils.putAttribute(attrs, "ou", ou);
LdapUtils.putAttribute(attrs, "description", description);
ctx.bind(path, null, attrs);
return null;
}
}.excecute();
}
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 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);
}