title: How can I just check if a given username exists?
body: <p>I have an application that uses both LDAP and simple database authentication to log users in. Only if the user does not exists in the LDAP context, the application checks if he exists in the database. So I need a way to check if the users exists in LDAP, without knowing the password. I mention that usernames are unique.</p>
  
  <p>I use this code, which works if I have a correct username and password. If the password OR the username are wrong, I get an exception. It would be ideal if I could get different exceptions, one if the username does not exist, other if the password provided is wrong.</p>
  
  <pre><code>    String username = "test";
      String password = "pass";
      Hashtable&lt;String, String&gt; environment = new Hashtable&lt;String, String&gt;();
      environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
      environment.put(Context.PROVIDER_URL, "ldap://server.example.com:389");
      environment.put(Context.SECURITY_AUTHENTICATION, "simple");
      String user = username + "@example.com";
      environment.put(Context.SECURITY_PRINCIPAL, user ); 
      environment.put(Context.SECURITY_CREDENTIALS, password);
      try
      {
          DirContext context = new InitialDirContext(environment);
  
          String searchBase = "DC=server,DC=example,DC=COM";
          String FILTER = "(&amp;(objectClass=user)(objectCategory=person)((sAMAccountName=" + username + ")))";
          SearchControls ctls = new SearchControls();
          ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
          NamingEnumeration&lt;SearchResult&gt; answer = context.search(searchBase, FILTER, ctls);
          SearchResult result = answer.next();
          Attribute email = result.getAttributes().get("mail");
          Attribute cn = result.getAttributes().get("cn");
          System.out.println(cn + " : " + email);
          context.close();
      }
      catch (AuthenticationException a)
      {
          Logger.getLogger().info("Authentication failed: " + a.getExplanation());
  
      }
      catch (NamingException e)
      {
          Logger.getLogger().info("Failed to bind to LDAP: " + e.getExplanation());
      }
  </code></pre>