Java Code Examples for javax.naming.directory.DirContext#lookup()

The following examples show how to use javax.naming.directory.DirContext#lookup() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReadWriteLDAPUserStoreManager.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 2
Source File: LdapTemplateAuthenticationITest.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 3
Source File: WebdavServlet.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 4
Source File: BaseDirContext.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 5
Source File: WebdavServlet.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 6
Source File: ApacheLDAPServerTest.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
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());

}
 
Example 7
Source File: SecureWebdavServlet.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * 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");

}
 
Example 8
Source File: SecureWebdavServlet.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * 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");

}
 
Example 9
Source File: LoginFilter.java    From iaf with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 10
Source File: SchemaViewer.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
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(""));
}
 
Example 11
Source File: LookupAttemptingCallback.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 12
Source File: BaseDirContext.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 13
Source File: AbstractCachedLDAPAuthorizationMapLegacyTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
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);
}