應用程式 4. 搜尋儲存的資料
先從 ApacheDS 上的一個簡單搜尋開始。假設在 ApacheDS 中有許多使用者。而您想要找到使用者 Alice 的所有詳細資料。下面列出了關於 Alice 的所有已知事項:
Alice 是一名使用者,所以在使用者的資料群組織單元中應當可以尋找她的資料條目。(在第 1 部分已經介 紹了組織單元或 “ou” 的概念。)
Alice 的使用者名稱是 “alice”(不區分大小寫)。
Alice 是一個人,所以她的資料條目使用的對象類必須直接或間接地擴充 person 對象類。
現在請參見清單 6,它顯示了名為 SearchForAlice 的應用程式。SearchForAlice 示範了一個非常簡 單的搜尋情境;後面我將擴充這個應用程式,使其適合更進階的搜尋情境。
清單 6. SearchForAlice
public class SearchForAlice {
public SearchForAlice() {
try
{
//------------------------------------------
//Step1: Setting up JNDI properties for ApacheDS
//------------------------------------------
InputStream inputStream = new FileInputStream ( "ApacheDS.properties");
Properties properties = new Properties();
properties.load(inputStream);
properties.setProperty("java.naming.security.credentials", "secret");
//------------------------------------------
// Step2: Fetching a DirContext object
//------------------------------------------
DirContext ctx = new InitialDirContext(properties);
//---------------------------------------------
//Step3: Setting search context
//---------------------------------------------
String searchContext = "ou=users";
//--------------------------------------------
//Step4: Creating search attributes for Alice
//--------------------------------------------
Attribute uid = new BasicAttribute("uid");
Attribute objclass = new BasicAttribute("objectClass");
//adding attribute values
uid.add("Alice");
objclass.add("person");
//Instantiate Attributes object and put search attributes in it.
Attributes attrs = new BasicAttributes(true);
attrs.put(uid);
attrs.put(objclass);
//------------------------------------------
//Step5: Executing search
//------------------------------------------
NamingEnumeration ne = ctx.search(searchContext, attrs);
if (ne != null)
{
//Step 6: Iterating through SearchResults
while (ne.hasMore()) {
//Step 7: Getting individual SearchResult object
SearchResult sr = (SearchResult) ne.next();
//Step 8:
String entryRDN = sr.getName();
System.out.println("RDN of the Searched entry: "+entryRDN);
//Step 9:
Attributes srAttrs = sr.getAttributes();
if (srAttrs != null) {
//Step 10:
for (Enumeration e = attrs.getAll() ; e.hasMoreElements() ;)
{
Attribute attr = (Attribute) e.nextElement();
//Step 11:
String attrID = attr.getID();
System.out.println("Attribute Name: "+attrID);
System.out.println("Attribute Value(s):");
NamingEnumeration e1 = attr.getAll();
while (e1.hasMore())
System.out.println("\t\t"+e1.nextElement());
}//for()
}//if (srAttrs)
}
}//if (ne != null)
} catch (Exception e) {
System.out.println("Operation failed: " + e);
}
}
public static void main(String[] args) {
SearchForAlice searchAlice = new SearchForAlice();
}
}