下面列出了怎么用javax.naming.directory.BasicAttributes的API类实例代码及写法,或者点击链接到github查看源代码。
private NamingEnumeration<SearchResult> mockSearchResults(String password)
throws NamingException {
@SuppressWarnings("unchecked")
NamingEnumeration<SearchResult> searchResults =
EasyMock.createNiceMock(NamingEnumeration.class);
EasyMock.expect(Boolean.valueOf(searchResults.hasMore()))
.andReturn(Boolean.TRUE)
.andReturn(Boolean.FALSE)
.andReturn(Boolean.TRUE)
.andReturn(Boolean.FALSE);
EasyMock.expect(searchResults.next())
.andReturn(new SearchResult("ANY RESULT", "",
new BasicAttributes(USER_PASSWORD_ATTR, password)))
.times(2);
EasyMock.replay(searchResults);
return searchResults;
}
@Test
public void testSearch_String_SearchControls_ContextMapper_DirContextProcessor() throws Exception {
expectGetReadOnlyContext();
SearchControls controls = searchControlsRecursive();
Object expectedObject = new Object();
SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes());
singleSearchResultWithStringBase(controls, searchResult);
Object expectedResult = expectedObject;
when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult);
List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, contextMapperMock,
dirContextProcessorMock);
verify(dirContextProcessorMock).preProcess(dirContextMock);
verify(dirContextProcessorMock).postProcess(dirContextMock);
verify(namingEnumerationMock).close();
verify(dirContextMock).close();
assertThat(list).isNotNull();
assertThat(list).hasSize(1);
assertThat(list.get(0)).isSameAs(expectedResult);
}
boolean compareToSearchResult(String name) {
boolean successful = false;
switch (status) {
case LdapClient.LDAP_COMPARE_TRUE:
status = LdapClient.LDAP_SUCCESS;
entries = new Vector<>(1,1);
Attributes attrs = new BasicAttributes(LdapClient.caseIgnore);
LdapEntry entry = new LdapEntry( name, attrs );
entries.addElement(entry);
successful = true;
break;
case LdapClient.LDAP_COMPARE_FALSE:
status = LdapClient.LDAP_SUCCESS;
entries = new Vector<>(0);
successful = true;
break;
default:
successful = false;
break;
}
return successful;
}
@Test
public void testNoChangeAttribute() 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();
assertThat(tested.isUpdateMode()).isTrue();
tested.setAttributeValue("abc", "123"); // change
ModificationItem[] mods = tested.getModificationItems();
assertThat(mods.length).isEqualTo(0);
}
@Test
public void testLookup_String_ReturnAttributes_ContextMapper()
throws Exception {
expectGetReadOnlyContext();
String[] attributeNames = new String[] { "cn" };
BasicAttributes expectedAttributes = new BasicAttributes();
expectedAttributes.put("cn", "Some Name");
when(dirContextMock.getAttributes(DEFAULT_BASE_STRING, attributeNames)).thenReturn(expectedAttributes);
LdapName name = LdapUtils.newLdapName(DEFAULT_BASE_STRING);
DirContextAdapter adapter = new DirContextAdapter(expectedAttributes,
name);
Object transformed = new Object();
when(contextMapperMock.mapFromContext(adapter)).thenReturn(transformed);
Object actual = tested.lookup(DEFAULT_BASE_STRING, attributeNames,
contextMapperMock);
verify(dirContextMock).close();
assertThat(actual).isSameAs(transformed);
}
@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);
}
@Test
public void testLookup_String_AttributesMapper() throws Exception {
expectGetReadOnlyContext();
BasicAttributes expectedAttributes = new BasicAttributes();
when(dirContextMock.getAttributes(DEFAULT_BASE_STRING)).thenReturn(expectedAttributes);
Object expected = new Object();
when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected);
Object actual = tested
.lookup(DEFAULT_BASE_STRING, attributesMapperMock);
verify(dirContextMock).close();
assertThat(actual).isSameAs(expected);
}
@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 verifyThatFindOneThrowsIncorrectResultSizeDataAccessExceptionWhenMoreResults() throws Exception {
Class<Object> expectedClass = Object.class;
when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock);
when(odmMock.filterFor(expectedClass,
new EqualsFilter("ou", "somevalue"))).thenReturn(new EqualsFilter("ou", "somevalue"));
DirContextAdapter expectedObject = new DirContextAdapter();
SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes());
setupSearchResults(searchControlsRecursive(), new SearchResult[]{searchResult, searchResult});
Object expectedResult = expectedObject;
when(odmMock.mapFromLdapDataEntry(expectedObject, expectedClass)).thenReturn(expectedResult, expectedResult);
try {
tested.findOne(query().where("ou").is("somevalue"), expectedClass);
fail("EmptyResultDataAccessException expected");
} catch (IncorrectResultSizeDataAccessException expected) {
assertThat(true).isTrue();
}
verify(namingEnumerationMock).close();
verify(dirContextMock).close();
}
@Test
public void testGetStringAttributesExistsWithInvalidType() throws Exception {
final Attributes attrs = new BasicAttributes();
Attribute multi = new BasicAttribute("abc");
multi.add(new Object());
attrs.put(multi);
class TestableDirContextAdapter extends DirContextAdapter {
public TestableDirContextAdapter() {
super(attrs, null);
}
}
tested = new TestableDirContextAdapter();
try {
tested.getStringAttributes("abc");
fail("ClassCastException expected");
}
catch (IllegalArgumentException expected) {
assertThat(true).isTrue();
}
}
@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");
}
boolean compareToSearchResult(String name) {
boolean successful = false;
switch (status) {
case LdapClient.LDAP_COMPARE_TRUE:
status = LdapClient.LDAP_SUCCESS;
entries = new Vector<>(1,1);
Attributes attrs = new BasicAttributes(LdapClient.caseIgnore);
LdapEntry entry = new LdapEntry( name, attrs );
entries.addElement(entry);
successful = true;
break;
case LdapClient.LDAP_COMPARE_FALSE:
status = LdapClient.LDAP_SUCCESS;
entries = new Vector<>(0);
successful = true;
break;
default:
successful = false;
break;
}
return successful;
}
@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);
}
/**
* Converts an {@link Entry} to an {@link Attributes}.
*
* @param entry
* the {@link Entry} to convert
* @return
* the equivalent {@link Attributes}
*/
public static Attributes toAttributes( Entry entry )
{
if ( entry != null )
{
Attributes attributes = new BasicAttributes( true );
// Looping on attributes
for ( Iterator<Attribute> attributeIterator = entry.iterator(); attributeIterator.hasNext(); )
{
Attribute entryAttribute = attributeIterator.next();
attributes.put( toJndiAttribute( entryAttribute ) );
}
return attributes;
}
return null;
}
@Test
public void testSearch_Name_AttributesMapper_DirContextProcessor() throws Exception {
expectGetReadOnlyContext();
SearchControls controls = searchControlsOneLevel();
controls.setReturningObjFlag(false);
BasicAttributes expectedAttributes = new BasicAttributes();
SearchResult searchResult = new SearchResult("", null, expectedAttributes);
singleSearchResult(controls, searchResult);
Object expectedResult = new Object();
when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult);
List list = tested.search(nameMock, "(ou=somevalue)", controls, attributesMapperMock, dirContextProcessorMock);
verify(dirContextProcessorMock).preProcess(dirContextMock);
verify(dirContextProcessorMock).postProcess(dirContextMock);
verify(namingEnumerationMock).close();
verify(dirContextMock).close();
assertThat(list).isNotNull();
assertThat(list).hasSize(1);
assertThat(list.get(0)).isSameAs(expectedResult);
}
/**
* Create the Trigger execution subentry
*
* @param apCtx The administration point context
* @param subentryCN The CN used by the suentry
* @param subtreeSpec The subtree specification
* @param prescriptiveTriggerSpec The prescriptive trigger specification
* @throws NamingException If the operation failed
*/
public static void createTriggerExecutionSubentry(
LdapContext apCtx,
String subentryCN,
String subtreeSpec,
String prescriptiveTriggerSpec ) throws NamingException
{
Attributes subentry = new BasicAttributes( SchemaConstants.CN_AT, subentryCN, true );
Attribute objectClass = new BasicAttribute( SchemaConstants.OBJECT_CLASS_AT );
subentry.put( objectClass );
objectClass.add( SchemaConstants.TOP_OC );
objectClass.add( SchemaConstants.SUBENTRY_OC );
objectClass.add( SchemaConstants.TRIGGER_EXECUTION_SUBENTRY_OC );
subentry.put( SchemaConstants.SUBTREE_SPECIFICATION_AT, subtreeSpec );
subentry.put( SchemaConstants.PRESCRIPTIVE_TRIGGER_SPECIFICATION_AT, prescriptiveTriggerSpec );
apCtx.createSubcontext( "cn=" + subentryCN, subentry );
}
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;
}
@Override
public void add(LDAPObject ldapObject) {
// id will be assigned by the ldap server
if (ldapObject.getUuid() != null) {
throw new ModelException("Can't add object with already assigned uuid");
}
String entryDN = ldapObject.getDn().toString();
BasicAttributes ldapAttributes = extractAttributesForSaving(ldapObject, true);
this.operationManager.createSubContext(entryDN, ldapAttributes);
ldapObject.setUuid(getEntryIdentifier(ldapObject));
if (logger.isDebugEnabled()) {
logger.debugf("Type with identifier [%s] and dn [%s] successfully added to LDAP store.", ldapObject.getUuid(), entryDN);
}
}
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;
}
};
}
};
}
boolean compareToSearchResult(String name) {
boolean successful = false;
switch (status) {
case LdapClient.LDAP_COMPARE_TRUE:
status = LdapClient.LDAP_SUCCESS;
entries = new Vector<>(1,1);
Attributes attrs = new BasicAttributes(LdapClient.caseIgnore);
LdapEntry entry = new LdapEntry( name, attrs );
entries.addElement(entry);
successful = true;
break;
case LdapClient.LDAP_COMPARE_FALSE:
status = LdapClient.LDAP_SUCCESS;
entries = new Vector<>(0);
successful = true;
break;
default:
successful = false;
break;
}
return successful;
}
public static Context getURLContext(
String scheme, Hashtable<?,?> environment)
throws NamingException {
return new InitialDirContext() {
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 void insert(final Group group) {
if (!fessConfig.isLdapAdminEnabled()) {
return;
}
final Supplier<Hashtable<String, String>> adminEnv = this::createAdminEnv;
final String entryDN = fessConfig.getLdapAdminGroupSecurityPrincipal(group.getName());
search(fessConfig.getLdapAdminGroupBaseDn(), fessConfig.getLdapAdminGroupFilter(group.getName()), null, adminEnv, result -> {
if (!result.isEmpty()) {
logger.info("{} exists in LDAP server.", group.getName());
modifyGroupAttributes(group, adminEnv, entryDN, result);
} else {
final BasicAttributes entry = new BasicAttributes();
addGroupAttributes(entry, group);
final Attribute oc = fessConfig.getLdapAdminGroupObjectClassAttribute();
entry.put(oc);
insert(entryDN, entry, adminEnv);
}
});
}
@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");
}
/**
* Convenience method for creating principals.
*
* @param cn the commonName of the person
* @param principal the kerberos principal name for the person
* @param sn the surName of the person
* @param uid the unique identifier for the person
* @param userPassword the credentials of the person
* @return the attributes of the person principal
*/
protected Attributes getPrincipalAttributes(String sn, String cn, String uid,
String userPassword, String principal) {
Attributes attributes = new BasicAttributes(true);
Attribute basicAttribute = new BasicAttribute("objectClass");
basicAttribute.add("top");
basicAttribute.add("person"); // sn $ cn
basicAttribute.add("inetOrgPerson"); // uid
basicAttribute.add("krb5principal");
basicAttribute.add("krb5kdcentry");
attributes.put(basicAttribute);
attributes.put("cn", cn);
attributes.put("sn", sn);
attributes.put("uid", uid);
attributes.put(SchemaConstants.USER_PASSWORD_AT, userPassword);
attributes.put(KerberosAttribute.KRB5_PRINCIPAL_NAME_AT, principal);
attributes.put(KerberosAttribute.KRB5_KEY_VERSION_NUMBER_AT, "0");
return attributes;
}
@Test
public void testAuthenticateWithErrorInCallbackShouldFail() throws Exception {
when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock);
Object expectedObject = new DirContextAdapter(new BasicAttributes(), LdapUtils.newLdapName("cn=john doe"),
LdapUtils.newLdapName("dc=jayway, dc=se"));
SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes());
singleSearchResult(searchControlsRecursive(), searchResult);
when(contextSourceMock.getContext("cn=john doe,dc=jayway,dc=se", "password"))
.thenReturn(authenticatedContextMock);
doThrow(new UncategorizedLdapException("Authentication failed")).when(entryContextCallbackMock)
.executeWithContext(authenticatedContextMock,
new LdapEntryIdentification(
LdapUtils.newLdapName("cn=john doe,dc=jayway,dc=se"), LdapUtils.newLdapName("cn=john doe")));
boolean result = tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock);
verify(authenticatedContextMock).close();
verify(dirContextMock).close();
assertThat(result).isFalse();
}
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 testSearch_AttributesMapper() throws Exception {
expectGetReadOnlyContext();
SearchControls controls = searchControlsOneLevel();
controls.setReturningObjFlag(false);
BasicAttributes expectedAttributes = new BasicAttributes();
SearchResult searchResult = new SearchResult("", null, expectedAttributes);
singleSearchResult(controls, searchResult);
Object expectedResult = new Object();
when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult);
List list = tested.search(nameMock, "(ou=somevalue)", 1, attributesMapperMock);
verify(namingEnumerationMock).close();
verify(dirContextMock).close();
assertThat(list).isNotNull();
assertThat(list).hasSize(1);
assertThat(list.get(0)).isSameAs(expectedResult);
}
/**
* Verifies that org.jivesoftware.openfire.ldap.LdapManager#getRelativeDNFromResult(javax.naming.directory.SearchResult)
* can handle a result that contains multiple RDN values.
*/
@Test
public void testGetRelativeDNFromResultMultiValue() throws Exception
{
// Setup test fixture.
final SearchResult input = new SearchResult( "cn=bender,ou=people", null, new BasicAttributes(), true );
// Execute system under test.
final Rdn[] result = LdapManager.getRelativeDNFromResult( input );
// Verify result.
assertEquals( 2, result.length );
assertEquals( "cn", result[0].getType() );
assertEquals( "bender", result[0].getValue() );
assertEquals( "ou", result[1].getType() );
assertEquals( "people", result[1].getValue() );
}
@Test
public void testPerformOperation() {
LdapName expectedOriginalDn = LdapUtils.newLdapName(
"cn=john doe");
LdapName expectedTempDn = LdapUtils.newLdapName(
"cn=john doe_temp");
Object expectedObject = new Object();
BasicAttributes expectedAttributes = new BasicAttributes();
RebindOperationExecutor tested = new RebindOperationExecutor(
ldapOperationsMock, expectedOriginalDn, expectedTempDn,
expectedObject, expectedAttributes);
// perform test
tested.performOperation();
verify(ldapOperationsMock).rename(expectedOriginalDn, expectedTempDn);
verify(ldapOperationsMock)
.bind(expectedOriginalDn, expectedObject, expectedAttributes);
}
@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);
}