public static void modifyAttributes(DirContext context, String cn, Map attMap)
throws NamingException, BaseException {
validateParams(context, cn, attMap);
if (attMap.isEmpty()) return;
Attributes attrs = new BasicAttributes();
for (Map.Entry e : attMap.entrySet()) {
Attribute att;
Object v = e.getValue();
if (v instanceof List) {
att = new BasicAttribute(e.getKey());
for (Object o : (List>) v) att.add(o);
} else {
att = new BasicAttribute(e.getKey(), v);
}
attrs.put(att);
}
context.modifyAttributes(cn, DirContext.REPLACE_ATTRIBUTE, attrs);
}
差異於 ADD_ATTRIBUTE(不存在則新增、存在則報錯)與 REMOVE_ATTRIBUTE,REPLACE_ATTRIBUTE 語意為「整體覆蓋」,不存在則建立,存在則完全取代,適合「設定最終狀態」場景。
public static Map getAttributes(DirContext context, String cn, List attNameList)
throws NamingException {
Map attsMap = new HashMap<>();
if (attNameList == null || attNameList.isEmpty()) {
// 未指定屬性名單:取回所有屬性(慎用,效能差)
Attributes results = context.getAttributes(cn);
// 迭代處理...
} else {
// 高效能:單次 RPC 取回指定屬性
String[] attArray = attNameList.toArray(new String[0]);
Attributes results = context.getAttributes(cn, attArray);
for (String name : attNameList) {
Attribute attr = results.get(name);
if (attr == null || attr.size() == 0) continue;
NamingEnumeration> vals = attr.getAll();
if (vals == null) continue;
Object first = vals.nextElement();
if (first == null) continue;
List
public static List
public static String getRoleAttributeValues(DirContext context, String cn, String attName)
throws NamingException {
List list = getAttributeValues(context, cn, attName);
return list.isEmpty() ? "" : list.get(0);
}
public static List
public static List
private static List
OBJECT_SCOPE、分頁、排序等需求只需修改內部方法。returnedAtts 版本。下一篇將示範完整整合測試:建立 Active Directory 使用者、設定密碼與帳號啟用屬性。