📄 testldap.java
字号:
/* @copyright module */
/* */
/* DISCLAIMER OF WARRANTIES: */
/* ------------------------- */
/* The following [enclosed] code is sample code created by IBM Corporation. */
/* This sample code is provided to you solely for the purpose of assisting */
/* you in the development of your applications. */
/* The code is provided "AS IS", without warranty of any kind. IBM shall */
/* not be liable for any damages arising out of your use of the sample code, */
/* even if they have been advised of the possibility of such damages. */
package com.ibm.introtoldap;
import java.io.IOException;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import com.ibm.util.GeneralDefs;
import com.ibm.util.MiscFuncs;
public class TestLDAP implements GeneralDefs {
// -------------------------------------------------
// LDAP URL.
// change this to the URL for your LDAP server.
// 389 is the standard non-secure LDAP port
// -------------------------------------------------
public static String LDAP_URL = "ldap://szsite2.achievo.com:389"; // "ldap://tirane:389";
private static String ERROR_LDAP = ">>> ERROR - ";
private static String SUCCESS_LDAP = ">>> SUCCESS - ";
public static void main(String args[]) throws NamingException, IOException {
TestLDAP ldapRunner = new TestLDAP();
// ------------------------------------------------------
// change the mobile phone number for Barbara Jensen (c0001) +1 999 333
// 2232
// ------------------------------------------------------
String filter = "CN=joyce wang";
String attrName;
String attrVal;
boolean result = ldapRunner.searchWithFilter(filter);
if (!result) {
System.out.println(ERROR_LDAP
+ "record not found for (CN=joyce wang) Joyce Wang "
+ filter);
}
//did find bab's record
else {
System.out.println(SUCCESS_LDAP
+ "record found for (CN=joyce wang) Barbara Jensen " + filter);
// ------------------------------------------------------
// change the mobile phone number for Babs +1 999 333 2232
// ------------------------------------------------------
attrName = "mobile";
attrVal = "+1 999 333 2232";
result = ldapRunner.updateAttribute(filter, attrName, attrVal,
false);
if (!result) {
System.out
.println(ERROR_LDAP
+ "Did not update (uid=c0001) Barbara Jensen's mobile number : "
+ attrVal);
} else {
System.out
.println(SUCCESS_LDAP
+ "Updated (uid=c0001) Barbara Jensen's mobile number : "
+ attrVal);
}
// ------------------------------------------------------
// add an office address.
// ------------------------------------------------------
// attrName = "physicalDeliveryOfficeName";
// attrVal = "P.O. Box 343A Anywhere, IL 24252";
// result = ldapRunner.updateAttribute(filter, attrName, attrVal,
// false);
// if (!result) {
// System.out
// .println(ERROR_LDAP
// + "Did not add (uid=c0001) Barbara Jensen's delivery office address : "
// + attrVal);
// } else {
// System.out
// .println(SUCCESS_LDAP
// + "Added (uid=c0001) Barbara Jensen's delivery office address : "
// + attrVal);
// }
}
// ------------------------------------------------------
// search for Susan Baker. (uid=c0007)
//------------------------------------------------------
filter = "s=Huang";
}
/**
* Any modifications to the LDAP tree require a secureConnection
*
* @param secureConnection
* @return
* @throws NamingException
*/
private DirContext connectLDAP(boolean secureConnection)
throws NamingException {
DirContext ctx = null;
// -----------------------------------------------
// Set up the environment for creating the initial
// context.
// -----------------------------------------------
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY, LDAP_PROVIDER);
props.setProperty(Context.PROVIDER_URL, LDAP_URL);
props.setProperty(Context.URL_PKG_PREFIXES, URL_CONTEXT_PREFIX);
props.setProperty(Context.REFERRAL, REFERRALS_IGNORE);
if (secureConnection) {
props.setProperty(Context.SECURITY_AUTHENTICATION,
UPDATE_SECURITY_LEVEL);
// --------------------------------------------------
//specify the root username
// --------------------------------------------------
props.setProperty(Context.SECURITY_PRINCIPAL, ROOT_USER);
//--------------------------------------------------
//specify the root password
// --------------------------------------------------
props.setProperty(Context.SECURITY_CREDENTIALS, ROOT_PASSWORD);
//--------------------------------------------------
}
// search does not need root user id and password.
else {
props.setProperty(Context.SECURITY_AUTHENTICATION,
SEARCH_SECURITY_LEVEL);
}
// -----------------------------------------------
// Get the environment properties (props) for
// creating initial context and specifying LDAP
// service provider parameters.
// -----------------------------------------------
ctx = new InitialDirContext(props);
return ctx;
}
/**
* Print out all the attributes.
*
* @param attributes
* @throws NamingException
*/
private void printAttributes(Attributes attributes) throws NamingException {
String attrType;
Attribute attr;
NamingEnumeration ne;
// Iterate through the attributes..
for (NamingEnumeration a = attributes.getAll(); a.hasMore();) {
attr = (Attribute) a.next();
System.out.print(attr.getID() + ": ");
ne = attr.getAll();
while (ne.hasMore()) {
System.out.print(ne.next());
}
System.out.print("\n");
}
}
/**
* Search for an attribute (name, value) in the tree.
*
* @param attributeName
* @param attributeValue
* @return true if the attribute is found. false o/w
*/
private boolean searchAttribute(String attributeName, String attributeValue) {
boolean bFoundIt = false;
// must specify a DN
if ((MiscFuncs.isStringEmpty(attributeName))
|| (MiscFuncs.isStringEmpty(attributeValue))) {
System.out.println("You must specify an attribute name and value");
return bFoundIt;
}
return searchWithFilter(attributeName + "=" + attributeValue);
}
private boolean searchWithFilter(String filter) {
boolean bFoundIt = false;
// must specify a DN
if (MiscFuncs.isStringEmpty(filter)) {
System.out.println("You must specify a filter");
return bFoundIt;
}
DirContext ctx = null;
try {
System.out.print("Search using " + filter);
// -----------------------------------------------
// note that the search security level does not
// require a root user id and password.
// -----------------------------------------------
ctx = connectLDAP(false);
// ------------------------------------------------
// Search the named object (searchDN) and all of its
// descendants.
// ------------------------------------------------
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
// ------------------------------------------------
// Retrieve the attributes found in the ePerson schema
// ------------------------------------------------
constraints.setReturningAttributes(EPERSON_ATTRIBUTE_LIST);
// Search the context specified in the String object BASE_SEARCH
// This is set to "ou=people,dc=ibm,dc=com"
NamingEnumeration results = ctx.search(BASE_SEARCH, filter,
constraints);
if (results.hasMoreElements()) {
System.out.println(" has returned results..\n");
bFoundIt = true;
// Since UID is unique across the entire directory,
// the search results should contain only one entry.
SearchResult sr = (SearchResult) results.next();
// --------------------------------------------------------
// Get all available attribute types and their associated
// values and print them out.
// --------------------------------------------------------
printAttributes(sr.getAttributes());
} else {
System.out.println(" has returned no results..");
}
} catch (Exception e) {
System.out.println("Exception : " + e.toString());
}
//always close the directory context when you are done
finally {
try {
if (null != ctx)
ctx.close();
} catch (Exception e2) {
}
}
System.out.println("--------------------------------------------");
System.out.println("Found it " + bFoundIt);
return bFoundIt;
}
/**
* Update the relative DN with a new attribute name, value pair
*
* @param updateDN
* @param attrName -
* The name of the attribute
* @param attrVal -
* The value associated with the attribute.
* @param bRemoveAttribute -
* Delete the attribute.
* @return true if the attribute was updated. false o/w.
*/
private boolean updateAttribute(String updateDN, String attrName,
String attrVal, boolean bRemoveAttribute) {
boolean bUpdatedIt = false;
// must specify a re lative DN, attribute name and value.
if ((MiscFuncs.isStringEmpty(updateDN))
|| (MiscFuncs.isStringEmpty(attrName))
|| (MiscFuncs.isStringEmpty(attrVal))) {
System.out
.println("You must specify a DN, attribute name and attribute value.");
return bUpdatedIt;
}
DirContext ctx = null;
try {
System.out.print("Update attribute for " + updateDN + " attr: "
+ attrName + ": " + attrVal);
//--------------------------------------------------
ctx = connectLDAP(true);
// Search the named object and all of its descendants.
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
// Retrieve the specified attributes only..
constraints.setReturningAttributes(EPERSON_ATTRIBUTE_LIST);
// Search the context specified in the String object "base".
// For TestLDAP, it is "ou=bluepages,o=ibm.com".
NamingEnumeration results = ctx.search(BASE_SEARCH, updateDN,
constraints);
if (results.hasMoreElements()) {
System.out.println(" has returned results..\n");
// Since UID is unique across the entire directory,
// the search results should contain only one entry.
SearchResult sr = (SearchResult) results.next();
// Get all available attribute types and their associated
// values.
Attributes attributes = sr.getAttributes();
// Specify the changes to make
ModificationItem[] mods = new ModificationItem[1];
// -------------------------------------------
// remove the attribute
// -------------------------------------------
if (bRemoveAttribute) {
// eliminate the attribute
if (null != attributes.get(attrName)) {
mods[0] = new ModificationItem(
DirContext.REMOVE_ATTRIBUTE,
new BasicAttribute(attrName, attrVal));
}
}
// -------------------------------------------
// replace or add the attribute
// -------------------------------------------
else {
// do a replace of the attribute
if (null != attributes.get(attrName)) {
mods[0] = new ModificationItem(
DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute(attrName, attrVal));
}
// add the attribute
else {
mods[0] = new ModificationItem(
DirContext.ADD_ATTRIBUTE, new BasicAttribute(
attrName, attrVal));
}
}
ctx.modifyAttributes(updateDN + "," + BASE_SEARCH, mods);
ctx.close();
// -------------------------------------------
// do a search just to see the updated value
bUpdatedIt = searchAttribute(attrName, attrVal);
if (bUpdatedIt && !bRemoveAttribute) {
System.out.println("Entry was updated.");
}
if (!bUpdatedIt && bRemoveAttribute) {
bUpdatedIt = true;
System.out.println("Entry was removed.");
}
} else {
System.out.println(" has returned no results..");
}
} catch (Exception e) {
System.out.println("Exception : " + e.toString());
}
// always close the directory context when you are done
finally {
try {
if (null != ctx)
ctx.close();
} catch (Exception e2) {
}
}
System.out.println("--------------------------------------------");
System.out.println("Updated it " + bUpdatedIt);
return bUpdatedIt;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -