下面列出了怎么用javax.naming.ldap.Control的API类实例代码及写法,或者点击链接到github查看源代码。
SimpleClientId(int version, String hostname, int port,
String protocol, Control[] bindCtls, OutputStream trace,
String socketFactory, String username, Object passwd) {
super(version, hostname, port, protocol, bindCtls, trace,
socketFactory);
this.username = username;
int pwdHashCode = 0;
if (passwd == null) {
this.passwd = null;
} else if (passwd instanceof byte[]) {
this.passwd = ((byte[])passwd).clone();
pwdHashCode = Arrays.hashCode((byte[])passwd);
} else if (passwd instanceof char[]) {
this.passwd = ((char[])passwd).clone();
pwdHashCode = Arrays.hashCode((char[])passwd);
} else {
this.passwd = passwd;
pwdHashCode = passwd.hashCode();
}
myHash = super.hashCode()
^ (username != null ? username.hashCode() : 0)
^ pwdHashCode;
}
DigestClientId(int version, String hostname, int port,
String protocol, Control[] bindCtls, OutputStream trace,
String socketFactory, String username,
Object passwd, Hashtable<?,?> env) {
super(version, hostname, port, protocol, bindCtls, trace,
socketFactory, username, passwd);
if (env == null) {
propvals = null;
} else {
// Could be smarter and apply default values for props
// but for now, we just record and check exact matches
propvals = new String[SASL_PROPS.length];
for (int i = 0; i < SASL_PROPS.length; i++) {
propvals[i] = (String) env.get(SASL_PROPS[i]);
}
}
myHash = super.hashCode() ^ Arrays.hashCode(propvals);
}
public static void main(String[] args) throws Throwable {
Class<?> simpleClientIdClass
= Class.forName("com.sun.jndi.ldap.SimpleClientId");
Constructor<?> init = simpleClientIdClass.getDeclaredConstructor(
int.class, String.class, int.class, String.class,
Control[].class, OutputStream.class, String.class,
String.class, Object.class);
init.setAccessible(true);
Object p1 = new byte[]{66,77};
Object p2 = new char[]{'w','d'};
Object p3 = "word";
test(init, new byte[]{65}, new byte[]{65});
test(init, new char[]{'p'}, new char[]{'p'});
test(init, "pass", "pass");
test(init, p1, p1);
test(init, p2, p2);
test(init, p3, p3);
test(init, null, null);
}
private static boolean equalsControls(Control[] a, Control[] b) {
if (a == b) {
return true; // both null or same
}
if (a == null || b == null) {
return false; // one is non-null
}
if (a.length != b.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].getID().equals(b[i].getID())
|| a[i].isCritical() != b[i].isCritical()
|| !Arrays.equals(a[i].getEncodedValue(),
b[i].getEncodedValue())) {
return false;
}
}
return true;
}
/**
* Gets a context at which to continue processing.
* The supplied environment properties and connection controls are used.
*/
public Context getReferralContext(Hashtable<?,?> newProps, Control[] connCtls)
throws NamingException {
if (debug)
System.out.println("LdapReferralException.getReferralContext");
LdapReferralContext refCtx = new LdapReferralContext(
this, newProps, connCtls, reqCtls,
nextName, skipThisReferral, handleReferrals);
refCtx.setHopCount(hopCount + 1);
if (skipThisReferral) {
skipThisReferral = false; // reset
}
return (Context)refCtx;
}
DigestClientId(int version, String hostname, int port,
String protocol, Control[] bindCtls, OutputStream trace,
String socketFactory, String username,
Object passwd, Hashtable<?,?> env) {
super(version, hostname, port, protocol, bindCtls, trace,
socketFactory, username, passwd);
if (env == null) {
propvals = null;
} else {
// Could be smarter and apply default values for props
// but for now, we just record and check exact matches
propvals = new String[SASL_PROPS.length];
for (int i = 0; i < SASL_PROPS.length; i++) {
propvals[i] = (String) env.get(SASL_PROPS[i]);
}
}
myHash = super.hashCode() ^ Arrays.hashCode(propvals);
}
DigestClientId(int version, String hostname, int port,
String protocol, Control[] bindCtls, OutputStream trace,
String socketFactory, String username,
Object passwd, Hashtable<?,?> env) {
super(version, hostname, port, protocol, bindCtls, trace,
socketFactory, username, passwd);
if (env == null) {
propvals = null;
} else {
// Could be smarter and apply default values for props
// but for now, we just record and check exact matches
propvals = new String[SASL_PROPS.length];
for (int i = 0; i < SASL_PROPS.length; i++) {
propvals[i] = (String) env.get(SASL_PROPS[i]);
}
}
myHash = super.hashCode() ^ Arrays.hashCode(propvals);
}
SimpleClientId(int version, String hostname, int port,
String protocol, Control[] bindCtls, OutputStream trace,
String socketFactory, String username, Object passwd) {
super(version, hostname, port, protocol, bindCtls, trace,
socketFactory);
this.username = username;
int pwdHashCode = 0;
if (passwd == null) {
this.passwd = null;
} else if (passwd instanceof byte[]) {
this.passwd = ((byte[])passwd).clone();
pwdHashCode = Arrays.hashCode((byte[])passwd);
} else if (passwd instanceof char[]) {
this.passwd = ((char[])passwd).clone();
pwdHashCode = Arrays.hashCode((char[])passwd);
} else {
this.passwd = passwd;
pwdHashCode = passwd.hashCode();
}
myHash = super.hashCode()
^ (username != null ? username.hashCode() : 0)
^ pwdHashCode;
}
UnsolicitedResponseImpl(String oid, byte[] berVal, Vector<Vector<String>> ref,
int status, String msg, String matchedDN, Control[] controls) {
this.oid = oid;
this.extensionValue = berVal;
if (ref != null && ref.size() > 0) {
int len = ref.size();
referrals = new String[len];
for (int i = 0; i < len; i++) {
// ref is a list of single-String Vectors
referrals[i] = ref.elementAt(i).elementAt(0);
}
}
exception = LdapCtx.mapErrorCode(status, msg);
// matchedDN ignored for now; could be used to set resolvedName
// exception.setResolvedName(new CompositeName().add(matchedDN));
this.controls = controls;
}
UnsolicitedResponseImpl(String oid, byte[] berVal, Vector<Vector<String>> ref,
int status, String msg, String matchedDN, Control[] controls) {
this.oid = oid;
this.extensionValue = berVal;
if (ref != null && ref.size() > 0) {
int len = ref.size();
referrals = new String[len];
for (int i = 0; i < len; i++) {
// ref is a list of single-String Vectors
referrals[i] = ref.elementAt(i).elementAt(0);
}
}
exception = LdapCtx.mapErrorCode(status, msg);
// matchedDN ignored for now; could be used to set resolvedName
// exception.setResolvedName(new CompositeName().add(matchedDN));
this.controls = controls;
}
private static boolean equalsControls(Control[] a, Control[] b) {
if (a == b) {
return true; // both null or same
}
if (a == null || b == null) {
return false; // one is non-null
}
if (a.length != b.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].getID().equals(b[i].getID())
|| a[i].isCritical() != b[i].isCritical()
|| !Arrays.equals(a[i].getEncodedValue(),
b[i].getEncodedValue())) {
return false;
}
}
return true;
}
/**
* Gets a context at which to continue processing.
* The supplied environment properties and connection controls are used.
*/
public Context getReferralContext(Hashtable<?,?> newProps, Control[] connCtls)
throws NamingException {
if (debug)
System.out.println("LdapReferralException.getReferralContext");
LdapReferralContext refCtx = new LdapReferralContext(
this, newProps, connCtls, reqCtls,
nextName, skipThisReferral, handleReferrals);
refCtx.setHopCount(hopCount + 1);
if (skipThisReferral) {
skipThisReferral = false; // reset
}
return (Context)refCtx;
}
public static void main(String[] args) throws Throwable {
Class<?> simpleClientIdClass
= Class.forName("com.sun.jndi.ldap.SimpleClientId");
Constructor<?> init = simpleClientIdClass.getDeclaredConstructor(
int.class, String.class, int.class, String.class,
Control[].class, OutputStream.class, String.class,
String.class, Object.class);
init.setAccessible(true);
Object p1 = new byte[]{66,77};
Object p2 = new char[]{'w','d'};
Object p3 = "word";
test(init, new byte[]{65}, new byte[]{65});
test(init, new char[]{'p'}, new char[]{'p'});
test(init, "pass", "pass");
test(init, p1, p1);
test(init, p2, p2);
test(init, p3, p3);
test(init, null, null);
}
DigestClientId(int version, String hostname, int port,
String protocol, Control[] bindCtls, OutputStream trace,
String socketFactory, String username,
Object passwd, Hashtable<?,?> env) {
super(version, hostname, port, protocol, bindCtls, trace,
socketFactory, username, passwd);
if (env == null) {
propvals = null;
} else {
// Could be smarter and apply default values for props
// but for now, we just record and check exact matches
propvals = new String[SASL_PROPS.length];
for (int i = 0; i < SASL_PROPS.length; i++) {
propvals[i] = (String) env.get(SASL_PROPS[i]);
if (propvals[i] != null) {
pHash = pHash * 31 + propvals[i].hashCode();
}
}
}
myHash = super.hashCode() + pHash;
}
SimpleClientId(int version, String hostname, int port,
String protocol, Control[] bindCtls, OutputStream trace,
String socketFactory, String username, Object passwd) {
super(version, hostname, port, protocol, bindCtls, trace,
socketFactory);
this.username = username;
if (passwd == null) {
this.passwd = null;
} else if (passwd instanceof String) {
this.passwd = passwd;
} else if (passwd instanceof byte[]) {
this.passwd = ((byte[])passwd).clone();
} else if (passwd instanceof char[]) {
this.passwd = ((char[])passwd).clone();
} else {
this.passwd = passwd;
}
myHash = super.hashCode()
+ (username != null ? username.hashCode() : 0)
+ (passwd != null ? passwd.hashCode() : 0);
}
UnsolicitedResponseImpl(String oid, byte[] berVal, Vector<Vector<String>> ref,
int status, String msg, String matchedDN, Control[] controls) {
this.oid = oid;
this.extensionValue = berVal;
if (ref != null && ref.size() > 0) {
int len = ref.size();
referrals = new String[len];
for (int i = 0; i < len; i++) {
// ref is a list of single-String Vectors
referrals[i] = ref.elementAt(i).elementAt(0);
}
}
exception = LdapCtx.mapErrorCode(status, msg);
// matchedDN ignored for now; could be used to set resolvedName
// exception.setResolvedName(new CompositeName().add(matchedDN));
this.controls = controls;
}
private static boolean equalsControls(Control[] a, Control[] b) {
if (a == b) {
return true; // both null or same
}
if (a == null || b == null) {
return false; // one is non-null
}
if (a.length != b.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].getID().equals(b[i].getID())
|| a[i].isCritical() != b[i].isCritical()
|| !Arrays.equals(a[i].getEncodedValue(),
b[i].getEncodedValue())) {
return false;
}
}
return true;
}
/**
* Gets a context at which to continue processing.
* The supplied environment properties and connection controls are used.
*/
public Context getReferralContext(Hashtable<?,?> newProps, Control[] connCtls)
throws NamingException {
if (debug)
System.out.println("LdapReferralException.getReferralContext");
LdapReferralContext refCtx = new LdapReferralContext(
this, newProps, connCtls, reqCtls,
nextName, skipThisReferral, handleReferrals);
refCtx.setHopCount(hopCount + 1);
if (skipThisReferral) {
skipThisReferral = false; // reset
}
return (Context)refCtx;
}
/**
* Parse the controls to navigate to next page.
*
* @param controls
* @return
*/
private static byte[] parseControls(Control[] controls) {
byte[] cookie = null;
// Handle the paged results control response
if (controls != null) {
for (int i = 0; i < controls.length; i++) {
if (controls[i] instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
cookie = prrc.getCookie();
}
}
}
return cookie;
}
/**
* Creates the proxy for LDAP context and wrap the context.
* Calculate the time taken for creation
*
* @param environment Used to get provider url and principal
* @param connectionControls The wrapped context
* @return ldap connection context
* @throws NamingException
*/
private LdapContext getLdapContext(Hashtable<?, ?> environment, Control[] connectionControls)
throws NamingException, UserStoreException {
if (Boolean.parseBoolean(System.getProperty(CORRELATION_LOG_SYSTEM_PROPERTY))) {
final Class[] proxyInterfaces = new Class[]{LdapContext.class};
long start = System.currentTimeMillis();
LdapContext context = initializeLdapContext(environment, connectionControls);
Object proxy = Proxy.newProxyInstance(LDAPConnectionContext.class.getClassLoader(), proxyInterfaces,
new LdapContextInvocationHandler(context));
long delta = System.currentTimeMillis() - start;
CorrelationLogDTO correlationLogDTO = new CorrelationLogDTO();
correlationLogDTO.setStartTime(start);
correlationLogDTO.setDelta(delta);
correlationLogDTO.setEnvironment(environment);
correlationLogDTO.setMethodName(CORRELATION_LOG_INITIALIZATION_METHOD_NAME);
correlationLogDTO.setArgsLength(CORRELATION_LOG_INITIALIZATION_ARGS_LENGTH);
correlationLogDTO.setArgs(CORRELATION_LOG_INITIALIZATION_ARGS);
logDetails(correlationLogDTO);
return (LdapContext) proxy;
} else {
return initializeLdapContext(environment, connectionControls);
}
}
/**
* Initialize the LDAP context.
*
* @param environment environment used to create the initial Context.
* @param connectionControls connection request controls for the initial context.
* @return ldap connection context.
* @throws NamingException if a naming exception is encountered.
* @throws UserStoreException if a user store related exception is encountered.
*/
private LdapContext initializeLdapContext(Hashtable<?, ?> environment, Control[] connectionControls)
throws NamingException, UserStoreException {
if (startTLSEnabled) {
return LdapContextWrapper.startTLS(environment, connectionControls);
} else {
return new InitialLdapContext(environment, connectionControls);
}
}
private static int hashCodeControls(Control[] c) {
if (c == null) {
return 0;
}
int code = 0;
for (int i = 0; i < c.length; i++) {
code = code * 31 + c[i].getID().hashCode();
}
return code;
}
private void ldapUnbind(Control[] reqCtls) {
BerEncoder ber = new BerEncoder(256);
int unbindMsgId = getMsgId();
//
// build the unbind request.
//
try {
ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
ber.encodeInt(unbindMsgId);
// IMPLICIT TAGS
ber.encodeByte(LdapClient.LDAP_REQ_UNBIND);
ber.encodeByte(0);
if (v3) {
LdapClient.encodeControls(ber, reqCtls);
}
ber.endSeq();
if (traceFile != null) {
Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(),
0, ber.getDataLen());
}
synchronized (this) {
outStream.write(ber.getBuf(), 0, ber.getDataLen());
outStream.flush();
}
} catch (IOException ex) {
//System.err.println("ldap.unbind: " + ex);
}
// Don't expect any response for the unbind request.
}
void abandonRequest(LdapRequest ldr, Control[] reqCtls) {
// Remove from queue
removeRequest(ldr);
BerEncoder ber = new BerEncoder(256);
int abandonMsgId = getMsgId();
//
// build the abandon request.
//
try {
ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
ber.encodeInt(abandonMsgId);
ber.encodeInt(ldr.msgId, LdapClient.LDAP_REQ_ABANDON);
if (v3) {
LdapClient.encodeControls(ber, reqCtls);
}
ber.endSeq();
if (traceFile != null) {
Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(), 0,
ber.getDataLen());
}
synchronized (this) {
outStream.write(ber.getBuf(), 0, ber.getDataLen());
outStream.flush();
}
} catch (IOException ex) {
//System.err.println("ldap.abandon: " + ex);
}
// Don't expect any response for the abandon request.
}
/**
* Constructs a new instance of LdapReferralException.
* @param resolvedName The part of the name that has been successfully
* resolved.
* @param resolvedObj The object to which resolution was successful.
* @param remainingName The remaining unresolved portion of the name.
* @param explanation Additional detail about this exception.
*/
LdapReferralException(Name resolvedName,
Object resolvedObj,
Name remainingName,
String explanation,
Hashtable<?,?> envprops,
String nextName,
int handleReferrals,
Control[] reqCtls) {
super(explanation);
if (debug)
System.out.println("LdapReferralException constructor");
setResolvedName(resolvedName);
setResolvedObj(resolvedObj);
setRemainingName(remainingName);
this.envprops = envprops;
this.nextName = nextName;
this.handleReferrals = handleReferrals;
// If following referral, request controls are passed to referral ctx
this.reqCtls =
(handleReferrals == LdapClient.LDAP_REF_FOLLOW ||
handleReferrals == LdapClient.LDAP_REF_FOLLOW_SCHEME ? reqCtls : null);
}
private void ldapUnbind(Control[] reqCtls) {
BerEncoder ber = new BerEncoder(256);
int unbindMsgId = getMsgId();
//
// build the unbind request.
//
try {
ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
ber.encodeInt(unbindMsgId);
// IMPLICIT TAGS
ber.encodeByte(LdapClient.LDAP_REQ_UNBIND);
ber.encodeByte(0);
if (v3) {
LdapClient.encodeControls(ber, reqCtls);
}
ber.endSeq();
if (traceFile != null) {
Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(),
0, ber.getDataLen());
}
synchronized (this) {
outStream.write(ber.getBuf(), 0, ber.getDataLen());
outStream.flush();
}
} catch (IOException ex) {
//System.err.println("ldap.unbind: " + ex);
}
// Don't expect any response for the unbind request.
}
public Context getInitialContext(Hashtable<?,?> envprops)
throws NamingException {
try {
String providerUrl = (envprops != null) ?
(String)envprops.get(Context.PROVIDER_URL) : null;
// If URL not in environment, use defaults
if (providerUrl == null) {
return new LdapCtx("", LdapCtx.DEFAULT_HOST,
LdapCtx.DEFAULT_PORT, envprops, false);
}
// Extract URL(s)
String[] urls = LdapURL.fromList(providerUrl);
if (urls.length == 0) {
throw new ConfigurationException(Context.PROVIDER_URL +
" property does not contain a URL");
}
// Generate an LDAP context
return getLdapCtxInstance(urls, envprops);
} catch (LdapReferralException e) {
if (envprops != null &&
"throw".equals(envprops.get(Context.REFERRAL))) {
throw e;
}
Control[] bindCtls = (envprops != null)?
(Control[])envprops.get(LdapCtx.BIND_CONTROLS) : null;
return (LdapCtx)e.getReferralContext(envprops, bindCtls);
}
}
/**
* Obtains a pooled connection that either already exists or is
* newly created using the parameters supplied. If it is newly
* created, it needs to go through the authentication checks to
* determine whether an LDAP bind is necessary.
*
* Caller needs to invoke ldapClient.authenticateCalled() to
* determine whether ldapClient.authenticate() needs to be invoked.
* Caller has that responsibility because caller needs to deal
* with the LDAP bind response, which might involve referrals,
* response controls, errors, etc. This method is responsible only
* for establishing the connection.
*
* @return an LdapClient that is pooled.
*/
static LdapClient getLdapClient(String host, int port, String socketFactory,
int connTimeout, int readTimeout, OutputStream trace, int version,
String authMech, Control[] ctls, String protocol, String user,
Object passwd, Hashtable<?,?> env) throws NamingException {
// Create base identity for LdapClient
ClientId id = null;
Pool pool;
int p = findPool(authMech);
if (p < 0 || (pool=pools[p]) == null) {
throw new IllegalArgumentException(
"Attempting to use pooling for an unsupported mechanism: " +
authMech);
}
switch (p) {
case NONE:
id = new ClientId(version, host, port, protocol,
ctls, trace, socketFactory);
break;
case SIMPLE:
// Add identity information used in simple authentication
id = new SimpleClientId(version, host, port, protocol,
ctls, trace, socketFactory, user, passwd);
break;
case DIGEST:
// Add user/passwd/realm/authzid/qop/strength/maxbuf/mutual/policy*
id = new DigestClientId(version, host, port, protocol,
ctls, trace, socketFactory, user, passwd, env);
break;
}
return (LdapClient) pool.getPooledConnection(id, connTimeout,
new LdapClientFactory(host, port, socketFactory, connTimeout,
readTimeout, trace));
}
private static int hashCodeControls(Control[] c) {
if (c == null) {
return 0;
}
int code = 0;
for (int i = 0; i < c.length; i++) {
code = code * 31 + c[i].getID().hashCode();
}
return code;
}
private static String toStringControls(Control[] ctls) {
if (ctls == null) {
return "";
}
StringBuffer str = new StringBuffer();
for (int i = 0; i < ctls.length; i++) {
str.append(ctls[i].getID());
str.append(' ');
}
return str.toString();
}