title: LDAP query get all groups (nested) of a group
body: <p>I want to list all groups in a Active Directory, including nested.</p>
  
  <p>With this I get the top level groups: </p>
  
  <pre><code>try {
      Hashtable&lt;String,String&gt; props = new Hashtable&lt;String,String&gt;();
      props.put(Context.SECURITY_AUTHENTICATION, "simple");
      props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      props.put(Context.PROVIDER_URL, "ldap://adserver");
      props.put(Context.SECURITY_PRINCIPAL, "user@domain");
      props.put(Context.SECURITY_CREDENTIALS, "password");
  
      DirContext ctx = new InitialDirContext(props);
  
      SearchControls cons = new SearchControls();
      cons.setReturningAttributes(new String[] {"cn"});
      cons.setSearchScope(SearchControls.ONELEVEL_SCOPE);
  
      NamingEnumeration&lt;SearchResult&gt; answer = ctx.search("cn=users,dc=domain,dc=com", "(objectcategory=group)", cons);
      System.out.println("AD GROUPS:");
      while(answer.hasMore()) {
          SearchResult result = (SearchResult) answer.next();
          Attributes atts = result.getAttributes();
          Attribute att = atts.get("cn");
          String groupName = (String)att.get();
  
          //how to search for groups nested in this group
      }
  } catch (NamingException e) {
      e.printStackTrace();
  }
  </code></pre>
  
  <p>How can I fetch nested groups? I googled a little and found this two ways:</p>
  
  <pre><code>NamingEnumeration&lt;SearchResult&gt; nested = ctx.search("cn=users,dc=domain,dc=com", "(&amp;(objectClass=group)(objectCategory=group)(memberOf:1.2.840.113556.1.4.194:=cn="+groupName+"))", controls);
  </code></pre>
  
  <p>and</p>
  
  <pre><code>NamingEnumeration&lt;SearchResult&gt; nested = ctx.search("cn=users,dc=domain,dc=com", "(&amp;(objectClass=group)(objectCategory=group)(memberOf=CN="+groupName+"))", controls);
  </code></pre>
  
  <p>But this is not returning the nested groups. What am I doing wrong?</p>