title: Get Groups using Ldap in java
body: <p>How can i get a particular user groups using Active Directory ?
  I am getting all groups but i want to get groups which user is belonging </p>
  
  <pre><code>  public static String ldapUri = "ldap://pdc.example.com:389";
    public static String usersContainer = "cn=users,dc=example,dc=com";  
    public ArrayList&lt;String&gt; getUserGroups(String email, String password){
      ArrayList&lt;String&gt; list = new   ArrayList&lt;String&gt;();
         Hashtable env = new Hashtable();
      env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      env.put(Context.PROVIDER_URL, ldapUri);
      env.put(Context.SECURITY_PRINCIPAL, email);
      env.put(Context.SECURITY_CREDENTIALS, password);
      try {
          DirContext ctx = new InitialDirContext(env);
          SearchControls ctls = new SearchControls();
          String[] attrIDs = { "cn" };
          ctls.setReturningAttributes(attrIDs);
          ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
  
          NamingEnumeration answer = ctx.search(usersContainer, "     (objectclass=group)", ctls);
          while (answer.hasMore()) {
          SearchResult rslt = (SearchResult) answer.next();
          Attributes attrs = rslt.getAttributes();
          String groups = attrs.get("cn").toString();
          String [] groupname = groups.split(":");
          String userGroup = groupname[1];
          System.out.println(attrs.get("cn"));
          }
          ctx.close();
          } catch (NamingException e) {
          e.printStackTrace();
      }
      return list;
    }
  </code></pre>