下面列出了javax.naming.directory.DirContext#lookup ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Returns the directory context for the user search base
*
* @return
* @throws NamingException
* @throws UserStoreException
*/
protected DirContext getSearchBaseDirectoryContext() throws UserStoreException {
DirContext mainDirContext = this.connectionSource.getContext();
// assume first search base in case of multiple definitions
String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE).split("#")[0];
try {
return (DirContext) mainDirContext.lookup(escapeDNForSearch(searchBase));
} catch (NamingException e) {
String errorMessage = "Can not access the directory context or"
+ "user already exists in the system";
if (log.isDebugEnabled()) {
log.debug(errorMessage, e);
}
throw new UserStoreException(errorMessage, e);
} finally {
JNDIUtil.closeContext(mainDirContext);
}
}
@Test
@Category(NoAdTest.class)
public void testAuthenticateWithLookupOperationPerformedOnAuthenticatedContext() {
AndFilter filter = new AndFilter();
filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3"));
AuthenticatedLdapEntryContextCallback contextCallback = new AuthenticatedLdapEntryContextCallback() {
public void executeWithContext(DirContext ctx, LdapEntryIdentification ldapEntryIdentification) {
try {
DirContextAdapter adapter = (DirContextAdapter) ctx.lookup(ldapEntryIdentification.getRelativeDn());
assertThat(adapter.getStringAttribute("cn")).isEqualTo("Some Person3");
}
catch (NamingException e) {
throw new RuntimeException("Failed to lookup " + ldapEntryIdentification.getRelativeDn(), e);
}
}
};
assertThat(tested.authenticate("", filter.toString(), "password", contextCallback)).isTrue();
}
/**
* Determines the methods normally allowed for the resource.
*
*/
private StringBuilder determineMethodsAllowed(DirContext dirContext,
HttpServletRequest req) {
StringBuilder methodsAllowed = new StringBuilder();
boolean exists = true;
Object object = null;
try {
String path = getRelativePath(req);
object = dirContext.lookup(path);
} catch (NamingException e) {
exists = false;
}
if (!exists) {
methodsAllowed.append("OPTIONS, MKCOL, PUT, LOCK");
return methodsAllowed;
}
methodsAllowed.append("OPTIONS, GET, HEAD, POST, DELETE, TRACE");
methodsAllowed.append(", PROPPATCH, COPY, MOVE, LOCK, UNLOCK");
if (listings) {
methodsAllowed.append(", PROPFIND");
}
if (!(object instanceof DirContext)) {
methodsAllowed.append(", PUT");
}
return methodsAllowed;
}
private Object doLookupWithoutNNFE(String name) throws NamingException {
if (!aliases.isEmpty()) {
AliasResult result = findAlias(name);
if (result.dirContext != null) {
return result.dirContext.lookup(result.aliasName);
}
}
// Next do a standard lookup
Object obj = doLookup(name);
if (obj != null) {
return obj;
}
// Check the alternate locations
String resourceName = "/META-INF/resources" + name;
for (DirContext altDirContext : altDirContexts) {
if (altDirContext instanceof BaseDirContext) {
obj = ((BaseDirContext) altDirContext)
.doLookupWithoutNNFE(resourceName);
} else {
try {
obj = altDirContext.lookup(resourceName);
} catch (NamingException ex) {
// ignore
}
}
if (obj != null) {
return obj;
}
}
// Return null instead
return null;
}
/**
* Determines the methods normally allowed for the resource.
*
*/
private StringBuilder determineMethodsAllowed(DirContext dirContext,
HttpServletRequest req) {
StringBuilder methodsAllowed = new StringBuilder();
boolean exists = true;
Object object = null;
try {
String path = getRelativePath(req);
object = dirContext.lookup(path);
} catch (NamingException e) {
exists = false;
}
if (!exists) {
methodsAllowed.append("OPTIONS, MKCOL, PUT, LOCK");
return methodsAllowed;
}
methodsAllowed.append("OPTIONS, GET, HEAD, POST, DELETE, TRACE");
methodsAllowed.append(", PROPPATCH, COPY, MOVE, LOCK, UNLOCK");
if (listings) {
methodsAllowed.append(", PROPFIND");
}
if (!(object instanceof DirContext)) {
methodsAllowed.append(", PUT");
}
return methodsAllowed;
}
private void addMyUser(DirContext ctx, String name)
throws Exception {
MyUser user = new MyUser("amilaj", "Jayasekara", "Amila");
ctx.bind(name, user);
// Lookup
DirContext obj = (DirContext)ctx.lookup(name);
assertNotNull(obj);
LOG.info("User is bound to: " + obj.getNameInNamespace());
}
/**
* OPTIONS Method.
*/
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = getRelativePath(req);
resp.addHeader("DAV", "1,2");
String methodsAllowed = null;
// Retrieve the resources
DirContext resources = getResources(req);
if (resources == null) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
boolean exists = true;
Object object = null;
try {
object = resources.lookup(path);
} catch (NamingException e) {
exists = false;
}
if (!exists) {
methodsAllowed = "OPTIONS, MKCOL, PUT, LOCK";
resp.addHeader("Allow", methodsAllowed);
return;
}
methodsAllowed = "OPTIONS, GET, HEAD, POST, DELETE, TRACE, " + "PROPFIND, PROPPATCH, COPY, MOVE, LOCK, UNLOCK";
if (!(object instanceof DirContext)) {
methodsAllowed += ", PUT";
}
resp.addHeader("Allow", methodsAllowed);
resp.addHeader("MS-Author-Via", "DAV");
}
/**
* OPTIONS Method.
*/
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = getRelativePath(req);
resp.addHeader("DAV", "1,2");
String methodsAllowed = null;
// Retrieve the resources
DirContext resources = getResources(req);
if (resources == null) {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
boolean exists = true;
Object object = null;
try {
object = resources.lookup(path);
} catch (NamingException e) {
exists = false;
}
if (!exists) {
methodsAllowed = "OPTIONS, MKCOL, PUT, LOCK";
resp.addHeader("Allow", methodsAllowed);
return;
}
methodsAllowed = "OPTIONS, GET, HEAD, POST, DELETE, TRACE, " + "PROPFIND, PROPPATCH, COPY, MOVE, LOCK, UNLOCK";
if (!(object instanceof DirContext)) {
methodsAllowed += ", PUT";
}
resp.addHeader("Allow", methodsAllowed);
resp.addHeader("MS-Author-Via", "DAV");
}
private boolean isMemberOf(DirContext ctx, String dnUser, String dnGroup) throws NamingException {
DirContext lookedContext = (DirContext) (ctx.lookup(dnGroup));
Attribute attrs = lookedContext.getAttributes("").get("member");
for (int i = 0; i < attrs.size(); i++) {
String foundMember = (String) attrs.get(i);
if (foundMember.equalsIgnoreCase(dnUser)) {
return true;
}
}
return false;
}
private static void printObject(String contextName, String schemaName, DirContext schemaContext)
throws NameNotFoundException, NamingException {
DirContext oContext = (DirContext)schemaContext.lookup(contextName + "/" + schemaName);
outstream.println("NAME:" + schemaName);
printAttrs(oContext.getAttributes(""));
}
@Override
public DirContextOperations mapWithContext(DirContext ctx, LdapEntryIdentification ldapEntryIdentification) {
try {
return (DirContextOperations) ctx.lookup(ldapEntryIdentification.getRelativeName());
}
catch (NamingException e) {
// rethrow, because we aren't allowed to throw checked exceptions.
throw LdapUtils.convertLdapException(e);
}
}
private Object doLookupWithoutNNFE(String name) throws NamingException {
if (!aliases.isEmpty()) {
AliasResult result = findAlias(name);
if (result.dirContext != null) {
return result.dirContext.lookup(result.aliasName);
}
}
// Next do a standard lookup
Object obj = doLookup(name);
if (obj != null) {
return obj;
}
// Class files may not be loaded from the alternate locations so don't
// waste cycles looking.
if (name.endsWith(".class")) {
return null;
}
// Check the alternate locations (Resource JARs)
String resourceName = "/META-INF/resources" + name;
for (DirContext altDirContext : altDirContexts) {
if (altDirContext instanceof BaseDirContext) {
obj = ((BaseDirContext) altDirContext)
.doLookupWithoutNNFE(resourceName);
} else {
try {
obj = altDirContext.lookup(resourceName);
} catch (NamingException ex) {
// ignore
}
}
if (obj != null) {
return obj;
}
}
// Return null instead
return null;
}
public static void cleanAndLoad(String deleteFromDn,
String ldifResourcePath,
String ldapHost,
int ldapPort,
String ldapUser,
String ldapPass,
DirContext context) throws Exception {
// Cleanup everything used for testing.
List<String> dns = new LinkedList<>();
dns.add(deleteFromDn);
while (!dns.isEmpty()) {
String name = dns.get(dns.size() - 1);
Context currentContext = (Context) context.lookup(name);
NamingEnumeration<NameClassPair> namingEnum = currentContext.list("");
if (namingEnum.hasMore()) {
while (namingEnum.hasMore()) {
dns.add(namingEnum.next().getNameInNamespace());
}
} else {
context.unbind(name);
dns.remove(dns.size() - 1);
}
}
// A bit of a hacked approach to loading an LDIF into OpenLDAP since there isn't an easy way to do it
// otherwise. This approach invokes the command line tool programmatically but has
// to short-circuit the call to System.exit that the command line tool makes when it finishes.
// We are assuming that there isn't already a security manager in place.
final SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPermission(java.security.Permission permission) {
if (permission.getName().contains("exitVM")) {
throw new SecurityException("System.exit calls disabled for the moment.");
}
}
};
System.setSecurityManager(securityManager);
File file = new File(AbstractCachedLDAPAuthorizationMapLegacyTest.class.getClassLoader().getResource(ldifResourcePath).toURI());
Class<?> clazz = Class.forName("LDAPModify");
Method mainMethod = clazz.getMethod("main", String[].class);
try {
mainMethod.invoke(null, new Object[]{new String[]{"-v", "-h", ldapHost, "-p", String.valueOf(ldapPort), "-D", ldapUser, "-w", ldapPass, "-a", "-f", file.toString()}});
} catch (InvocationTargetException e) {
if (!(e.getTargetException() instanceof SecurityException)) {
throw e;
}
}
System.setSecurityManager(null);
}