下面列出了怎么用javax.naming.directory.Attributes的API类实例代码及写法,或者点击链接到github查看源代码。
private static Object createObjectFromFactories(Object obj, Name name,
Context nameCtx, Hashtable<?,?> environment, Attributes attrs)
throws Exception {
FactoryEnumeration factories = ResourceManager.getFactories(
Context.OBJECT_FACTORIES, environment, nameCtx);
if (factories == null)
return null;
ObjectFactory factory;
Object answer = null;
// Try each factory until one succeeds
while (answer == null && factories.hasMore()) {
factory = (ObjectFactory)factories.next();
if (factory instanceof DirObjectFactory) {
answer = ((DirObjectFactory)factory).
getObjectInstance(obj, name, nameCtx, environment, attrs);
} else {
answer =
factory.getObjectInstance(obj, name, nameCtx, environment);
}
}
return answer;
}
@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");
}
/**
* Checks if Collection of naming Attributes contain defined required properties for OLAT * Configuration: LDAP Required Map = olatextconfig.xml (property=reqAttrs)
*
* @param attributes
* Collection of LDAP Naming Attribute
* @return null If all required Attributes are found, otherwise String[] of missing Attributes
*/
public static String[] checkReqAttr(final Attributes attrs) {
final Map<String, String> reqAttrMap = getReqAttrs();
final String[] missingAttr = new String[reqAttrMap.size()];
int y = 0;
for (String attKey : reqAttrMap.keySet()) {
attKey = attKey.trim();
if (attrs.get(attKey) == null) {
missingAttr[y++] = attKey;
}
}
if (y == 0) {
return null;
} else {
return missingAttr;
}
}
public LdapUser findByUsername(final Object username, final String... organizationalUnits)
{
return (LdapUser) new LdapTemplate(ldapConnector) {
@Override
protected Object call() throws NameNotFoundException, Exception
{
NamingEnumeration< ? > results = null;
final SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
final String searchBase = getSearchBase(organizationalUnits);
results = ctx.search(searchBase, "(&(objectClass=" + getObjectClass() + ")(uid=" + username + "))", controls);
if (results.hasMore() == false) {
return null;
}
final SearchResult searchResult = (SearchResult) results.next();
final String dn = searchResult.getName();
final Attributes attributes = searchResult.getAttributes();
if (results.hasMore() == true) {
log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + username);
}
return mapToObject(dn, searchBase, attributes);
}
}.excecute();
}
protected List<Object> getAttributeValueList(final List<SearchResult> result, final String name) {
try {
for (final SearchResult srcrslt : result) {
final Attributes attrs = srcrslt.getAttributes();
final Attribute attr = attrs.get(name);
if (attr == null) {
continue;
}
final List<Object> attrList = new ArrayList<>();
for (int i = 0; i < attr.size(); i++) {
final Object attrValue = attr.get(i);
if (attrValue != null) {
attrList.add(attrValue);
}
}
return attrList;
}
return Collections.emptyList();
} catch (final NamingException e) {
throw new LdapOperationException("Failed to parse attribute values for " + name, e);
}
}
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 testModifyAttributes() {
String dn = "cn=Some Person,ou=company1,ou=Sweden";
// Perform test
dummyDao.modifyAttributes(dn, "Updated lastname", "Updated description");
// Verify result - check that the operation was not rolled back
Object result = ldapTemplate.lookup(dn, new AttributesMapper() {
public Object mapFromAttributes(Attributes attributes) throws NamingException {
assertThat(attributes.get("sn").get()).isEqualTo("Updated lastname");
assertThat(attributes.get("description").get()).isEqualTo("Updated description");
return new Object();
}
});
assertThat(result).isNotNull();
}
@Test
public void testUnbindWithException() {
String dn = "cn=Some Person,ou=company1,ou=Sweden";
try {
// Perform test
dummyDao.unbindWithException(dn, "Some Person");
fail("DummyException expected");
}
catch (DummyException expected) {
assertThat(true).isTrue();
}
// Verify result - check that the operation was properly rolled back
Object ldapResult = ldapTemplate.lookup(dn, new AttributesMapper() {
public Object mapFromAttributes(Attributes attributes) throws NamingException {
// Just verify that the entry still exists.
return new Object();
}
});
assertThat(ldapResult).isNotNull();
}
@Override
public Object mapFromAttributes(Attributes attrs) throws NamingException
{
UserGroup group = new UserGroup();
String id = getAttribute(attrs, "id");
if(StringUtils.isBlank(id)) {
LOGGER.warn("Empty id for UserGroup");
if(LOGGER.isDebugEnabled()) {
for(Object oa: Collections.list(attrs.getAll())) {
Attribute a = (Attribute)oa;
LOGGER.debug("---> " + a);
}
}
}
group.setExtId(id);
group.setName(getAttribute(attrs, "groupname"));
group.setEnabled(true);
return group;
}
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 static Set<String> collectRecords(String dns) {
if (ConfigUtil.getDebugOrFalse()) {
logger.info("Collecting A records for " + dns);
}
Set<String> retVal = new HashSet<>();
try {
InitialDirContext context = new InitialDirContext();
Attributes attributes = context.getAttributes("dns:/" + dns, new String[] { "A" });
NamingEnumeration<?> attributeEnum = attributes.get("A").getAll();
while (attributeEnum.hasMore()) {
retVal.add(attributeEnum.next().toString());
}
} catch (NamingException ex) {
logger.error(ex.getMessage(), ex);
}
if (ConfigUtil.getDebugOrFalse()) {
logger.info("Got " + retVal.size() + " record(s) for " + dns);
}
return retVal;
}
@Test
public void testUpdate() {
String dn = "cn=Some Person,ou=company1,ou=Sweden";
OrgPerson person = (OrgPerson) this.hibernateTemplate.load(OrgPerson.class, new Integer(1));
person.setLastname("Updated Person");
person.setDescription("Updated description");
dummyDao.update(person);
log.debug("Verifying result");
Object ldapResult = ldapTemplate.lookup(dn, new AttributesMapper() {
public Object mapFromAttributes(Attributes attributes) throws NamingException {
assertThat(attributes.get("sn").get()).isEqualTo("Updated Person");
assertThat(attributes.get("description").get()).isEqualTo("Updated description");
return new Object();
}
});
OrgPerson updatedPerson = (OrgPerson) this.hibernateTemplate.load(OrgPerson.class, new Integer(1));
assertThat(updatedPerson.getLastname()).isEqualTo("Updated Person");
assertThat(updatedPerson.getDescription()).isEqualTo("Updated description");
assertThat(ldapResult).isNotNull();
}
@Test
public void testChangeMultiAttribute_RemoveValue() 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" });
ModificationItem[] modificationItems = tested.getModificationItems();
assertThat(modificationItems.length).isEqualTo(1);
assertThat(modificationItems[0].getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE);
assertThat(modificationItems[0].getAttribute().get()).isEqualTo("qwe");
}
private static Set<String> collectRecords(String dns) {
if (ConfigUtil.getDebugOrFalse()) {
logger.info("Collecting A records for " + dns);
}
Set<String> retVal = new HashSet<>();
try {
InitialDirContext context = new InitialDirContext();
Attributes attributes = context.getAttributes("dns:/" + dns, new String[] { "A" });
NamingEnumeration<?> attributeEnum = attributes.get("A").getAll();
while (attributeEnum.hasMore()) {
retVal.add(attributeEnum.next().toString());
}
} catch (NamingException ex) {
logger.error(ex.getMessage(), ex);
}
if (ConfigUtil.getDebugOrFalse()) {
logger.info("Got " + retVal.size() + " record(s) for " + dns);
}
return retVal;
}
@Override
public void updateLDAPUser(User user, Attributes attrs) {
HashMap<String, String> map = getLDAPUserAttributes(attrs);
user.setLogin(map.get("login"));
user.setFirstName(map.get("fname"));
user.setLastName(map.get("lname"));
user.setEmail(map.get("email"));
user.setAddressLine1(map.get("address1"));
user.setAddressLine2(map.get("address2"));
user.setAddressLine3(map.get("address3"));
user.setCity(map.get("city"));
user.setState(map.get("state"));
user.setPostcode(map.get("postcode"));
user.setCountry(map.get("country"));
user.setDayPhone(map.get("dayphone"));
user.setEveningPhone(map.get("eveningphone"));
user.setFax(map.get("fax"));
user.setMobilePhone(map.get("mobile"));
user.setLocale(getLocale(map.get("locale")));
user.setDisabledFlag(getDisabledBoolean(attrs));
service.saveUser(user);
}
protected List<X509CRL> getCRLsFromLdap(String tmpRootDN, String tmpFilter, String tmpAttrName) {
try {
List<X509CRL> crls = new ArrayList<>();
NamingEnumeration<SearchResult> answer = ldapSearch.searchSubTree(tmpRootDN, tmpFilter);
while (answer.hasMore()) {
SearchResult sr = answer.next();
Attributes attrs = sr.getAttributes();
Attribute attribute = attrs.get(tmpAttrName);
if (attribute != null) {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509CRL crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(
(byte[]) attribute.get()));
crls.add(crl);
}
}
return crls;
} catch (CertificateException | NamingException | CRLException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public boolean validateDnExist(LdapTemplateContextSource ldapTemplateContextSource, String fullDn){
try {
String dn = fullDn.replace("," + ldapTemplateContextSource.getLdapContextSource().getBaseLdapPathAsString(), "");
Object result = ldapTemplateContextSource.getLdapTemplate().lookup(dn, new AbstractContextMapper<Object>() {
@Override
protected Object doMapFromContext(DirContextOperations ctx) {
Attributes group = ctx.getAttributes();
return group;
}
});
return result != null;
}catch (Exception e){
logger.warn(String.format("validateDnExist[%s] fail", fullDn), e);
return false;
}
}
private static Object createObjectFromFactories(Object obj, Name name,
Context nameCtx, Hashtable<?,?> environment, Attributes attrs)
throws Exception {
FactoryEnumeration factories = ResourceManager.getFactories(
Context.OBJECT_FACTORIES, environment, nameCtx);
if (factories == null)
return null;
ObjectFactory factory;
Object answer = null;
// Try each factory until one succeeds
while (answer == null && factories.hasMore()) {
factory = (ObjectFactory)factories.next();
if (factory instanceof DirObjectFactory) {
answer = ((DirObjectFactory)factory).
getObjectInstance(obj, name, nameCtx, environment, attrs);
} else {
answer =
factory.getObjectInstance(obj, name, nameCtx, environment);
}
}
return answer;
}
public NamingEnumeration<SearchResult> search(String name,
Attributes matchingAttributes)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
return res.getDirContext().search(res.getString(),
matchingAttributes);
}
public NamingEnumeration<SearchResult> search(Name name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().search(res.getName(), matchingAttributes,
attributesToReturn);
}
@Test
public void testAddAttributeValueInUpdateMode() throws NamingException {
tested.setUpdateMode(true);
tested.addAttributeValue("abc", "123");
// Perform test
Attributes attrs = tested.getAttributes();
assertThat(attrs.get("abc")).isNull();
ModificationItem[] modificationItems = tested.getModificationItems();
assertThat(modificationItems.length).isEqualTo(1);
Attribute attribute = modificationItems[0].getAttribute();
assertThat(attribute.getID()).isEqualTo("abc");
assertThat(attribute.get()).isEqualTo("123");
}
public NamingEnumeration<SearchResult> search(String name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
return res.getDirContext().search(res.getString(),
matchingAttributes,
attributesToReturn);
}
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 String getValueFromAttribute(Attributes attrs, String attrName){
javax.naming.directory.Attribute attr = attrs.get(attrName);
if( attr == null ) {
return null;
}
String attrString = attr.toString();
return attrString.substring(attrString.indexOf(":") + 1);
}
public NamingEnumeration<SearchResult> search(String name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
return res.getDirContext().search(res.getString(),
matchingAttributes,
attributesToReturn);
}
public NamingEnumeration<SearchResult> search(String name,
Attributes matchingAttributes)
throws NamingException {
DirContextStringPair res = getTargetContext(name);
return res.getDirContext().search(res.getString(),
matchingAttributes);
}
public NamingEnumeration<SearchResult> search(Name name,
Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException {
DirContextNamePair res = getTargetContext(name);
return res.getDirContext().search(res.getName(), matchingAttributes,
attributesToReturn);
}
protected void insert(final String entryDN, final Attributes entry, final Supplier<Hashtable<String, String>> envSupplier) {
try (DirContextHolder holder = getDirContext(envSupplier)) {
logger.debug("Inserting {}", entryDN);
holder.get().createSubcontext(entryDN, entry);
} catch (final NamingException e) {
throw new LdapOperationException("Failed to add " + entryDN, e);
}
}
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException {
try {
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
out.println("*** ApacheDS RootDSE ***\n");
DirContext ctx = new InitialDirContext(this.createEnv());
SearchControls ctls = new SearchControls();
ctls.setReturningAttributes(new String[] { "*", "+" });
ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
NamingEnumeration<SearchResult> result = ctx.search("", "(objectClass=*)", ctls);
if (result.hasMore()) {
SearchResult entry = result.next();
Attributes as = entry.getAttributes();
NamingEnumeration<String> ids = as.getIDs();
while (ids.hasMore()) {
String id = ids.next();
Attribute attr = as.get(id);
for (int i = 0; i < attr.size(); ++i) {
out.println(id + ": " + attr.get(i));
}
}
}
ctx.close();
out.flush();
} catch (Exception e) {
throw new ServletException(e);
}
}
public static Object getAttributeValue(final Attributes attributes, final String attrId) throws NamingException
{
final Attribute attr = attributes.get(attrId);
if (attr == null) {
return null;
}
return attr.get();
}