ldap.LdapApi.java Source code

Java tutorial

Introduction

Here is the source code for ldap.LdapApi.java

Source

/**
* Copyright (c) 2001-2012 "Redbasin Networks, INC" [http://redbasin.org]
*
* This file is part of Redbasin OpenDocShare community project.
*
* Redbasin OpenDocShare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package ldap;

import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import util.RegexStrUtil;
import util.LdapConstants;
import util.LdapUtil;

import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.LdapName;
import java.util.Hashtable;

import ldap.UserAccount;
import ldap.SearchUtility;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.jboss.cache.Fqn;

public class LdapApi {

    protected static final Log logger = LogFactory.getLog("ldap.LdapApi");

    // variables
    boolean debug = false; // whether to print debug messages
    public static boolean verbose = false; // whether to print the jndi/ldap trace

    /*
        public enum Action {
    NULL, ADD, DELETE, UPDATE, LIST, CHECK, VERIFY
        }
    */
    private DirContext context;
    LdapName searchBase;

    /**
     * open the directory connection.
     * @throws LdapException
     */
    public LdapApi() {
        searchBase = null;
        try {
            context = openDirectoryConnection();
        } catch (NamingException e) {
            throw new LdapException("openDirectoryConnection() NamingException" + e.getMessage(), e);
        }

        if (context == null) {
            logger.info("new LdapApi() context is null");
            throw new LdapException("new LdapApi() context is null");
        }
    }

    /**
     * creates useraccount
     * @param attributeList - attribute list
     * @param valueList - values of the attributes
     * @param action - create
     * @param login - login  for whom the above action is done
     * @param password - password for this login to authenticate 
     * @param userDN - userbaseDN
     * @throws LdapException
     */
    public String accessLdap(List attributeList, List valueList, String action, String login, String password,
            String userBaseDN) throws LdapException {

        if ((attributeList == null) || (valueList == null) || RegexStrUtil.isNull(login)
                || RegexStrUtil.isNull(password)) {
            throw new LdapException("accessLdap() params are null");
        }

        // represents the user entry in the directory 
        // (or to be added to the directory)
        UserAccount userAccount = new UserAccountImpl();
        if (userAccount != null) {
            //logger.info("userAccount = " + userAccount.toString());
            setParameters(attributeList, valueList, userAccount);
            logger.info("setParameters() completed");
            // userbasedn is null
            return executeAction(action, login, password, userAccount, userBaseDN);
        }
        return null;
    }

    /**
     * verify/update/delete useraccount
     * @param attributeList - attribute list
     * @param valueList - values of the attributes
     * @param action - delete/update/verify/
     * @param login - login  for whom the above action is done
     * @param password - password for this login to authenticate 
     * @throws LdapException
     */
    public String accessLdap(List attributeList, List valueList, String action, String login, String password)
            throws LdapException {

        if ((attributeList == null) || (valueList == null) || RegexStrUtil.isNull(login)
                || RegexStrUtil.isNull(password)) {
            throw new LdapException("accessLdap() params are null");
        }

        // represents the user entry in the directory 
        // (or to be added to the directory)
        UserAccount userAccount = new UserAccountImpl();
        if (userAccount != null) {
            //logger.info("userAccount = " + userAccount.toString());
            setParameters(attributeList, valueList, userAccount);
            logger.info("setParameters() completed");
            // userbasedn is null
            return executeAction(action, login, password, userAccount, "");
        }
        return null;
    }

    /**
     * list useraccount
     * @param attributeList - attribute list
     * @param action - delete/update/verify/
     * @param login - login  for whom the above action is done
     * @param password - password for this login to authenticate 
     * @throws LdapException
     */
    public Entry accessLdap(List attributeList, String action, String login) throws LdapException {

        if ((attributeList == null) || RegexStrUtil.isNull(login)) {
            throw new LdapException("accessLdap() params are null");
        }
        return executeAction(action, login);
    }

    /**
     * connectLdap() connects to Ldap server
     * @param attributeList - attribute list
     * @param valueList - values of the attributes
     * @param action - create/delete/update/verify/
     * @param login - login  for whom the above action is done
     * @param password - password for this login to authenticate 
     * @throws LdapException
     */
    public String connectLdap(List attributeList, List valueList, String action, String login, String password)
            throws LdapException {

        if ((attributeList == null) || (valueList == null) || RegexStrUtil.isNull(login)
                || RegexStrUtil.isNull(password)) {
            throw new LdapException("connectLdap() params are null");
        }

        // represents the user entry in the directory 
        // (or to be added to the directory)
        UserAccount userAccount = new UserAccountImpl();
        if (userAccount != null) {
            setParameters(attributeList, valueList, userAccount);
            return executeAction(action, login, password, userAccount, "");
        }
        return null;
    }

    /**
     * openDirectoryConnection() - Open the directory connection for the executeAction() method to use.
     */
    private DirContext openDirectoryConnection() throws NamingException {
        try {
            context = setupJNDIConnection(LdapConstants.ldapDirectoryUrl, LdapConstants.ldapDirectoryAdmin,
                    LdapConstants.ldapDirectoryPwd, false);

        } catch (AuthenticationException e) {
            logger.info("There was an error establishing the 'admin' connection to the directory" + e.getMessage());
            logger.info("The directory rejected the administration credentials:");
            logger.info("   user: " + LdapConstants.ldapDirectoryAdmin);
            //logger.info("   pwd:  " + LdapConstants.ldapDirectoryPwd + "\n" + e.getMessage());
            logger.info("There was an error establishing the 'admin' connection to the directory", e);
            logger.info("  Examine the stack trace below for details, including the LDAP error message"
                    + e.getMessage());
            throw e;
        }

        if (context == null) {
            logger.info("openDirectoryConnection(), context is null");
            //throw new LdapException("openDirectoryConnection(), Error: context is null");
        }
        return context;
    }

    /**
     * open the directory connection.
     * @param url
     * @param dn
     * @param password
     * @param tracing
     * @return DirContext - context
     * @throws NamingException
     */
    private DirContext setupJNDIConnection(String url, String userDN, String password, boolean tracing)
            throws NamingException {
        /*
        *  setup  environment variables to sensible default valuse
        */
        Hashtable env = new Hashtable();
        // sanity check
        if (url == null) {
            throw new LdapException("URL not specified in openContext()!");
        }

        // tracing on/off, since it can't be set once the connection is open.
        if (tracing) {
            env.put("com.sun.jndi.ldap.trace.ber", System.err); // echo trace to standard error output
        }

        //env.put("java.naming.ldap.version", "3");               // always use ldap v3 - v2 too limited
        env.put(LdapConstants.ldapVersionStr, LdapConstants.ldapVersion); // always use ldap v3 - v2 too limited
        env.put(Context.INITIAL_CONTEXT_FACTORY, LdapConstants.ldapContext); // use default jndi provider
        env.put(LdapConstants.ldapDeleteRdn, LdapConstants.ldapDeleteRdnValue); // usually what we want
        //env.put(Context.REFERRAL, "ignore");                    //could be: follow, ignore, throw
        env.put(Context.REFERRAL, LdapConstants.ldapIgnore); //could be: follow, ignore, throw
        // env.put("java.naming.ldap.derefAliases", "finding");    // could be: finding, searching, etc.
        env.put(LdapConstants.ldapFindingAliases, LdapConstants.ldapFindingStr); // could be: finding, searching, etc.

        //env.put(Context.SECURITY_AUTHENTICATION, "simple");         // 'simple' = username + password
        env.put(Context.SECURITY_AUTHENTICATION, LdapConstants.ldapSecurityAuth); // 'simple' = username + password

        env.put(Context.SECURITY_PRINCIPAL, userDN); // add the full user dn
        env.put(Context.SECURITY_CREDENTIALS, password); // stupid jndi requires us to cast this to a string-
        env.put(Context.PROVIDER_URL, url); // the ldap url to connect to; e.g. "ldap://ca.com:389"

        /*
         *  Open the actual LDAP session using the above environment variables
         */
        context = new InitialDirContext(env);
        if (context == null) {
            throw new NamingException(
                    "Internal Error with jndi connection: No Context was returned, however no exception was reported by jndi.");
        } else {
            logger.info("context is not null");
        }
        return context;
    }

    /**
     * executeAction - initiates calls to the methods to 
     *  add/update/delete/list/verify  ldap user account.
     * @param actionStr - add/delete/verify/list/update
     * @param login - login
     * @param password - password
     * @param userAccount - userAccount
     * @param addUserDN - addUserDN applicable to addAccount
     * @return status - null or statusmsg
     * @throws exception - error
     */
    public String executeAction(String actionStr, String login, String password, UserAccount userAccount,
            String addUserDN) throws LdapException {

        if (context == null) {
            try {
                context = openDirectoryConnection();
            } catch (Exception e) {
                throw new LdapException("context is null" + e.getMessage(), e);
            }
        }
        if (context == null) {
            throw new LdapException("unable to create context, context is null");
        }

        if (userAccount == null) {
            throw new LdapException("userAccount is null.");
        }

        if (actionStr == null) {
            throw new LdapException("executeAction(), ldap action is null.");
        }

        if (RegexStrUtil.isNull(login) || RegexStrUtil.isNull(password)) {
            throw new LdapException("login or password is null");
        }

        SearchUtility searcher = null;
        try {
            searcher = new SearchUtility(
                    Arrays.asList("username", "section", "division", "group", "area", "company"), false);
            if (searcher == null) {
                throw new LdapException("SearchUtility new() searcher is null");
            }
        } catch (Exception e) {
            throw new LdapException("exception in creating new SearchUtitity()" + e.getMessage(), e);
        }

        ActiveLoginImpl actionHandler = new ActiveLoginImpl();
        if (actionHandler == null) {
            throw new LdapException("actionHandler = new ActiveLoginImpl() is null.");
        }
        try {
            actionHandler.testMain();
        } catch (Exception e) {
            throw new LdapException("testMain() error = " + e.getMessage(), e);
        }

        Entry myUser = getMyUser(login, context, searcher);
        String myUserDN = null;
        if (myUser != null) {
            myUserDN = getUserDN(myUser);
            //logger.info("myUserDN = " + myUserDN);
            String myUserStr = myUser.getName().toString();
            //logger.info("myUserStr = " + myUserStr);
            try {
                // logger.info(" myUser whole = " + myUser.toString());
                logger.info(" myUser, mail = " + myUser.getValue(LdapConstants.ldapAttrMail));
                logger.info(" myUser, phone = " + myUser.getValue(LdapConstants.ldapAttrPhoneNumber));
                logger.info(" myUser, uid = " + myUser.getValue(LdapConstants.ldapAttrUid));
            } catch (Exception e) {
                throw new LdapException("error in myUser.getValue = " + e.getMessage());
            }
        } else {
            logger.info("myUserDN is null");
        }

        int action = new Integer(actionStr).intValue();
        switch (action) {
        case 0: /* NULL: */
            logger.info("NOTHING TO DO");
            break;
        case 1: /* ADD */
            try {
                actionHandler.addAccount(userAccount, context, addUserDN);
            } catch (Exception e) {
                throw new LdapException("addAccount() exception" + e.getMessage(), e);
            }
            //logger.info("ACCOUNT " + userAccount.getUserID() + " ADDED");
            logger.info("ACCOUNT ADDED");
            return "User " + userAccount.getUserID() + " added.";
        case 2: /* DELETE */
            try {
                actionHandler.deleteAccount(login, context, myUserDN);
            } catch (Exception e) {
                throw new LdapException("deleteAccount exception" + e.getMessage(), e);
            }
            logger.info("ACCOUNT " + login + " DELETED");
            break;
        case 3: /* Update */
            //logger.info("updating account" + userAccount.getUserID() );
            logger.info("updating account");
            try {
                actionHandler.updateAccount(userAccount, context, myUserDN);
            } catch (Exception e) {
                throw new LdapException("updateAccount exception" + e.getMessage(), e);
            }
            //logger.info("ACCOUNT " + userAccount.getUserID() + " UPDATED");
            logger.info("ACCOUNT UPDATED");
            break;
        //case 4: /* LIST: */
        //UserAccount account = actionHandler.getAccount(login);
        //logger.info("ACCOUNT LISTING:\n" + account.toString());
        //return account.toString();
        case 5: /* CHECK: */
            boolean isAdmin;
            try {
                isAdmin = actionHandler.isAdmin(login, context, myUserDN);
            } catch (Exception e) {
                throw new LdapException("isAdmin(login,context) exception" + e.getMessage(), e);
            }
            logger.info("ACCOUNT " + login + (isAdmin ? " IS ADMIN" : " IS NOT AN ADMIN"));
            return (isAdmin ? LdapConstants.ldapIsAdmin : LdapConstants.ldapNotAdmin);

        case 6: /* VERIFY: */
            /** login can be any attribute, (cn, email etc)
            *  so just pass that attribute from the xml
             */
            try {
                if (actionHandler.testBind(login, password, myUserDN)) {
                    logger.info("testBind ..............can verify login and password, login= " + login);
                    return LdapConstants.ldapLoginOk;
                } else {
                    //logger.info("testBind ..............cannot verify login and password " + login + " " + password);
                    logger.info("testBind ..............cannot verify login and password " + login);
                    try {
                        String myUserStr = myUser.getName().toString();
                        //logger.info("myUserStr = " + myUserStr);
                        if (searcher.userHasAttribute(myUserStr, "userPassword", password, context)) {
                            logger.info("LOGIN OK, login =" + login);
                            return LdapConstants.ldapLoginOk;
                        } else {
                            logger.info("USER EXISTS, INVALID PASSWORD, ");
                            return LdapConstants.ldapInvalidPassword;
                        }
                    } catch (NamingException e) {
                        throw new LdapException(
                                " function userHasAttribute(DN, userpassword, password, context)" + e.getMessage(),
                                e);
                    }
                }
            } catch (Exception e) {
                logger.info("testBind exception testBind .............." + e.getMessage(), e);
                throw new LdapException("testBind exception for login=" + login + e.getMessage(), e);
            }
        }
        return null;
    }

    /*
          Entry user = null;
          try {
          user = searcher.getUser(LdapConstants.ldapAttrLogin, login, context);
          } catch (NamingException e) {
     throw new LdapException("getUser NamingException" + e.getMessage(), e);
          }
        
          if (user == null) {
               logger.info("USER DOES NOT EXIST");
     return LdapConstants.ldapUserDoesNotExist;
          } else {
               String DN = user.getName().toString();
          if (DN != null) {
               logger.info("DN = " + DN);
       }
    */

    /* if (LdapUtil.isLdapEncryptionEnabled()) {
    logger.info("ldapencryption is enabled");
        try {
                  // show one way to do a logon...
                 logger.info("\nShow some methods to log in a user...");
    // if it is clear text, this is ok 
    // for encrypted ones,  we need to use the function
       Attributes newUser = new BasicAttributes();
       newUser.put(LdapConstants.ldapAttrCn, login);
       newUser.put(LdapConstants.ldapAttrUserPassword, password);
       newUser.put(LdapConstants.ldapObjectClass, "person");
                 Attributes userWithHashPass  = actionHandler.hashPasswordAttribute(newUser);
       String originalPassword = actionHandler.stringEncode((byte[])userWithHashPass.get(LdapConstants.ldapAttrUserPassword).get());
       logger.info("originalPassword stringEncoded = " + originalPassword); 
       String userPassword = user.getValue("userPassword");
       if (userPassword != null) {
          logger.info("userpassword from ldap = " + userPassword); 
       } else {
          logger.info("userpassword from ldap is null");
       }
       if (originalPassword.equals(userPassword)) {
    logger.info("originalPassword and userPassword are the same");
       } else {
    logger.info("originalPassword and userPassword are NOT the same");
       } 
       if (actionHandler.passwordVerify(userPassword, password)) {
          logger.info("passwordVerify(), matches with password=" + password);
          return LdapConstants.ldapLoginOk;
       } else {
          logger.info("passwordVerify(), does not match with password=" + password);
               return LdapConstants.ldapInvalidPassword;
       }
    } catch(Exception e){
      throw new LdapException("error in hashPasswordAttribute/passwordVerify() " + e.getMessage(), e);
    }
     } else {
    logger.info("ldapencryption is not enabled");
    try {
                if (searcher.userHasAttribute(DN, "userPassword", password, context)) {
                   logger.info("LOGIN OK, login =" + login + " password = " + password);
         return LdapConstants.ldapLoginOk;
           } else {
                   logger.info("USER EXISTS, INVALID PASSWORD, " + password);
              return LdapConstants.ldapInvalidPassword;
      }
    } catch(NamingException e) {
      throw new LdapException(" function userHasAttribute(DN, userpassword, password, context)" + e.getMessage(), e);
    }
    } */

    /**
     * Fairly self explanatory parsing of user options.  
     * See 'printHelp()' for details
     * of individual options.
     *
     * @param argv
     * @throws LdapException
     */
    public void setParameters(List attributeList, List valueList, UserAccount userAccount) throws LdapException {
        addAttributeValuePairToUserAccount(attributeList, valueList, userAccount);
    }

    /**
     * This takes an ldap attribute value pair such 
     * as 'uid=fred' or 'userPassword=secret', parses
     * it into the attribute name and the value, and then adds it 
     * to the 'userAccount' object.
     * @param key
     * @throws LdapException
     */
    private void addAttributeValuePairToUserAccount(List attributeList, List valueList, UserAccount userAccount)
            throws LdapException {

        if (valueList != null && valueList.size() > 0) {
            if (attributeList != null && attributeList.size() > 0) {
                if (valueList.size() == attributeList.size()) {
                    for (int i = 0; i < attributeList.size(); i++) {
                        //logger.info(attributeList.get(i) + "=" + valueList.get(i));
                        userAccount.put((String) attributeList.get(i), (String) valueList.get(i));
                    }
                }
            }
        }
    }

    /**
    *
    * @param structureType - can be a "group", "area", "section", "division", division
    * @return List - values for a structureType
    * @throws LdapException
    *
    */
    public List<String> getStructureValues(String structureType) throws LdapException {

        List<String> structValues = null;
        try {
            SearchUtility searcher = new SearchUtility(
                    Arrays.asList("username", "section", "division", "group", "area", "company"), false);
            if (searcher == null) {
                throw new LdapException("SearchUtility new() searcher is null");
            }

            structValues = searcher.getStructureElements(structureType, context);
            if (structValues != null) {
                for (String structValue : structValues) {
                    logger.info(structureType + "=" + structValue);
                }
            }
        } catch (Exception e) {
            throw new LdapException("new SearchUtility() exception" + e.getMessage(), e);
        }
        return structValues;
    }

    public List<String> getUserStructure(String attrType, String attrValue) throws LdapException {

        logger.info("getUserStructure entered");
        try {
            SearchUtility searcher = new SearchUtility(
                    Arrays.asList("username", "section", "division", "group", "area", "company"), false);
            //Entry user = searcher.getUser("mail", "asa@isac.gov.in");
            Entry user = searcher.getUser(attrType, attrValue, context);
            logger.info(" getUser ");
            if (user != null) {
                //logger.info("user=" + user.toString());
                String DN = user.getName().toString();
                logger.info("DN = " + DN);
                //return LdapUtil.getQNames(DN, ",ou="); 
                return LdapUtil.getQNames(DN, LdapConstants.ldapToken);
            } else {
                logger.info("user is null");
                return null;
            }
        } catch (Exception e) {
            throw new LdapException("getUserStructure() new Searcher() exception" + e.getMessage(), e);
        }
    }

    /**
    * getSearcher() returns the handle for searcher in ldap
    */
    private SearchUtility getSearcher(String searchDn) throws LdapException {

        try {
            searchBase = new LdapName(searchDn);
            SearchUtility searcher = new SearchUtility(
                    Arrays.asList("username", "section", "division", "group", "area", "company"), false);
            return searcher;
        } catch (Exception e) {
            throw new LdapException("new LdapName(searchDn) or new SearchUtility() exception" + e.getMessage(), e);
        }

        /*
                userList.add(searcher.convertUserEntriesToStrings(users, Config.USER_MAIL_ATT);
                groups = searcher.convertUserEntriesToStrings(users, Config.USER_GROUP_ATT);
                userNames = searcher.convertUserEntriesToStrings(users);
           usersList.add(userNames);
        */
    }

    /**
    * getLdapUsers() returns users based on certain criteria
    * @param searchDn - searchDn base
    * @param attrList - attrList 
    * @return List - users list 
    * @throws LdapException
    */
    public List getLdapUsers(String searchDn, String[] attrList) throws LdapException {
        try {
            SearchUtility searcher = getSearcher(searchDn);
            List<Entry> users = null;
            try {
                users = searcher.getUsers(searchBase, context);
                if (users == null) {
                    logger.info("users are null.");
                } else {
                    logger.info("users are not null.");
                }
            } catch (NamingException e) {
                throw new LdapException("getUsers(searchBase, context) exception" + e.getMessage(), e);
            }
            return getAttrUsersList(searcher, attrList, users);
        } catch (LdapException e1) {
            throw new LdapException("getSearcher(searchDn) exception " + e1.getMessage(), e1);
        }
    }

    private List getAttrUsersList(SearchUtility searcher, String[] attrList, List users) throws LdapException {
        if (users == null) {
            logger.info("users is null.");
            return null;
        }
        if (attrList == null) {
            return users;
        } else {
            int i = 0;
            try {
                List usersList = new ArrayList();
                if (usersList == null) {
                    throw new LdapException("usersList is null, cannot create ArrayList() of usersList");
                } else {

                    /**
                         * If attList is null, return userList which is ok.
                    */
                    for (i = 0; i < attrList.length; i++) {
                        List attList = searcher.convertUserEntriesToStrings(users, attrList[i]);
                        if (attList != null) {
                            for (int j = 0; j < attList.size(); j++) {
                                //if (!RegexStrUtil.isNull(attrList[i])) {
                                //logger.info(attrList[i] + ": "  + attList.get(j));
                                //}
                            }
                            usersList.add(attList);
                            logger.info("attList = " + attList.size());
                        }
                        for (int k = 0; k < usersList.size(); k++) {
                            List mylist = (List) usersList.get(k);
                            //logger.info(attrList[k] + ":" + mylist.size());
                            //logger.info(mylist.toString());
                        }
                    }
                }
                return usersList;
            } catch (Exception e) {
                throw new LdapException(
                        "ConvertUserEntriesToString(users, attrList[" + i + "]= " + attrList[i] + e.getMessage(),
                        e);
            }
        } // else 
    }

    /**
    * getLdapUsers() returns users based on certain criteria
    * @param searchDn - searchDn base
    * @param attrList - searchDn base
    * @param startChar - start character to search for Users with alphabets 
    * @param endChar - end character to search for Users with alphabets 
    * (for example (A, C) or (A,A)
    * @return List - users list 
    * @throws LdapException
    */
    public List getLdapUsers(String searchDn, String[] attrList, char startChar, char endChar)
            throws LdapException {
        try {
            SearchUtility searcher = getSearcher(searchDn);
            List<Entry> users = searcher.getUsers(searchBase, startChar, endChar, context);
            return getAttrUsersList(searcher, attrList, users);
        } catch (Exception e) {
            throw new LdapException("getUsers(searchBase, startChar, endChar, context) exception, searchDn= "
                    + searchDn + " startChar = " + startChar + " endChar= " + endChar + e.getMessage(), e);
        }
    }

    /**
    * getLdapUsers() returns users based on certain criteria
    * @param searchDn - searchDn base
    * @param attrList - searchDn base
    * @param startChar - start character to search for Users with alphabets 
    * @param endChar - end character to search for Users with alphabets 
    * @param pageSize - the number of users to return
    * @param pageNumber - the number of the page
    * (for example (A, C) or (A,A)
    * @return List - of matching, sorted users 
    * @throws LdapException
    */
    public List getLdapUsers(String searchDn, String[] attrList, char startChar, char endChar, int pageSize,
            int pageNumber) throws LdapException {

        logger.info("searchDn = " + searchDn);
        //logger.info("attrList = " + attrList);

        try {
            SearchUtility searcher = getSearcher(searchDn);
            try {
                List<Entry> users = searcher.getUsers(searchBase, startChar, endChar, pageSize, pageNumber,
                        context);
                return getAttrUsersList(searcher, attrList, users);
            } catch (NamingException e) {
                throw new LdapException(
                        "getUsers(searchBase, startChar, endChar, pageSize, pageNumber, context) exception, searchDn="
                                + searchDn + " startChar=" + startChar + " endChar=" + endChar + " pageSize="
                                + pageSize + " pageNumber=" + pageNumber + e.getMessage(),
                        e);
            }
        } catch (Exception e1) {
            throw new LdapException("getSearcher(searchDn)" + e1.getMessage(), e1);
        }
    }

    /**
    * print parameters debugging
    */
    public void printParameters() {
        /*
                logger.info("ACTION = " + action);
                if (userAccount != null) logger.info(userAccount.toString());
                if (userName != null) logger.info("USERNAME: " + userName);
                if (password != null) logger.info("PASSWORD: " + password);
                if (verbose) logger.info("VERBOSE ON");
                if (debug) logger.info("DEBUG ON");
        */
    }

    public void printHelp() {
        logger.info("LDAPLdapApi ldap.LdapApi is a simple java program to demonstrate LDAP connectivity.\n"
                + "USAGE:\n"
                + "    java ldap.LdapApi [-h|-help] [-d|-debug] [-a|add] [-d|delete] [-u|update] [-l|list] [-c|check] [-b|bind] [attribute=value] \n"
                + "       -h help message\n" + "       -x turns debugging on\n"
                + "       -z verbose debugging, including an LDAP trace\n"
                + "       -a add a user with given attributes\n"
                + "       -d delete a user with the given user name\n"
                + "       -u update a user with the given attributes\n"
                + "       -l list a user with the given user name\n"
                + "       -c check whether a user is an admin\n"
                + "       -v verify a username and password combo\n"
                + "       -n name set the name of the user being operated on\n"
                + "       -p password set the password of the user being operated on\n"
                + "       attribute=value an LDAP attribute value pair\n" + "EXAMPLES:\n"
                + "   java ldap.LdapApi -add uid=fred cn=fred sn=smith email=fred@fred.com password=secret\n"
                + "   java ldap.LdapApi -bind -n fred -p secret\n" + "   java ldap.LdapApi -list -n fred\n");
    }

    /**
    * getUser() - returns the user from the ldap directory
    * add email address to the login that is sent by the user
    * javax.naming.directory does not recognize any other attributes other
    * than email for searching for users in ldap directory
    */
    private Entry getMyUser(String login, DirContext context, SearchUtility searcher) {
        Entry user = null;
        try {
            // for isro.ldif purposes attach the email address now for searching       // as uid is not unique.
            String email = login + "@isac.gov.in";
            user = searcher.getUser(LdapConstants.ldapAttrMail, email, context);
        } catch (NamingException e) {
            throw new LdapException("getUser NamingException" + e.getMessage(), e);
        }

        if (user == null) {
            logger.info("USER DOES NOT EXIST");
            return null;
        } else {
            return user;
        }
    }

    /*
    * return the user DN from the user
    */
    private String getUserDN(Entry user) {
        String DN = user.getName().toString();
        if (DN != null) {
            logger.info("DN = " + DN);
            return DN;
        } else {
            return null;
        }
    }

    /**
     * executeAction - initiates calls to the methods to 
     *  list ldap user account.
     * @param actionStr - list the user entry or get the user entry 
     * @param login - login
     * @return Entry - user entry
     * @throws exception - error
     */
    public Entry executeAction(String actionStr, String login) {

        if (context == null) {
            try {
                context = openDirectoryConnection();
            } catch (Exception e) {
                throw new LdapException("context is null" + e.getMessage(), e);
            }
        }
        if (context == null) {
            throw new LdapException("unable to create context, context is null");
        }

        if (actionStr == null) {
            throw new LdapException("executeAction(), ldap action is null.");
        }

        if (RegexStrUtil.isNull(login)) {
            throw new LdapException("login is null");
        }

        SearchUtility searcher = null;
        try {
            searcher = new SearchUtility(
                    Arrays.asList("username", "section", "division", "group", "area", "company"), false);
            if (searcher == null) {
                throw new LdapException("SearchUtility new() searcher is null");
            }
        } catch (Exception e) {
            throw new LdapException("exception in creating new SearchUtitity()" + e.getMessage(), e);
        }

        ActiveLoginImpl actionHandler = new ActiveLoginImpl();
        if (actionHandler == null) {
            throw new LdapException("actionHandler = new ActiveLoginImpl() is null.");
        }

        Entry myUser = getMyUser(login, context, searcher);
        String myUserDN = null;
        if (myUser != null) {
            myUserDN = getUserDN(myUser);
            //logger.info("myUserDN = " + myUserDN);
            String myUserStr = myUser.getName().toString();
            //logger.info("myUserStr = " + myUserStr);
            try {
                // logger.info(" myUser whole = " + myUser.toString());
                logger.info(" myUser, mail = " + myUser.getValue(LdapConstants.ldapAttrMail));
                logger.info(" myUser, phone = " + myUser.getValue(LdapConstants.ldapAttrPhoneNumber));
                logger.info(" myUser, uid = " + myUser.getValue(LdapConstants.ldapAttrUid));
            } catch (Exception e) {
                throw new LdapException("error in myUser.getValue = " + e.getMessage());
            }
        } else {
            logger.info("myUserDN is null");
        }

        if (actionStr.equals(LdapConstants.ldapList)) {
            return myUser;
        } else {
            return null;
        }
    }
}