protected LDAPObject queryByEmail(RealmModel realm, String email) {
    LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(this, realm);
    LDAPQueryConditionsBuilder conditionsBuilder = new LDAPQueryConditionsBuilder();

    // Mapper should replace "email" in parameter name with correct LDAP mapped attribute
    Condition emailCondition = conditionsBuilder.equal(new QueryParameter(UserModel.EMAIL), email);
    ldapQuery.where(emailCondition);

    return ldapQuery.getFirstResult();
  }
  protected List<LDAPObject> searchLDAP(
      RealmModel realm, Map<String, String> attributes, int maxResults) {

    List<LDAPObject> results = new ArrayList<LDAPObject>();
    if (attributes.containsKey(USERNAME)) {
      LDAPObject user = loadLDAPUserByUsername(realm, attributes.get(USERNAME));
      if (user != null) {
        results.add(user);
      }
    }

    if (attributes.containsKey(EMAIL)) {
      LDAPObject user = queryByEmail(realm, attributes.get(EMAIL));
      if (user != null) {
        results.add(user);
      }
    }

    if (attributes.containsKey(FIRST_NAME) || attributes.containsKey(LAST_NAME)) {
      LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(this, realm);
      LDAPQueryConditionsBuilder conditionsBuilder = new LDAPQueryConditionsBuilder();

      // Mapper should replace parameter with correct LDAP mapped attributes
      if (attributes.containsKey(FIRST_NAME)) {
        ldapQuery.where(
            conditionsBuilder.equal(new QueryParameter(FIRST_NAME), attributes.get(FIRST_NAME)));
      }
      if (attributes.containsKey(LAST_NAME)) {
        ldapQuery.where(
            conditionsBuilder.equal(new QueryParameter(LAST_NAME), attributes.get(LAST_NAME)));
      }

      List<LDAPObject> ldapObjects = ldapQuery.getResultList();
      results.addAll(ldapObjects);
    }

    return results;
  }
  public LDAPObject loadLDAPUserByUsername(RealmModel realm, String username) {
    LDAPQuery ldapQuery = LDAPUtils.createQueryForUserSearch(this, realm);
    LDAPQueryConditionsBuilder conditionsBuilder = new LDAPQueryConditionsBuilder();

    String usernameMappedAttribute = this.ldapIdentityStore.getConfig().getUsernameLdapAttribute();
    Condition usernameCondition = conditionsBuilder.equal(usernameMappedAttribute, username);
    ldapQuery.addWhereCondition(usernameCondition);

    LDAPObject ldapUser = ldapQuery.getFirstResult();
    if (ldapUser == null) {
      return null;
    }

    return ldapUser;
  }