下面列出了javax.naming.directory.BasicAttributes#put ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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 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);
}
@Test
public void testAddDnAttributeNewValue() 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.addAttributeValue("uniqueMember", LdapUtils.newLdapName("cn=jane doe, ou=company"));
ModificationItem[] modificationItems = tested.getModificationItems();
assertThat(modificationItems.length).isEqualTo(1);
ModificationItem modificationItem = modificationItems[0];
assertThat(modificationItem.getModificationOp()).isEqualTo(DirContext.ADD_ATTRIBUTE);
assertThat(modificationItem.getAttribute().getID()).isEqualTo("uniqueMember");
assertThat(modificationItem.getAttribute().get()).isEqualTo("cn=jane doe, ou=company");
}
@Test
public void testSetDnAttributesValuesOneNewEntry() 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.setAttributeValues("uniqueMember", new Object[]{
LdapUtils.newLdapName("cn=john doe, ou=company"),
LdapUtils.newLdapName("cn=jane doe, ou=company")
});
ModificationItem[] modificationItems = tested.getModificationItems();
assertThat(modificationItems.length).isEqualTo(1);
ModificationItem modificationItem = modificationItems[0];
assertThat(modificationItem.getModificationOp()).isEqualTo(DirContext.ADD_ATTRIBUTE);
assertThat(modificationItem.getAttribute().getID()).isEqualTo("uniqueMember");
assertThat(modificationItem.getAttribute().get()).isEqualTo("cn=jane doe, ou=company");
}
@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");
}
/**
* Returns a BasicAttributes object with basic required attributes
*
* @param userName
* @return
*/
protected BasicAttributes getAddUserBasicAttributes(String userName) {
BasicAttributes basicAttributes = new BasicAttributes(true);
String userEntryObjectClassProperty = realmConfig
.getUserStoreProperty(LDAPConstants.USER_ENTRY_OBJECT_CLASS);
BasicAttribute objectClass = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
String[] objectClassHierarchy = userEntryObjectClassProperty.split("/");
for (String userObjectClass : objectClassHierarchy) {
if (userObjectClass != null && !userObjectClass.trim().equals("")) {
objectClass.add(userObjectClass.trim());
}
}
// If KDC is enabled we have to set KDC specific object classes also
if (kdcEnabled) {
// Add Kerberos specific object classes
objectClass.add("krb5principal");
objectClass.add("krb5kdcentry");
objectClass.add("subschema");
}
basicAttributes.put(objectClass);
BasicAttribute userNameAttribute = new BasicAttribute(
realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE));
userNameAttribute.add(userName);
basicAttributes.put(userNameAttribute);
if (kdcEnabled) {
userName = userName + UserCoreConstants.PRINCIPAL_USERNAME_SEPARATOR + Constants.SUPER_TENANT_DOMAIN_NAME;
String principal = userName + "@" + this.getRealmName();
BasicAttribute principalAttribute = new BasicAttribute(KRB5_PRINCIPAL_NAME_ATTRIBUTE);
principalAttribute.add(principal);
basicAttributes.put(principalAttribute);
BasicAttribute versionNumberAttribute = new BasicAttribute(
KRB5_KEY_VERSION_NUMBER_ATTRIBUTE);
versionNumberAttribute.add("0");
basicAttributes.put(versionNumberAttribute);
}
return basicAttributes;
}
@Test
public void byteArrayValueIsCheckedAsString() throws Exception {
BasicAttributes entity = new BasicAttributes(true);
entity.put("userPassword", new byte[]{50, 82, 115, 48, 67, 99, 54, 74});
Whitebox.setInternalState(entityFacade, "entity", entity);
entityFacade.entityHasAttributeWithValue("userpassword", "2Rs0Cc6J");
}
@Test
public void charArrayValueIsCheckedAsString() throws Exception {
BasicAttributes entity = new BasicAttributes(true);
entity.put("userPassword", new char[]{'h', 'e', 'l', 'l', 'o'});
Whitebox.setInternalState(entityFacade, "entity", entity);
entityFacade.entityHasAttributeWithValue("userpassword", "hello");
}
@Test
public void stringValueIsCheckedAsString() throws Exception {
BasicAttributes entity = new BasicAttributes(true);
entity.put("userPassword", "hello");
Whitebox.setInternalState(entityFacade, "entity", entity);
entityFacade.entityHasAttributeWithValue("userpassword", "hello");
}
@Test
public void intArrayValueIsCheckedAsString() throws Exception {
BasicAttributes entity = new BasicAttributes(true);
entity.put("userPassword", new int[]{1, 2, 3});
Whitebox.setInternalState(entityFacade, "entity", entity);
entityFacade.entityHasAttributeWithValue("userpassword", "{1,2,3}");
}
@Test
public void testSetDnAttributeValueIdentical() {
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.setAttributeValue("uniqueMember", LdapUtils.newLdapName("cn=john doe, ou=company"));
ModificationItem[] modificationItems = tested.getModificationItems();
assertThat(modificationItems.length).isEqualTo(0);
}
@Test
public void testAddDnAttributeValueIdentical() {
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.addAttributeValue("uniqueMember", LdapUtils.newLdapName("cn=john doe, ou=company"));
ModificationItem[] modificationItems = tested.getModificationItems();
assertThat(modificationItems.length).isEqualTo(0);
}
private void constructBasicAttributes(BasicAttributes basicAttributes, String id, String principleName,
Object credential, String commonName, String surName)
throws DirectoryServerManagerException {
// set the objectClass type for schema
BasicAttribute objectClass = new BasicAttribute(LDAPServerManagerConstants.LDAP_OBJECT_CLASS);
objectClass.add(LDAPServerManagerConstants.LDAP_INTET_ORG_PERSON);
objectClass.add(LDAPServerManagerConstants.LDAP_ORG_PERSON);
objectClass.add(LDAPServerManagerConstants.LDAP_PERSON);
objectClass.add(LDAPServerManagerConstants.LDAP_TOP);
// Add Kerberos specific object classes
objectClass.add(LDAPServerManagerConstants.LDAP_KRB5_PRINCIPLE);
objectClass.add(LDAPServerManagerConstants.LDAP_KRB5_KDC);
objectClass.add(LDAPServerManagerConstants.LDAP_SUB_SCHEMA);
basicAttributes.put(objectClass);
BasicAttribute uid = new BasicAttribute(LDAPServerManagerConstants.LDAP_UID);
uid.add(id);
basicAttributes.put(uid);
String principal = getFullyQualifiedPrincipalName(principleName);
BasicAttribute principalAttribute = new BasicAttribute
(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE);
principalAttribute.add(principal);
basicAttributes.put(principalAttribute);
BasicAttribute versionNumberAttribute = new BasicAttribute
(LDAPServerManagerConstants.KRB5_KEY_VERSION_NUMBER_ATTRIBUTE);
versionNumberAttribute.add("0");
basicAttributes.put(versionNumberAttribute);
BasicAttribute userPassword = new BasicAttribute(LDAPServerManagerConstants.LDAP_PASSWORD);
//Since we are using the KDC, we will always use plain text password.
//KDC does not support other types of passwords
String password = getPasswordToStore((String) credential,
LDAPServerManagerConstants.PASSWORD_HASH_METHOD_PLAIN_TEXT);
userPassword.add(password.getBytes());
basicAttributes.put(userPassword);
if (commonName == null || commonName.isEmpty()) {
commonName = principleName + " Service";
}
BasicAttribute cn = new BasicAttribute(LDAPServerManagerConstants.LDAP_COMMON_NAME);
cn.add(commonName);
basicAttributes.put(cn);
BasicAttribute sn = new BasicAttribute(LDAPServerManagerConstants.SERVER_PRINCIPAL_ATTRIBUTE_NAME);
sn.add(surName);
basicAttributes.put(sn);
}
/**
* Executes {@link org.springframework.ldap.core.LdapTemplate#search(org.springframework.ldap.query.LdapQuery,
* org.springframework.ldap.core.AttributesMapper)}.
*
* @param ldapTemplate the LDAP template to use
* @param query the LDAP query specification
* @param mapper the <code>Attributes</code> to supply all found Attributes to
*
* @return the predefined LDAP search results constructed by the given {@link org.springframework.ldap.core.AttributesMapper}
*/
@Override
public <T> List<T> search(LdapTemplate ldapTemplate, LdapQuery query, AttributesMapper<T> mapper)
{
// Create an empty results list.
List<T> results = new ArrayList<>();
// Get the query filter as a string.
String filter = query.filter().toString();
// Check if we need to respond with the predefined result.
if (!filter.contains(MOCK_USER_ID_USER_NO_EXISTS))
{
// 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(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_FULL_NAME), AbstractDaoTest.USER_FULL_NAME));
attributes
.put(new BasicAttribute(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_JOB_TITLE), AbstractDaoTest.USER_JOB_TITLE));
attributes.put(
new BasicAttribute(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_EMAIL_ADDRESS), AbstractDaoTest.USER_EMAIL_ADDRESS));
// Check if it is OK to add the user phone number attribute.
if (!filter.contains(MOCK_USER_ID_ATTRIBUTE_USER_TELEPHONE_NUMBER_NO_EXISTS))
{
attributes.put(new BasicAttribute(configurationHelper.getProperty(ConfigurationValue.LDAP_ATTRIBUTE_USER_TELEPHONE_NUMBER),
AbstractDaoTest.USER_TELEPHONE_NUMBER));
}
// Map the results.
try
{
results.add(mapper.mapFromAttributes(attributes));
}
catch (NamingException e)
{
// Do nothing.
}
}
// Return the results.
return results;
}
@Test
public void testRolesFor() throws NamingException {
LdapRealm realm = new LdapRealm();
realm.setGroupSearchBase("cn=groups,dc=apache");
realm.setGroupObjectClass("posixGroup");
realm.setMemberAttributeValueTemplate("cn={0},ou=people,dc=apache");
HashMap<String, String> rolesByGroups = new HashMap<>();
rolesByGroups.put("group-three", "zeppelin-role");
realm.setRolesByGroup(rolesByGroups);
LdapContextFactory ldapContextFactory = mock(LdapContextFactory.class);
LdapContext ldapCtx = mock(LdapContext.class);
Session session = mock(Session.class);
// expected search results
BasicAttributes group1 = new BasicAttributes();
group1.put(realm.getGroupIdAttribute(), "group-one");
group1.put(realm.getMemberAttribute(), "principal");
// user doesn't belong to this group
BasicAttributes group2 = new BasicAttributes();
group2.put(realm.getGroupIdAttribute(), "group-two");
group2.put(realm.getMemberAttribute(), "someoneelse");
// mapped to a different Zeppelin role
BasicAttributes group3 = new BasicAttributes();
group3.put(realm.getGroupIdAttribute(), "group-three");
group3.put(realm.getMemberAttribute(), "principal");
NamingEnumeration<SearchResult> results = enumerationOf(group1, group2, group3);
when(ldapCtx.search(any(String.class), any(String.class), any(SearchControls.class)))
.thenReturn(results);
Set<String> roles = realm.rolesFor(
new SimplePrincipalCollection("principal", "ldapRealm"),
"principal", ldapCtx, ldapContextFactory, session);
verify(ldapCtx).search("cn=groups,dc=apache", "(objectclass=posixGroup)",
realm.getGroupSearchControls());
assertEquals(new HashSet(Arrays.asList("group-one", "zeppelin-role")), roles);
}
@Test
public void testLookup_ReturnAttributes_AttributesMapper() throws Exception {
expectGetReadOnlyContext();
String[] attributeNames = new String[] { "cn" };
BasicAttributes expectedAttributes = new BasicAttributes();
expectedAttributes.put("cn", "Some Name");
when(dirContextMock.getAttributes(nameMock, attributeNames)).thenReturn(expectedAttributes);
Object expected = new Object();
when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected);
Object actual = tested.lookup(nameMock, attributeNames,
attributesMapperMock);
verify(dirContextMock).close();
assertThat(actual).isSameAs(expected);
}
private void constructBasicAttributes(BasicAttributes basicAttributes, String id, String principleName,
Object credential, String commonName, String surName)
throws DirectoryServerManagerException {
// set the objectClass type for schema
BasicAttribute objectClass = new BasicAttribute(LDAPServerManagerConstants.LDAP_OBJECT_CLASS);
objectClass.add(LDAPServerManagerConstants.LDAP_INTET_ORG_PERSON);
objectClass.add(LDAPServerManagerConstants.LDAP_ORG_PERSON);
objectClass.add(LDAPServerManagerConstants.LDAP_PERSON);
objectClass.add(LDAPServerManagerConstants.LDAP_TOP);
// Add Kerberos specific object classes
objectClass.add(LDAPServerManagerConstants.LDAP_KRB5_PRINCIPLE);
objectClass.add(LDAPServerManagerConstants.LDAP_KRB5_KDC);
objectClass.add(LDAPServerManagerConstants.LDAP_SUB_SCHEMA);
basicAttributes.put(objectClass);
BasicAttribute uid = new BasicAttribute(LDAPServerManagerConstants.LDAP_UID);
uid.add(id);
basicAttributes.put(uid);
String principal = getFullyQualifiedPrincipalName(principleName);
BasicAttribute principalAttribute = new BasicAttribute
(LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE);
principalAttribute.add(principal);
basicAttributes.put(principalAttribute);
BasicAttribute versionNumberAttribute = new BasicAttribute
(LDAPServerManagerConstants.KRB5_KEY_VERSION_NUMBER_ATTRIBUTE);
versionNumberAttribute.add("0");
basicAttributes.put(versionNumberAttribute);
BasicAttribute userPassword = new BasicAttribute(LDAPServerManagerConstants.LDAP_PASSWORD);
//Since we are using the KDC, we will always use plain text password.
//KDC does not support other types of passwords
String password = getPasswordToStore((String) credential,
LDAPServerManagerConstants.PASSWORD_HASH_METHOD_PLAIN_TEXT);
userPassword.add(password.getBytes());
basicAttributes.put(userPassword);
if (commonName == null || commonName.isEmpty()) {
commonName = principleName + " Service";
}
BasicAttribute cn = new BasicAttribute(LDAPServerManagerConstants.LDAP_COMMON_NAME);
cn.add(commonName);
basicAttributes.put(cn);
BasicAttribute sn = new BasicAttribute(LDAPServerManagerConstants.SERVER_PRINCIPAL_ATTRIBUTE_NAME);
sn.add(surName);
basicAttributes.put(sn);
}
public void testExecute() {
QueryCallback qc = new QueryCallback() {
public void processRow(final ParametersCallback parameters) {
assertEquals("uid"+rows, parameters.getParameter("uid"));
assertEquals("search"+rows, parameters.getParameter("cn"));
assertEquals("cn=search"+rows+", ou=ldap, dc=scriptella", parameters.getParameter("dn"));
rows++;
}
};
SearchFilterQuery q = new SearchFilterQuery(null, MockParametersCallbacks.UNSUPPORTED, qc) {
protected NamingEnumeration<SearchResult> query(final LdapConnection connection, final String filter) {
List<SearchResult> res = new ArrayList<SearchResult>();
for (int i=0;i<2;i++) {
BasicAttributes a = new BasicAttributes("uid","uid"+i);
a.put("cn", "search"+i);
SearchResult sr = new SearchResult("cn=search"+i+", ou=ldap, dc=scriptella", null, a);
sr.setNameInNamespace(sr.getName());
res.add(sr);
}
final Iterator<SearchResult> it = res.iterator();
return new NamingEnumeration<SearchResult>() {
public SearchResult next() {
return it.next();
}
public boolean hasMore() {
return it.hasNext();
}
public void close() {
closed=true;
}
public boolean hasMoreElements() {
return hasMore();
}
public SearchResult nextElement() {
return next();
}
};
}
};
q.execute("filter");//in this test case filter doesn't matter
assertTrue("Naming enumeration must be closed after iteration", closed);
assertEquals(2, rows);
}
@Test
public void testLookup_ReturnAttributes_ContextMapper() throws Exception {
expectGetReadOnlyContext();
String[] attributeNames = new String[] { "cn" };
BasicAttributes expectedAttributes = new BasicAttributes();
expectedAttributes.put("cn", "Some Name");
LdapName name = LdapUtils.newLdapName(DEFAULT_BASE_STRING);
DirContextAdapter adapter = new DirContextAdapter(expectedAttributes,
name);
when(dirContextMock.getAttributes(name,attributeNames)).thenReturn(expectedAttributes);
Object transformed = new Object();
when(contextMapperMock.mapFromContext(adapter)).thenReturn(transformed);
Object actual = tested.lookup(name, attributeNames, contextMapperMock);
verify(dirContextMock).close();
assertThat(actual).isSameAs(transformed);
}
@Test
public void testLookup_String_ReturnAttributes_AttributesMapper()
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);
Object expected = new Object();
when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected);
Object actual = tested.lookup(DEFAULT_BASE_STRING, attributeNames,
attributesMapperMock);
verify(dirContextMock).close();
assertThat(actual).isSameAs(expected);
}