package ibase.servlet;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import ibase.bean.ChangePasswordBean;
import ibase.bean.DashboardBean;
import ibase.bean.EventLogInfoBean;
import ibase.bean.ExtAuthApplicationBean;
import ibase.bean.ExtAuthRespBean;
import ibase.bean.TabManagerBean;
import ibase.bean.UserSessionInfoBean;
import ibase.ejb.CommonDBAccessEJB;
import ibase.ejb.CommonDBAccessRemote;
import ibase.ejb.E12SMSComp;
import ibase.ejb.E12SMSComp.SMSType;
import ibase.hibernate.dao.ObjUserPrefDao;
import ibase.system.config.AppConnectParm;
import ibase.utility.ApplicationTO;
import ibase.utility.BaseException;
import ibase.utility.BaseLogger;
import ibase.utility.CommonConstants;
import ibase.utility.CryptographyUtil;
import ibase.utility.E12GenericUtility;
import ibase.utility.InternalLogger;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.DBAccessEJB;
import ibase.webitm.ejb.SocialEntEJB;
import ibase.webitm.ejb.ITMDBAccessEJB;

public class AuthenticateServlet extends HttpServlet
{
	ServletContext servletContext = null;
	ServletConfig servletConfig = null;
	//Added by Sadique S [To hide/encrypt the OTP at client side] on 26-06-19
	String key = "aesEncryptionKey";
	String initVector = "encryptionIntVec";
	//Commented global userinfo object by Pankaj T on 18-01-18 for resolving issue of display data of another user
	//UserInfoBean userInfo = null;
	//Changed by Sandesh on 18/11/2016 [For Authentication API] Start
	ExtAuthApplicationBean applicationBean = null;
	//Changed by Sandesh on 18/11/2016 [For Authentication API] End

	public void init(ServletConfig servletConfig) throws ServletException
	{
		this.servletConfig = servletConfig;
		this.servletContext = servletConfig.getServletContext();
	}
	protected void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException
    {
		//Added by trushant for session timeout issue in native application Start
		request.setCharacterEncoding( CommonConstants.ENCODING );
		response.setContentType("application/x-www-form-urlencoded; charset="+CommonConstants.ENCODING);
		
		BaseLogger.log("2",null,null,"AuthenticateServlet inside doGet session 89");
		response.setHeader("Access-Control-Allow-Origin","*");
		response.setHeader("Access-Control-Allow-Headers","content-type,authorization");
		response.setHeader("Access-Control-Allow-Credentials","true");
		response.setHeader("Set-Cookie", "JSESSIONID="+request.getSession().getId()+"; HttpOnly; SameSite=none; secure");
		request.getSession().setAttribute("NameInSession", "VISION");
		BaseLogger.log("2",null,null,"95 inside doGet session id :"+request.getSession().getId());
		//Added by trushant for session timeout issue in native application Start
		doPost( request, response );
    }

	public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException
	{
        //Commented global userinfo object by Pankaj T on 18-01-18 for resolving issue of display data of another user
		//userInfo = null;
		//Added By Prajyot on 17MAY2013 [ As per Danish Sir for Russian Server Issue]
		request.setCharacterEncoding( CommonConstants.ENCODING );
		response.setContentType("application/x-www-form-urlencoded; charset="+CommonConstants.ENCODING);
		String reqHeader = request.getHeader("User-Agent") ;
		BaseLogger.log("2",null,null,"Pankaj Auth Request Header ["+reqHeader+"]");
		//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] create String variable targetCustomer
		//String targetCustomer = "";

		//Gulzar on 30/01/15 to invalidate the session on exception;
		boolean isError = false;
		String action = request.getParameter("action"); //$NON-NLS-1$
		try
		{
			setLogger();
			//Changed by Rupali to check the login mode is MOBILE for HTML
			String loginMode = request.getParameter("loginMode"); //$NON-NLS-1$
			//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]
			String loginClient = request.getParameter("loginClient"); //$NON-NLS-1$
			//Added by Pankaj T on 19-12-17 [for multitenancy Added new method for getting transDB when authenticate] - Start
			String code = request.getParameter( "USER" );
			getCommonDBAccess().getTransDB(code);
			//Added by Pankaj T on 19-12-17 [for multitenancy Added new method for getting transDB when authenticate] - End
			//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] getting customer Input value from properties table Start.
			//targetCustomer = getCommonDBAccess().getProperties("TARGET_CUSTOMER");
			//Added By Mahesh Patidar on 06-SEP-13 [to get value of caller page used for redirect if login failed]
			String callerPage =  request.getParameter("callerPage"); //$NON-NLS-1$

			//Changed by Sandesh on 18/11/2016 [For Authentication API] Start
			String isAUTHAPI =  E12GenericUtility.checkNull(request.getParameter("ISAUTHAPI"));
			String appID = E12GenericUtility.checkNull(request.getParameter("APPID"));
			String appUrl = appID.length() > 0 ? "/ibase/login/ExtAuth.jsp?appId="+appID  : "/ibase/login/ExtAuth.jsp";
			String href = isAUTHAPI.equalsIgnoreCase("true") ? appUrl : "/ibase/jsp/login.html" ;
			//Changed by Sandesh on 18/11/2016 [For Authentication API] End

			if ( "UPDATE_GRACE_COUNT".equals( action ) ) //$NON-NLS-1$
			{
				//Changed by Gulzar on 03/DEC/13 - to solve the link issue : START
				String referer = request.getParameter("REFERER"); //$NON-NLS-1$

				if("null".equalsIgnoreCase(referer) || referer == null || referer.trim().length() == 0 )
				{
					referer ="/jsp/Welcome.jsp";
				}

				BaseLogger.log("3",null,null,"referer[UPDATE_GRACE_COUNT] =["+referer+"]");

				updateGraceCount( request.getParameter( "USER" ) ); //$NON-NLS-1$
				//RequestDispatcher reqDis  = request.getRequestDispatcher( "/jsp/Welcome.jsp" ); //$NON-NLS-1$
				request.getSession().setAttribute("REFERER", referer);
				RequestDispatcher reqDis  = request.getRequestDispatcher( "/jsp/DirectAccess.jsp" ); //$NON-NLS-1$

				//Changed by Gulzar on 03/DEC/13 - to solve the link issue : END

				reqDis.forward( request, response );
			}
			//Changed by Rupali Hande on 08-11-2008 [to update the logout time in logintrace table].Start
			else if("LOGOUT".equals( action )){ //$NON-NLS-1$
				//Changed by Rakesh  on 23-10-10 [MO01SUN005 to redirect the user to Login.html on Logout from Blackbery Workflow application]
				String applnContext = request.getParameter("APPL_CXT"); //$NON-NLS-1$
				BaseLogger.log("3",null,null,"APPLICATION Context"+applnContext); //$NON-NLS-1$
				//Changed by Pankaj T. on 02-12-2021 [Removed sensitive request parameter USERID & SESSIONID for vulnerability]
				//Revert code for issue of userinfo getting null in authenticateservlet logout action
				String sessionId = request.getParameter("SESSIONID"); //$NON-NLS-1$
				String userId = request.getParameter("USERID"); //$NON-NLS-1$
				//ibase.utility.UserInfoBean userInfo = ( ibase.utility.UserInfoBean )request.getSession().getAttribute( "USER_INFO" );
				//String userId = userInfo.getLoginCode();
				//String sessionId = request.getSession().getId();
				//BaseLogger.log("9",null,null,"LOGOUT ACTION :-- [session Id ==("+sessionId+") and userId ("+userId+")");
				// Changed by Mukesh on  22-05-09 [ SY89BAS026-to remove the users who have logged out] Start
//				UserSessionInfoBean sib = new UserSessionInfoBean();
//				HashMap applLevUserInfo =null;
				//Commented By Mahesh Patidar on 06/MAR/13[WI2LSUN001 || To remove userSession map refereces]
//				HashMap usersSession= null;
//				ibase.utility.UserInfoBean userInfo = (ibase.utility.UserInfoBean )request.getSession().getAttribute("USER_INFO"); //$NON-NLS-1$
//				if(this.servletContext != null)
//				{
//
//					if ( servletContext.getAttribute("applLevUserInfo") != null) //$NON-NLS-1$
//					{
//						applLevUserInfo = (HashMap)servletContext.getAttribute("applLevUserInfo");	 //$NON-NLS-1$
//						applLevUserInfo.remove(userId+":"+sessionId); //$NON-NLS-1$
//
//					}
					//Changed By Mahesh Patidar on 07/MAR/13[WI2LSUN001 || To remove userSession map refereces]
//					if ( servletContext.getAttribute("usersSession") != null) //$NON-NLS-1$
//					{
//						usersSession = (HashMap)servletContext.getAttribute("usersSession"); //$NON-NLS-1$
//						usersSession.remove(sessionId);
//
//					}
					//Ended By Mahesh Patidar
//				}// Changed by Mukesh on 22-05-09 [  SY89BAS026 -to remove the users who have logged out]End

				logout(userId, sessionId);
				//Request ID : W15BMIT003 - Set Current Geo Position in Login trace.
				String currentGeoPos = request.getParameter("CURRENT_GEO_POS");
				String dataMode = request.getParameter("DATA_MODE");
				BaseLogger.log("3",null,null,"@LOGOUT CURRENT_GEO_POS["+ currentGeoPos +"] dataMode["+dataMode+"]");
				// Changed and Added by Pankaj R on 20-JAN-18
				getCommonDBAccess().updateCurrentGeoPos(userId, sessionId, currentGeoPos, dataMode, "");

                //Changed by Rakesh on 23-10-10[MO01SUN005 to redirect the user to Login.html on Logout from Blackbery Workflow application]Starts
                if("ME".equals(applnContext)) //$NON-NLS-1$
                {
                    response.sendRedirect("/ibase/ME/Login.html"); //$NON-NLS-1$
                }
                else
                {
                    //Changes by Raju K. On 3APR14[To fix issue on Logout - In IE browsers]
                    //String responseString = "<HTML><HEAD><SCRIPT language=JAVASCRIPT>function closeW() {window.opener = self;window.close();} </SCRIPT></HEAD><BODY onload=closeW();></BODY></HTML>"; //$NON-NLS-1$
                    String responseString = "<HTML><HEAD><SCRIPT language=JAVASCRIPT>function closeW() {window.opener = self;} </SCRIPT></HEAD><BODY onload=closeW();></BODY></HTML>"; //$NON-NLS-1$
                    //Added By Mahesh Patidar on 27/JUN/13 [ to resolved page redirection issue]
                    response.setHeader ("refresh", "1; url = /ibase/jsp/logout.jsp");
                    response.setBufferSize(responseString.length());

                    //Added by Dnyaneshwar Chavan on 24-OCT-13 [CO3ASUN005] [ Resolved the issue of when response in Russian language or etc.  ] START
                    //response.setContentType("text/html"); //$NON-NLS-1$
                    response.setContentType( "text/html; charset="+CommonConstants.ENCODING );
                    //Added by Dnyaneshwar Chavan on 24-OCT-13 [CO3ASUN005] [ Resolved the issue of when response in Russian language or etc.  ] END

                    OutputStream outputStream = response.getOutputStream();
                    outputStream.write(responseString.getBytes());
                    outputStream.flush();
                    outputStream.close();
                }
                //Changed by Rakesh on 23-10-10[MO01SUN005 to redirect the user to Login.html on Logout from Blackbery Workflow application]End
				//Changed by Rupali Hande on 08-11-2008 [to update the logout time in logintrace table].End
			}
			//Change by Nilesh on 11/11/10 [WI01SUN016][For Mobile Login from GWT component]Start
			else if("MELOGIN".equals(action)) //$NON-NLS-1$
			{
				//Added by Harshada on 26th Oct 2012 [Creating user connections on login]
				String conApplNm = request.getParameter("conApplNm");
				//Added by Prajyot On 16-JAN-2013 [To assign SFA as applName in case of null]
				conApplNm = ( conApplNm != null ) ? conApplNm : "SFA" ;
				BaseLogger.log("3",null,null,"application name for explorer " + conApplNm);
				//Added by Sandeep S. on 24/11/16 [[S16HBAS012]  Check for latest apk version ] start
				String currentApkVersion = request.getParameter("CURRENTAPKVERSION");
				String batteryStatus = request.getParameter("BATTERY_STATUS");
				BaseLogger.log("3",null,null,"BATTERY_STATUS ::  "+batteryStatus);
				String upgradeMessage = "";
				String recommendedMessage = "";
				BaseLogger.log("3",null,null,"currentApkVersion " + currentApkVersion);
				boolean checkVersion = true;
				boolean checkRecommendedVersion = true;
				if( currentApkVersion != null && !"".equalsIgnoreCase(currentApkVersion) )
				{
					checkVersion = checkVersionComaptibility(currentApkVersion);
					if( !checkVersion )
					{
						//changed by vishal pathare on 7.8.18 as suggested by KB sir
						//upgradeMessage = "This version is no more compatible for this server, please upgrade from Google PlayStore";
						upgradeMessage = "This version of the app is out dated. Please update the version from Play Store/App Store.";
					}

					if( checkVersion )
					{
						checkRecommendedVersion = checkRecommendedVersionComaptibility(currentApkVersion);
						if( !checkRecommendedVersion )
						{
							//Change by Sandeep S. on 05/12/16
							//recommendedMessage = "The recommended apk version for this server is " + CommonConstants.APK_RECOMMENDED_VERSION;
							recommendedMessage = "There is new version of APK ("+CommonConstants.APK_RECOMMENDED_VERSION+") available.<br>It is recommended to upgrade.";
						}
					}
				}
				//Added by Sandeep S. on 24/11/16 [[S16HBAS012]  Check for latest apk version ] end
				//Change by Nilesh on 05-May-2011[][send XML with userInfo data after authenticate]Start
				StringBuffer responseStrBuf = new StringBuffer();

				//changed by Gulzar on 29/01/15 to check for max allowed session for login user. START
				//If it exceeds the defined maximum allow then will return with error message
				String loginUserID = request.getParameter("USER");
				boolean isAllowExceeded = isAllowSessionsExceeded(loginUserID);
				BaseLogger.log("3",null,null,"AuthenticateServlet >> isAllowExceeded[MELOGIN] =["+isAllowExceeded+"]");
				BaseLogger.log("3",null,null,"Inside MELogin action checkVersion " + checkVersion);
				if( checkVersion )
				{
					if(isAllowExceeded)
					{
						String msgStr = Messages.getString("AuthenticateServlet_maxSessionAllowed",getUserLangAndCountry(loginUserID) );
						responseStrBuf.append( "<Root>" );
						responseStrBuf.append( "<Errors>" );
						responseStrBuf.append( "<error id= 'MAXSESS' type ='E' column_name='' >" );
						responseStrBuf.append( "<message><![CDATA[" ).append( "Invalid login" ).append( "]]></message>" );
						responseStrBuf.append( "<description><![CDATA[" ).append( msgStr ).append( "]]></description>" );
						//Change by shrutika on 28-03-20 [Start] for description is display only with 'E'
						//responseStrBuf.append( "<description><![CDATA[" ).append( "E" ).append( "]]></description>" );
						responseStrBuf.append( "<trace><![CDATA[" ).append( "Invalid login" ).append( "]]></trace>" );
						//Change by shrutika on 28-03-20 [Start] for max_session_allwd configuration not working in case of mobile for relogin screen.
						responseStrBuf.append( "</error>" );
						responseStrBuf.append( "</Errors>" );
						//responseStrBuf.append( "</error>" );
						responseStrBuf.append( "</Root>" );
						BaseLogger.log("3",null,null, "responseStrBuf:["+responseStrBuf.toString()+"]" );

						OutputStream outputStream = response.getOutputStream();
						outputStream.write( responseStrBuf.toString().getBytes() );
						outputStream.flush();
						outputStream.close();
					}
					else
					{
						//changed by Gulzar on 29/01/15 to check for max allowed session for login user. END
						String status = authenticate( request );
						BaseLogger.log("3",null,null,"authentication status:["+status+"]");
						//Commented global userinfo object by Pankaj T on 18-01-18 for resolving issue of display data of another user
						ibase.utility.UserInfoBean userInfo = (ibase.utility.UserInfoBean)request.getSession().getAttribute("USER_INFO"); //$NON-NLS-1$
						//userInfo = (ibase.utility.UserInfoBean)request.getSession().getAttribute("USER_INFO");
						//Added by Sandeep S. on 01-Feb-18 [To check session exist or not for same user in Mobile apk] Start
						boolean isSessionExist = isSessionExistInMobile(request, loginUserID);
						E12GenericUtility genericUtility = new E12GenericUtility();
						if( "true".equals( status ) ) //$NON-NLS-1$
						{
							//getMenuTree( userInfo.getLoginCode(), userInfo.getProfileId(), "0" ); //$NON-NLS-1$
							
							// Added by jay - To call getSocialOpt()- Start
							SocialEntEJB socialEntObj = new SocialEntEJB();
							String socialOptValue = E12GenericUtility.checkNull(userInfo.getEnterprise());
							String socialOpt = socialEntObj.getSocialOpt(socialOptValue);
							BaseLogger.log("3",null,null,"social opt:["+socialOpt+"]");
							// Added by jay - To call getSocialOpt()- End

							responseStrBuf.append( "<Root>" ); //$NON-NLS-1$
							responseStrBuf.append( "<status><![CDATA[" ).append( status ).append( "]]></status>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<userID><![CDATA[" ).append( userInfo.getLoginCode() ).append( "]]></userID>" ); //$NON-NLS-1$ //$NON-NLS-2$
							// Added by Sandeshs 09-Feb-2016 [Req:S15JBAS002 Social Post] START
							responseStrBuf.append( "<userName><![CDATA[" ).append( userInfo.getUserName() ).append( "]]></userName>" );
							responseStrBuf.append( "<isPasswordStore><![CDATA[" ).append( userInfo.getIsPasswordStore() ).append( "]]></isPasswordStore>" );
							// Added by Sandeshs 09-Feb-2016 [Req:S15JBAS002 Social Post] END
							responseStrBuf.append( "<profileID><![CDATA[" ).append( userInfo.getProfileId() ).append( "]]></profileID>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<applnName><![CDATA[" ).append( conApplNm ).append( "]]></applnName>" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							responseStrBuf.append( "<empDesignation><![CDATA[" ).append( userInfo.getDesignation() ).append( "]]></empDesignation>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<empDivision><![CDATA[" ).append( userInfo.getDivision() ).append( "]]></empDivision>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<empHeadQuat><![CDATA[" ).append( userInfo.getStanCode() ).append( "]]></empHeadQuat>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<empDOJ><![CDATA[" ).append( userInfo.getDateJoin() ).append( "]]></empDOJ>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<dispDate><![CDATA[" ).append( genericUtility.getDispDateFormat() ).append( "]]></dispDate>" ); //$NON-NLS-1$ //$NON-NLS-2$

							//Added by Harshada on 10 Dec 2012 [create user connections on login]START
							responseStrBuf.append( "<userLevel><![CDATA[" ).append( userInfo.getUserLevel() ).append( "]]></userLevel>" ); //$NON-NLS-1$ //$NON-NLS-2$
							//Added by Harshada on 10 Dec 2012 [create user connections on login]END

							//Added by Harshada on 6 MAR 2013 [Get all user information on authentication]START
							responseStrBuf.append( "<deptCode><![CDATA[" ).append( userInfo.getDeptCode() ).append( "]]></deptCode>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<siteCode><![CDATA[" ).append( userInfo.getSiteCode() ).append( "]]></siteCode>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<siteDescr><![CDATA[" ).append( userInfo.getSiteDescr() ).append( "]]></siteDescr>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<entityCode><![CDATA[" ).append( userInfo.getEntityCode() ).append( "]]></entityCode>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<itemSer><![CDATA[" ).append( userInfo.getItemSer() ).append( "]]></itemSer>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<deptDescr><![CDATA[" ).append( userInfo.getDeptDescr() ).append( "]]></deptDescr>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<emailIdOff><![CDATA[" ).append( userInfo.getEmailIdOff() ).append( "]]></emailIdOff>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<empCode><![CDATA[" ).append( userInfo.getEmpCode() ).append( "]]></empCode>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<empName><![CDATA[" ).append( userInfo.getEmpName() ).append( "]]></empName>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<reportTo><![CDATA[" ).append( userInfo.getReportTo() ).append( "]]></reportTo>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<stanCode><![CDATA[" ).append( userInfo.getStanCode() ).append( "]]></stanCode>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<userCountry><![CDATA[" ).append( userInfo.getUserCountry() ).append( "]]></userCountry>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<userLanguage><![CDATA[" ).append( userInfo.getUserLanguage() ).append( "]]></userLanguage>" ); //$NON-NLS-1$ //$NON-NLS-2$
							//Added by Harshada on 6 MAR 2013 [Get all user information on authentication]END
							//Added by Savita Yadav on 8-04-2015 [for password length]-Start
							responseStrBuf.append( "<minPwdLen><![CDATA[" ).append( getCommonDBAccess().getMinPwdLength(userInfo.getTransDB())).append( "]]></minPwdLen>" ); //$NON-NLS-1$ //$NON-NLS-2$
							//Added by Savita Yadav on 8-04-2015 [for password length]-End
							responseStrBuf.append( "<applDateTimeFromat><![CDATA[" ).append( genericUtility.getApplDateTimeFormat() ).append( "]]></applDateTimeFromat>" ); //Added by Dnyaneshwar Chavan on 22-Jun-15 [ Get display date and time format. ]
							//Added by Dnyaneshwar Chavan on 30-Jul-15 [ Implement Geo fencing functionality  ] Start
							responseStrBuf.append( "<geoFenceEnabled><![CDATA[" ).append( userInfo.getUserGeoFence() ).append( "]]></geoFenceEnabled>" );
							responseStrBuf.append( "<geoFenceAccuracy><![CDATA[" ).append( CommonConstants.GEO_FENCE_ACCURACY ).append( "]]></geoFenceAccuracy>" );
							responseStrBuf.append( "<geoFenceRadius><![CDATA[" ).append( CommonConstants.GEO_FENCE_RADIUS ).append( "]]></geoFenceRadius>" );
							//Added by Dnyaneshwar Chavan on 30-Jul-15 [ Implement Geo fencing functionality  ] End
							// Added by Sandeshs 21-Jun-2016 [Req:W15BSUN011] START
							responseStrBuf.append( "<defaultMenu><![CDATA[" ).append( userInfo.getDefaultMenu() ).append( "]]></defaultMenu>" );
							// Added by Sandeshs 21-Jun-2016 [Req:W15BSUN011] END
							//Added By Suraj on 20-March-2017 [To configure slide menu panel footer options]Start
							responseStrBuf.append( "<features><![CDATA[" ).append( userInfo.getFeatures() ).append( "]]></features>" );
							//Added By Suraj on 20-March-2017 [To configure slide menu panel footer options]End
							//Addded By sanket J on 01-Aug-2017 [to get userType on login]-[Start]
							responseStrBuf.append( "<userType><![CDATA[" ).append( userInfo.getUserType() ).append( "]]></userType>" ); //$NON-NLS-1$ //$NON-NLS-2$
							//Addded By sanket J on 01-Aug-2017 [to get userType on login]-[End]
							//Added by Sagar B on[12/Jan/17]START
							responseStrBuf.append( "<geoPosOption><![CDATA[" ).append( userInfo.getGeoPosOption() ).append( "]]></geoPosOption>" ); //$NON-NLS-1$ //$NON-NLS-2$
							//Added by Sagar B. to set network configuration[07-Feb-19]START
							responseStrBuf.append( "<networkOption><![CDATA[" ).append( userInfo.getUserNetworkOption() ).append( "]]></networkOption>" ); //$NON-NLS-1$ //$NON-NLS-2$
							//Added by Sagar B. to set network configuration[07-Feb-19]END
							//Added by Sagar B. to set offline edit/delete configuration enterprise-wise[13-Mar-19]START
							responseStrBuf.append( "<isAllowOfflineEdit><![CDATA[" ).append( userInfo.getIsAllowOfflineEdit() ).append( "]]></isAllowOfflineEdit>" ); //$NON-NLS-1$ //$NON-NLS-2$
							responseStrBuf.append( "<isAllowOfflineDelete><![CDATA[" ).append( userInfo.getIsAllowOfflineDelete() ).append( "]]></isAllowOfflineDelete>" ); //$NON-NLS-1$ //$NON-NLS-2$
							//Added by Sagar B. to set offline edit/delete configuration enterprise-wise[13-Mar-19]END
							//added by vishal pathare on 13.4.18 for[site wise enterprise image related changes]
							responseStrBuf.append( "<enterprise><![CDATA[" ).append( userInfo.getEnterprise()).append( "]]></enterprise>" );
							//Added by Pankaj T. on 16-11-18 for console configuration if 1 then print console only
							responseStrBuf.append( "<clientDebugLevel><![CDATA[" ).append( CommonConstants.CLIENT_DEBUG_LEVEL).append( "]]></clientDebugLevel>" );
							//Added By Pankaj T. on 18-11--2020 for removing weak account lock vulnerability - if user wrongly enter password more than 5 times then lock the account and send new password on email/mobile and unlock account using new password
							responseStrBuf.append( "<wrongLoginCount><![CDATA[" ).append( CommonConstants.WRONG_LOGIN_COUNT).append( "]]></wrongLoginCount>" );
							//added by Pratheek on 05-02-19[ to pass the fin_entity and facility_code value on login in mobile reports]-Start
							responseStrBuf.append( "<fin_entity><![CDATA[" ).append( userInfo.getFin_entity()).append( "]]></fin_entity>" );
							responseStrBuf.append( "<facility_code><![CDATA[" ).append( userInfo.getFacility_code()).append( "]]></facility_code>" );
							//added by Pratheek on 05-02-19[ to pass the fin_entity and facility_code value on login in mobile reports]-End
							//responseStrBuf.append( "<geoFenceOption><![CDATA[" ).append( userInfo.getGeoFenceOption() ).append( "]]></geoFenceOption>" ); //$NON-NLS-1$ //$NON-NLS-2$
							//Added by Sagar B on[12/Jan/17]END
							//Added by Pankaj R on 25-FEB-19 to pass AUTO_SYNC data from ibase.xml[START]
							responseStrBuf.append( "<autoSync><![CDATA[" ).append( CommonConstants.AUTO_SYNC).append( "]]></autoSync>" );
							//Added by Pankaj R on 25-FEB-19 to pass AUTO_SYNC data from ibase.xml[END]
							//Added by Sainath T. on 11-JUN-19 [For Cross site Scripting Filter]- Start
							responseStrBuf.append( "<xssFilter> <![CDATA[").append( CommonConstants.XSS_FILTER).append( "]]></xssFilter>");
							//Added by Sainath T. on 11-JUN-19 [For Cross site Scripting Filter]- Start
							
							//Added by jay to append social_opt  - Start
							responseStrBuf.append( "<social_opt> <![CDATA[").append( socialOpt ).append( "]]></social_opt>");
							//Added by jay to append social_opt  - End

							if( !checkRecommendedVersion )
							{
								responseStrBuf.append( "<recommendedMessage><![CDATA[" ).append( recommendedMessage ).append( "]]></recommendedMessage>" );
							}
							//Added by Sandeep S. on 21-07-17 [To implement delete cache in mobile and browser] Start
							responseStrBuf.append( "<buildNo><![CDATA[" ).append( CommonConstants.BUILD_NO ).append( "]]></buildNo>" );
							responseStrBuf.append( "<pageSize><![CDATA[" ).append( CommonConstants.PAGE_SIZE ).append( "]]></pageSize>" ); //Added by Bhupendra on 06-08-18 for Pagination Implementation.
							//Added by Sandeep S. on 21-07-17 [To implement delete cache in mobile and browser] End
							if( isSessionExist )
							{
								String msgStr = "There is another session is running with this User ID. Terminate the running session?";
								String sessionIdToRemove = null;
								sessionIdToRemove = (String)request.getSession().getAttribute("mobileSessionIdToRemove");
								responseStrBuf.append( "<Message id= 'SESSEXIST' type ='W' column_name='' >" );
								responseStrBuf.append( "<message><![CDATA[" ).append( "Session Exist : " ).append( "]]></message>" );
								responseStrBuf.append( "<description><![CDATA[" ).append( msgStr ).append( "]]></description>" );
								responseStrBuf.append( "<trace><![CDATA[" ).append( msgStr ).append( "]]></trace>" );
								responseStrBuf.append( "</Message>" );
								responseStrBuf.append( "<mobileSessionIdToRemove><![CDATA[" ).append( sessionIdToRemove ).append( "]]></mobileSessionIdToRemove>" );
							}
							//Added by Sandeep S. on 01-Feb-18 [To check session exist or not for same user in Mobile apk] End
							responseStrBuf.append( "</Root>" ); //$NON-NLS-1$
							BaseLogger.log("3",null,null, "responseStrBuf:["+responseStrBuf+"]" );

							//Added by Pravin K on 12-JAN-19 [Add user in system_support group if not present] START
							if(userInfo != null)
							{
								SocialEntEJB socialEntEJB = new SocialEntEJB();
								BaseLogger.log("3",null,null,"Inside MELogin action response str ==>  userInfo.getLoginCode() : "+userInfo.getLoginCode());
								socialEntEJB.createSystemSupportGroup(userInfo, userInfo.getLoginCode()  );
							}
							//Added by Pravin K on 12-JAN-19 [Add user in system_support group if not present] END
						}
						else
						{
							responseStrBuf.append( status );
						}
						OutputStream outputStream = response.getOutputStream();
						//outputStream.write(authenticate(request).getBytes());
						outputStream.write( responseStrBuf.toString().getBytes() );
						outputStream.flush();
						outputStream.close();

						//Added by Prajyot on 15MAR13[ Null check for userInfo ]
						if( userInfo != null )
						{
							//Added by Dnyaneshwar chavan 06-Feb-2013 [ Get "RIA_CACHE_STATUS" value from DB & pass this value in 'getMenuTree' method ] Start
							String userCode = getDecodedStr( new String( request.getParameter( "USER" ) ) );
							String columnName = " RIA_CACHE_STATUS ";
							String tableName = " USERS ";

							// Change by Abhishek on 13.03.2016 [Req Id:S15LBAS004 Authentication changes] START
							                                       // passing userCode from UserInfoBean.
							String condition = " WHERE CODE = '" + userInfo.getLoginCode() + "' ";  /*userCode.trim()*/
							// Change by Abhishek on 13.03.2016 [Req Id:S15LBAS004 Authentication changes] END
							//Added by Pankaj T on 12-01-18 [changes for multitenancy]
							String riaChacheStatus = getCommonDBAccess().getDBColumnValue( tableName.trim(), columnName.trim(), condition )  ;
							riaChacheStatus = (riaChacheStatus == null || riaChacheStatus.equalsIgnoreCase("null") ) ? "0" : riaChacheStatus;
							//getMenuTree(userInfo.getLoginCode(), userInfo.getProfileId(),"0",conApplNm );
							//Commented and chnaged by Gulzar on 10/10/13 to pass userInfo for multidb connection: START
							//getMenuTree( userInfo.getLoginCode(), userInfo.getProfileId(), riaChacheStatus, conApplNm, true );
							getMenuTree( userInfo.getLoginCode(), userInfo.getProfileId(), riaChacheStatus, conApplNm, true, userInfo );
							//Commented and chnaged by Gulzar on 10/10/13 to pass userInfo for multidb connection: END

							//End by Harshada on 26th Oct 2012 [Creating user connections on login]
							//Added by Dnyaneshwar chavan 06-Feb-2013 End
						}
						//Added by Prajyot on 15MAR13[ Null check for userInfo ]

						//Change by Nilesh on 05-May-2011[][send XML with userInfo data after authenticate]End
					}
				}
				//Added by Sandeep S. on 24/11/16 [[S16HBAS012]  Check for latest apk version ] start
				else
				{
					responseStrBuf.append( "<Root>" );
					responseStrBuf.append( "<upgradeMessage><![CDATA[" ).append(upgradeMessage).append("]]></upgradeMessage>");
					responseStrBuf.append( "</Root>" );
					BaseLogger.log("3",null,null,"Inside MELogin action response str ==> "+responseStrBuf.toString());
					OutputStream outputStream = response.getOutputStream();
					outputStream.write( responseStrBuf.toString().getBytes() );
					outputStream.flush();
					outputStream.close();
				}
				//Added by Sandeep S. on 24/11/16 [[S16HBAS012]  Check for latest apk version ] end
			}
			//Change by Nilesh on 11/11/10 [WI01SUN016][For Mobile Login from GWT component]End
			//Change by Nilesh on 02-Feb-11 [SY90SUN016][To retrive password] Start
			//Added by Sadique S [To hide/encrypt the OTP at client side] on 26-06-19 START
			else if( "OtpVerification".equals( action ) ) //$NON-NLS-1$
			{
				String responseStr = "";
				response.setContentType("text/html");
				String userName = request.getParameter("userName");
				String encryptGenOtp = request.getParameter("encrptC");
				String userOtp = request.getParameter("verifyCode");
				String mac=request.getParameter("MAC_ADDRESS");
				String decryptGenotp ="";
				PrintWriter out=response.getWriter();
				BaseLogger.log("3",null,null,"OtpVerification mac = "+mac+"] and userOtp = ["+userOtp+"] and encryptOtp = ["+encryptGenOtp+"]");
				if(encryptGenOtp!=null)
				{
					decryptGenotp =decrypt(encryptGenOtp);
				}
				else
				{
					out.println("<script type=\"text/javascript\">");
					out.println("alert('Invalid verification code');");
					out.println("location='jsp/ForgotPassword.jsp';");
					out.println("</script>");
				}
				if(!userOtp.equalsIgnoreCase(decryptGenotp))
				{
					out.println("<script type=\"text/javascript\">");
					out.println("alert('Invalid verification code');");
					out.println("location='jsp/ForgotPassword.jsp';");
					out.println("</script>");
				}
				else
				{
					BaseLogger.log("3",null,null,"userName = ["+userName+"] and mac = ["+mac+"]");
					request.setAttribute("USERNAME", userName);
					request.setAttribute("DEVICEID", mac);
					request.getRequestDispatcher("jsp/VerifyUserRedirect.jsp").forward(request, response); //$NON-NLS-1$
					responseStr = "SUCCESS";
				}
			}
			//Added by Sadique S [To hide/encrypt the OTP at client side] on 26-06-19 END
			else if( "FORGOTPASSWORD".equals( action ) ) //$NON-NLS-1$
			{
				String userName = request.getParameter("USER"); //$NON-NLS-1$
				
				// Changed by Abhishek T on 09-Oct-2019 [USER value can be email id, mobile etc.] START
				UserInfoBean basicUserInfo = getCommonDBAccess().getBasicUserInfo(userName);
				userName = basicUserInfo.getLoginCode();
				basicUserInfo = null;
				// Changed by Abhishek T on 09-Oct-2019 [USER value can be email id, mobile etc.] END
				
				//Added by Sagar B. for forgot password impl in APK[16/11/17]START
				String editor = request.getParameter("EDITOR"); //Added by Sagar B. on 2/11/17
				editor = E12GenericUtility.checkNull(editor);
				//Added by Sagar B. for forgot password impl in APK[16/11/17]END
				//Changed by Nilesh on 29-Mar-2011 [SY01SUN049][To verify user before chg password]
				//String clientIP = request.getRemoteAddr();
				String responseStr = ""; //Gulzar on 04/03/14 - changed from null to "" to avoide null pointer exception.
				//Changed By Yogesh on 06/05/11 [SY1BSUN004 |Authentication happen from users table ]Start
				String empStatus = getCommonDBAccess().checkEmpStatus(userName);
				//if( "S".equalsIgnoreCase(getCommonDBAccess().checkEmpStatus(userName)))
				if( "".equals(empStatus) || "A".equalsIgnoreCase(empStatus) ) //$NON-NLS-1$ //$NON-NLS-2$
				{
					//Changed by Nilesh on 29-Mar-2011 [SY01SUN049][To verify user before chg password]Start
					//secureAccount(userName, "0");
					//getCommonDBAccess().updatePasswordChgLog( userName, clientIP, "Browser");
					//responseStr = "<HTML><HEAD><SCRIPT language=JAVASCRIPT>alert('Your new password has been sent to your e-mail id');window.location.href = '/ibase/jsp/login.html'</SCRIPT></HEAD></HTML>";
					//Yogesh on 14-06-11 [SY1BSUN004 | to get deactivate_date of user from users master].start
					/*String verCode = getCommonDBAccess().sendVarificationCode( userName );
					request.setAttribute("USERNAME", userName);
					request.setAttribute("VERIFYCODE", verCode);
					request.getRequestDispatcher("jsp/ForgotPassword.jsp").forward(request, response);*/
					//Changed by Nilesh on 29-Mar-2011 [SY01SUN049][To verify user before chg password]End
					java.util.Date empDeactDate = getCommonDBAccess().checkEmpDeactDate( userName );
					java.util.Date currentDate = new  java.util.Date();
					if ( empDeactDate != null && empDeactDate.before( currentDate ))
					{
						//Added by Sagar B. for forgot password impl in APK[16/11/17]START
						if( "MOBILE".equalsIgnoreCase(editor) )
						{
							responseStr = ""+Messages.getString("AuthenticateServlet_notAnActiveUser",getUserLangAndCountry(userName));
							BaseLogger.log("3",null,null,"[AuthenticateServlet] responseStr::::["+responseStr+"]");
						}
						else
						{
							//Added by Sagar B. for forgot password impl in APK[16/11/17]END
							//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.start
							//responseStr = "<HTML><HEAD><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_notAnActiveUser")+"');window.location.href = '/ibase/jsp/login.html'</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							/*if(targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer))
							{
								// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
							    responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_notAnActiveUser",getUserLangAndCountry(userName))+"');window.location.href = '/ibase/jsp/login.jsp'</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							}
							else
							{
								// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
								//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
								responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_notAnActiveUser",getUserLangAndCountry(userName))+"');window.location.href = '"+href+"'</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
								//Changed by Sandesh on 05/12/2016 [For Authentication API] End
							}*/
							responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_notAnActiveUser",getUserLangAndCountry(userName))+"');window.location.href = '"+href+"'</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.end
						}

					}
				    else
				    {
				    	//Added By Pankaj T. on 02-07-2020 removed vulnerability of Email Flooding in forgot password (if difference between 2 request is less than predefined interval then not allowed to initiate again forgot password request)- start
				    	if( getCommonDBAccess().checkForgotPwdReqInterval( userName ) )
				    	{
				    		//Added by Pravin k on 1-MAR-19 [For appHash] START
				    		String applicationHashCode = request.getParameter("APP_HASH");
				    		String verCode = getCommonDBAccess().sendVarificationCode(userName, applicationHashCode);
				    		//Added By Pankaj T. on 19-07-2022 [Added new column ver_code in users table for maintain forgot password verification code to resend the same when next request trigger in predefined interval]
				    		getCommonDBAccess().updateVerfCode(verCode, userName);
				    		BaseLogger.log("3",null,null,"applicationHashCode :["+applicationHashCode+"]");
				    		//Added by Pravin k on 1-MAR-19 [For appHash] END
				    		BaseLogger.log("3",null,null,"verCode =["+verCode+"]");
				    		//Added by Sagar B. for forgot password impl in APK[16/11/17]START
				    		if( "MOBILE".equalsIgnoreCase(editor) )
				    		{
				    			BaseLogger.log("3",null,null,"sessionID in FORGOTPASSWORD method : "+request.getSession().getId());
				    			request.getSession().setAttribute("VF_CODE", verCode);
				    			responseStr = "SUCCESS";
				    			BaseLogger.log("3",null,null,"[AuthenticateServlet] responseStr::::["+responseStr+"]");
				    		}
				    		else
				    		{
				    			//Changed by Sadique S [To hide/encrypt the OTP at client side] on 26-06-19 START
				    			String codeOtp = encrypt(verCode);
				    			request.getSession().setAttribute("VF_CODE", codeOtp);
				    			//Added by Sagar B. for forgot password impl in APK[16/11/17]END
				    			request.setAttribute("USERNAME", userName); //$NON-NLS-1$
				    			//request.setAttribute("VERIFYCODE", verCode); //$NON-NLS-1$
				    			//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
				    			//Added by Santosh on 27-10-2017 to display dynamic message[Start]
				    			String secCommMode = getCommonDBAccess().getSecurityCommMode(userName);
				    			BaseLogger.log("3",null,null,"[AuthenticateServlet] secCommMode["+secCommMode+"]");
				    			request.setAttribute("SEC_COMM_MODE", secCommMode);
				    			request.setAttribute("PREFFERED_COMM", CommonConstants.PREFFERED_COMM);
				    			//Added by Santosh on 27-10-2017 to display dynamic message[End]
				    			request.setAttribute("HREF", href);
				    			//Changed by Sandesh on 05/12/2016 [For Authentication API] End
				    			request.getRequestDispatcher("jsp/ForgotPassword.jsp").forward(request, response); //$NON-NLS-1$
				    			responseStr = "SUCCESS";
				    			//Changed by Sadique S [To hide/encrypt the OTP at client side] on 26-06-19 END
				    		}
				    	}
				    	//Added By Pankaj T. on 02-07-2020 removed vulnerability of Email Flooding in forgot password (if difference between 2 request is less than predefined interval then not allowed to initiate again forgot password request)- start
				    	else
				    	{
				    		if( "MOBILE".equalsIgnoreCase(editor) )
							{
								responseStr = ""+Messages.getString("AuthenticateServlet_forgotPasswordReqFailedMsgStr",getUserLangAndCountry(userName))+" OR Try after "+ getCommonDBAccess().getForgotPwdReqIntervalDiff(userName) + " minutes.";
							}
							else
							{
								//Added By Pankaj T. on 19-07-2022 [Added new column ver_code in users table for maintain forgot password verification code to resend the same when next request trigger in predefined interval or open the verification page]
								String retryPassHref = "/ibase/jsp/RetryForgotPassword.jsp?USERNAME="+userName;
								responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_forgotPasswordReqFailedMsgStr",getUserLangAndCountry(userName))+" OR Try after "+ getCommonDBAccess().getForgotPwdReqIntervalDiff(userName) + " minutes."+"');window.location.href = '"+retryPassHref+"'</SCRIPT></HEAD></HTML>";
							}
				    		BaseLogger.log("3",null,null,"[AuthenticateServlet] responseStr::::["+responseStr+"]");
				    	}
				    	//Added By Pankaj T. on 02-07-2020 removed vulnerability of Email Flooding in forgot password (if difference between 2 request is less than predefined interval then not allowed to initiate again forgot password request)- end
				    }
					//Yogesh on 14-06-11 [SY1BSUN004 | to get deactivate_date of user from users master].end
				}
				else
				{
					//Added by Sagar B. for forgot password impl in APK[16/11/17]START
					if( "MOBILE".equalsIgnoreCase(editor) )
					{
						responseStr = ""+Messages.getString("AuthenticateServlet_pleaseEnterValidUser",getUserLangAndCountry(userName));
						BaseLogger.log("3",null,null,"[AuthenticateServlet] responseStr::::["+responseStr+"]");
					}
					else
					{
						//Added by Sagar B. for forgot password impl in APK[16/11/17]END
						//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.start
						//responseStr = "<HTML><HEAD><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUser")+"');window.location.href = '/ibase/jsp/login.html'</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						//Changed By Mahesh Patidar on 06-SEP-13 [to redirect back to login.jsp if callerPage is JSP]
	//					if(targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer))
						/*if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
						{
						  	// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
							responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUser",getUserLangAndCountry(userName))+"');window.location.href = '/ibase/jsp/login.jsp'</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						}
						else
						{
							// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
							//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
							responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUser",getUserLangAndCountry(userName))+"');window.location.href = '"+href+"'</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							//Changed by Sandesh on 05/12/2016 [For Authentication API] End
						}*/
						responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUser",getUserLangAndCountry(userName))+"');window.location.href = '"+href+"'</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.end
					}

				}
				//Changed By Yogesh on 06/05/11 [SY1BSUN004 |Authentication happen from users table ]End

				//Changes made by Gulzar on 03/03/14[WS3LFOR001]  : START
				response.setBufferSize(responseStr.length());
				response.setContentType( "text/html; charset=UTF8,"+CommonConstants.ENCODING );
				//Changes made by Gulzar on 03/03/14[WS3LFOR001]  : END

				OutputStream outputStream = response.getOutputStream();
				outputStream.write(responseStr.getBytes());
				outputStream.flush();
				outputStream.close();
			}
			//Change by Nilesh on 02-Feb-11 [SY90SUN016][To retrive password] End
			//Changed by Nilesh on 29-Mar-2011 [SY01SUN049][To verify user before chg password]Start
			else if( "VERIFYUSER".equals( action ) ) //$NON-NLS-1$
			{
				//below code is Added by sadique shaikh 24-6-2019 for changes password
				String deviceId = request.getParameter("MAC_ADDRESS");
				if( deviceId == null || deviceId.trim().length() == 0 )
				{
					deviceId = request.getParameter("DEVICEID");
				}
				String responseStr = "";
				String userName = request.getParameter("USER");
				//Added by Sagar B. for forgot password impl in APK[16/11/17]START
				String editor = request.getParameter("EDITOR"); //Added by Sagar B. on 2/11/17
				editor = E12GenericUtility.checkNull(editor);
				//Commented global userinfo object by Pankaj T on 18-01-18 for resolving issue of display data of another user
				BaseLogger.log("3",null,null,"VerifyUser userName:::"+userName);
				//ibase.utility.UserInfoBean userInfo = getCommonDBAccess().createUserInfo(userName);
				//userInfo = (ibase.utility.UserInfoBean)request.getSession().getAttribute("USER_INFO");
				String transDB = "";
				getCommonDBAccess().getTransDB(userName);
				transDB = getCommonDBAccess().getTransDB();
				StringBuffer responseStrBuf = new StringBuffer();
				if( "MOBILE".equalsIgnoreCase(editor) )
				{
					String vfcode = request.getParameter("VFCODE");
					vfcode = E12GenericUtility.checkNull(vfcode);
					try
					{
						BaseLogger.log("3",null,null,"sessionID in VERIFYUSER method : "+request.getSession().getId());
						if(validateVFCode(request, vfcode))
						{
							responseStrBuf.append( "<Root>" ); //$NON-NLS-1$
							if( transDB != null && transDB.length() > 0 )
							{
								responseStrBuf.append( "<minPwdLen><![CDATA[" ).append( getCommonDBAccess().getMinPwdLength(transDB)).append( "]]></minPwdLen>" ); //$NON-NLS-1$ //$NON-NLS-2$
							}
							else
							{
								responseStrBuf.append( "<minPwdLen><![CDATA[8]]></minPwdLen>" ); //$NON-NLS-1$ //$NON-NLS-2$
							}
					        responseStrBuf.append( "</Root>" ); //$NON-NLS-1$
							BaseLogger.log("3",null,null, "responseStrBuf If:["+responseStrBuf+"]" );
						}
						else
						{
							responseStrBuf.append("FALSE");
							BaseLogger.log("3",null,null, "responseStrBuf else:["+responseStrBuf+"]" );
						}

					}
					catch (Exception e)
					{
						BaseLogger.log("0",null,null,"Exception in [AuthenticateServlet] VERIFYUSER"+e.getMessage());
					}
					OutputStream outputStream = response.getOutputStream();
					outputStream.write(responseStrBuf.toString().getBytes());
					outputStream.flush();
					outputStream.close();
				}
				else
				{
					//Added by Sagar B. for forgot password impl in APK[16/11/17]END
					//String clientIP = request.getRemoteAddr();
					//Changed By Pankaj T. on 21-05-2021 for getting actual client ip in case of load balancer - start
					String clientIP = request.getHeader("X-Forwarded-For");
					if(clientIP == null)
					{  
						clientIP = request.getRemoteAddr();
					}
					//Changed By Pankaj T. on 21-05-2021 for getting actual client ip in case of load balancer - end
					//Below code commented and Two new arguement added by sadique 25-6-2019 for change password
					//secureAccount(userName, "0"); //$NON-NLS-1$
					secureAccount(userName, "0",clientIP,deviceId); //$NON-NLS-1$
					//Added By Pankaj T. on 02-07-2020 removed vulnerability of Email Flooding in forgot password (if difference between 2 request is less than predefined interval then not allowed to initiate again forgot password request)- start
					getCommonDBAccess().updateForgotPwdReqDateTime( false, userName ) ;
					//Added By Pankaj T. on 02-07-2020 removed vulnerability of Email Flooding in forgot password (if difference between 2 request is less than predefined interval then not allowed to initiate again forgot password request)- end
					getCommonDBAccess().updatePasswordChgLog( userName, clientIP, "Browser"); //$NON-NLS-1$
					//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.start
					//String responseStr = "<HTML><HEAD><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_newPasswordIsSentToYourEmaiID")+"');window.location.href = '/ibase/jsp/login.html'</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
					//Added by Santosh on 27-10-2017 to display proper message based on SEC_COMM_MODE value [Start]
					String message = "";
					String secCommMode = getCommonDBAccess().getSecurityCommMode(userName);
					if(!"".equalsIgnoreCase(secCommMode))
					{
						if("0".equalsIgnoreCase(secCommMode))
						{
							message = Messages.getString("AuthenticateServlet_newPasswordIsSentToYourEmaiIDAndMob",getUserLangAndCountry(userName));
						}
						else if("1".equalsIgnoreCase(secCommMode))
						{
							message = Messages.getString("AuthenticateServlet_newPasswordIsSentToYourMobile",getUserLangAndCountry(userName));
						}
						else if("2".equalsIgnoreCase(secCommMode))
						{
							message = Messages.getString("AuthenticateServlet_newPasswordIsSentToYourEmaiID",getUserLangAndCountry(userName));
						}
					}
					else
					{
						if("EMAIL".equalsIgnoreCase(CommonConstants.PREFFERED_COMM))
						{
							message = Messages.getString("AuthenticateServlet_newPasswordIsSentToYourEmaiID",getUserLangAndCountry(userName));
						}
						else if("SMS".equalsIgnoreCase(CommonConstants.PREFFERED_COMM))
						{
							message = Messages.getString("AuthenticateServlet_newPasswordIsSentToYourMobile",getUserLangAndCountry(userName));
						}
						else
						{
							message = Messages.getString("AuthenticateServlet_newPasswordIsSentToYourEmaiID",getUserLangAndCountry(userName));
						}
					}
					//Added by Santosh on 27-10-2017 to display proper message based on SEC_COMM_MODE value [End]
					//Changed By Mahesh Patidar on 06-SEP-13 [to redirect back to login.jsp if callerPage is JSP]
	//				if(targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer))
					/*if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
					{
					    // Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
						//Changed by Santosh on 27-10-2017 to display proper message based on SEC_COMM_MODE value
						//responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_newPasswordIsSentToYourEmaiID",getUserLangAndCountry(userName))+"');window.location.href = '/ibase/jsp/login.jsp'</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+message+"');window.location.href = '/ibase/jsp/login.jsp'</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
					}
					else
					{
						// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
						//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
						//Changed by Santosh on 27-10-2017 to display proper message based on SEC_COMM_MODE value
						//responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_newPasswordIsSentToYourEmaiID",getUserLangAndCountry(userName))+"');window.location.href = '"+href+"'</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+message+"');window.location.href = '"+href+"'</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						//Changed by Sandesh on 05/12/2016 [For Authentication API] End
					}*/
					responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+message+"');window.location.href = '"+href+"'</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
					//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.end

					//Changes made by Gulzar on 03/03/14[WS3LFOR001]  : START
					response.setBufferSize(responseStr.length());
					// Changed by Raju K on 05-03-14 for To achieve russian language message
					response.setContentType( "text/html; charset=UTF8,"+CommonConstants.ENCODING );
					//Changes made by Gulzar on 03/03/14[WS3LFOR001]  : END

					OutputStream outputStream = response.getOutputStream();
					outputStream.write(responseStr.getBytes());
					outputStream.flush();
					outputStream.close();
				}
			}
			//Changed by Nilesh on 29-Mar-2011 [SY01SUN049][To verify user before chg password]End
			//Added By Pankaj T. on 19-07-2022 [Added new column ver_code in users table for maintain forgot password verification code to resend the same when next request trigger in predefined interval or open the verification page]
			else if( "VERIFYFORGOTPASSWORD".equals( action ) ) //$NON-NLS-1$
			{
				System.out.println("AuthenticateServlet.doPost() REVERIFYFORGOTPASSWORD action");
				String userName = request.getParameter("userName");
				System.out.println("AuthenticateServlet.doPost() REVERIFYFORGOTPASSWORD action userName:["+userName+"]");
				UserInfoBean basicUserInfo = getCommonDBAccess().getBasicUserInfo(userName);
				userName = basicUserInfo.getLoginCode();
				basicUserInfo = null;
				System.out.println("AuthenticateServlet.doPost() REVERIFYFORGOTPASSWORD action LOGINCODE:["+userName+"]");
				String verCode = getCommonDBAccess().getDBColumnValue("USERS", "VER_CODE", " WHERE CODE = '"+userName+"'");
				String codeOtp = encrypt(verCode);
    			request.getSession().setAttribute("VF_CODE", codeOtp);
    			request.setAttribute("USERNAME", userName);
    			String secCommMode = getCommonDBAccess().getSecurityCommMode(userName);
    			BaseLogger.log("3",null,null,"[AuthenticateServlet] secCommMode["+secCommMode+"]");
    			request.setAttribute("SEC_COMM_MODE", secCommMode);
    			request.setAttribute("PREFFERED_COMM", CommonConstants.PREFFERED_COMM);
    			request.setAttribute("HREF", href);
    			request.getRequestDispatcher("jsp/ForgotPassword.jsp").forward(request, response);
    			String responseStr = "SUCCESS";
    			response.setBufferSize(responseStr.length());
				response.setContentType( "text/html; charset=UTF8,"+CommonConstants.ENCODING );
				OutputStream outputStream = response.getOutputStream();
				outputStream.write(responseStr.getBytes());
				outputStream.flush();
				outputStream.close();
			}
			else if( "RESENDFORGOTPASSWORD".equals( action ) ) //$NON-NLS-1$
			{
				System.out.println("AuthenticateServlet.doPost() RETRYFORGOTPASSWORD action");
				String userName = request.getParameter("userName");
				System.out.println("AuthenticateServlet.doPost() REVERIFYFORGOTPASSWORD action userName:["+userName+"]");
				UserInfoBean basicUserInfo = getCommonDBAccess().getBasicUserInfo(userName);
				userName = basicUserInfo.getLoginCode();
				basicUserInfo = null;
				String responseStr = "";
	    		String applicationHashCode = request.getParameter("APP_HASH");
	    		String verCode = getCommonDBAccess().sendVarificationCode(userName, applicationHashCode, true);
	    		BaseLogger.log("3",null,null,"applicationHashCode :["+applicationHashCode+"]");
	    		BaseLogger.log("3",null,null,"verCode =["+verCode+"]");
    			String codeOtp = encrypt(verCode);
    			request.getSession().setAttribute("VF_CODE", codeOtp);
    			request.setAttribute("USERNAME", userName);
    			String secCommMode = getCommonDBAccess().getSecurityCommMode(userName);
    			BaseLogger.log("3",null,null,"[AuthenticateServlet] secCommMode["+secCommMode+"]");
    			request.setAttribute("SEC_COMM_MODE", secCommMode);
    			request.setAttribute("PREFFERED_COMM", CommonConstants.PREFFERED_COMM);
    			request.setAttribute("HREF", href);
    			request.getRequestDispatcher("jsp/ForgotPassword.jsp").forward(request, response);
    			responseStr = "SUCCESS";
				response.setBufferSize(responseStr.length());
				response.setContentType( "text/html; charset=UTF8,"+CommonConstants.ENCODING );
				OutputStream outputStream = response.getOutputStream();
				outputStream.write(responseStr.getBytes());
				outputStream.flush();
				outputStream.close();
			}
			//Added By Pankaj T. on 19-07-2022 [Added new column ver_code in users table for maintain forgot password verification code to resend the same when next request trigger in predefined interval or open the verification page]
			//Change by Sandesh on 08/04/2016 [For onResumeEvent on Session Expired]Start
			else if( "RESUME_CONN".equals( action ) )
		    {
				StringBuffer responseStrBuf = new StringBuffer();
				//Commented global userinfo object by Pankaj T on 18-01-18 for resolving issue of display data of another user
				ibase.utility.UserInfoBean userInfo = (ibase.utility.UserInfoBean)request.getSession().getAttribute("USER_INFO");
				//userInfo = (ibase.utility.UserInfoBean)request.getSession().getAttribute("USER_INFO");
				if(userInfo == null)
				{
					responseStrBuf.append("re-connect");
					authenticate(request);
		        }
				else
				{
					responseStrBuf.append("connected");
				}
				OutputStream outputStream = response.getOutputStream();
				outputStream.write(responseStrBuf.toString().getBytes());
				outputStream.flush();
				outputStream.close();
		    }
			//Change by Sandesh on 08/04/2016 [For onResumeEvent on Session Expired]End
			//Changed by Sandesh on 18/11/2016 [For Authentication API] Start
			else if("GET_EXTAPPINFO".equals( action ))
			{
				String responseStr = "";
				String appId = request.getParameter("APPID");
				applicationBean = getCommonDBAccess().getExtAuthApplicationInfo(appId);
				if (applicationBean != null	&& E12GenericUtility.checkNull(applicationBean.getActive()).equalsIgnoreCase("T"))
				{

					responseStr = "{\"applicationId\":\""+appId+ "\", \"redirectUrl\":\""+applicationBean.getAppRedirectURL()+ "\"}";
				}
				else
				{
					responseStr = "Error~Application is not valid";
				}

				response.setBufferSize(responseStr.length());
				response.setContentType("text/html; charset=UTF8," + CommonConstants.ENCODING);
				OutputStream outputStream = response.getOutputStream();
				outputStream.write(responseStr.getBytes());
				outputStream.flush();
				outputStream.close();
			}
			//Changed by Sandesh on 18/11/2016 [For Authentication API] End
			//Added by Sandeep S. on 02-NOV-2017 [To update status of user is active or not when delete the connection and To check the status of user is active or not when sending push notification] Start
			else if("UPDATE_ACTIVE_STATUS".equals( action ))
			{
				String responseStr = "";
				String deviceId = request.getParameter("DEVICE_ID");
				String userId = request.getParameter("USER_ID");
				responseStr = getCommonDBAccess().updateActiveStatus(userId, deviceId);
				BaseLogger.log("3",null,null,"response for action UPDATE_ACTIVE_STATUS ===> "+responseStr);
				response.setBufferSize(responseStr.length());
				response.setContentType("text/html; charset=UTF8," + CommonConstants.ENCODING);
				OutputStream outputStream = response.getOutputStream();
				outputStream.write(responseStr.getBytes());
				outputStream.flush();
				outputStream.close();
			}
			//Added by Sandeep S. on 02-NOV-2017 [To update status of user is active or not when delete the connection and To check the status of user is active or not when sending push notification] End
			//Added by Sagar B. for forgot password impl in APK[16/11/17]START
			else if( "CHANGE_PASSWD".equals( action )) //$NON-NLS-1$
			{
				BaseLogger.log("3",null,null,"AuthenticateServlet >> in CHANGE_PASSWD");
				String responseStr = ""; //$NON-NLS-1$
				String user = request.getParameter("USER");
				String password = new String( request.getParameter( "NEW_PASSWD" ).getBytes( CommonConstants.ENCODING ), CommonConstants.ENCODING );
				String newPwdSHA256 = ( request.getParameter( "newPwdSHA256" ) == null ) ? "" : request.getParameter( "newPwdSHA256" );
				String userLang = ( request.getParameter( "userLang" ) == null ) ? "" : request.getParameter( "userLang" );
				//Added by Dnyaneshwar Chavan on 30-OCT-14 [ Change password not working in native interface ] End
				//Commented global userinfo object by Pankaj T on 18-01-18 for resolving issue of display data of another user
				ibase.utility.UserInfoBean userInfo = (ibase.utility.UserInfoBean)request.getSession().getAttribute("USER_INFO"); //$NON-NLS-1$
				//userInfo = (ibase.utility.UserInfoBean)request.getSession().getAttribute("USER_INFO"); //$NON-NLS-1$
				if( userInfo == null )
				{
					userInfo = getCommonDBAccess().createUserInfo(user);
				}
				/*AppConnectParm appConnect = new AppConnectParm();
				InitialContext ctx = new InitialContext(appConnect.getProperty());
				DBAccessRemote dbAccess = (DBAccessRemote) ctx.lookup( "ibase/DBAccessEJB/remote" );*/
				DBAccessEJB dbAccess = new DBAccessEJB();
				//Below code get ip address added by sadique 25-6-2019 for change password
				String chgIp=request.getRemoteHost();
				userInfo.setEmpInfo( dbAccess.getEmpInfo( userInfo.getLoginCode(), userInfo.getSiteCode(), userInfo.getTransDB() ) );
				String currPwd = E12GenericUtility.checkNull(userInfo.getLoginPwd());
				String userType = E12GenericUtility.checkNull(userInfo.getUserType());
				String userName = E12GenericUtility.checkNull(userInfo.getUserName());
				String empCode = E12GenericUtility.checkNull(userInfo.getEmpCode());
				String empName = E12GenericUtility.checkNull(userInfo.getEmpName());
				String empFName = "";
				String empMName = "";
				String empLName = "";
				BaseLogger.log("3",null,null,"in change password==> userType["+userType+"] currPwd["+currPwd+"] userName["+userName+"] empCode["+empCode+"] empName["+empName+"] ");
				if( currPwd.equalsIgnoreCase(password) || currPwd.equalsIgnoreCase(newPwdSHA256) )
				{
					responseStr = "PWD_EXIST";
				}
				else
				{
					//Added By Pankaj T. on 04-06-2020 for sun vulnerabilities added server side validation of old & new password - start
					CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
					if( commonDBAccessEJB.validatePassword(password, userInfo) )
					{
						ChangePasswordBean changePasswordBean = new ChangePasswordBean();
						if(!changePasswordBean.checkPassHistory(user,password, userInfo))
						{
							if( "E".equalsIgnoreCase(userType))
							{
								String[] empNameSlipt = empName.split(" ");
								empFName = E12GenericUtility.checkNull(empNameSlipt[0]);
								empMName = E12GenericUtility.checkNull(empNameSlipt[1]);
								empLName = E12GenericUtility.checkNull(empNameSlipt[2]);
								
								boolean toBeChecked = "".equals(empFName)?true:false;
								//check whether name is used in the password or not
								if (toBeChecked || password.toLowerCase().indexOf(empFName.toLowerCase()) == -1 )
								{
									toBeChecked = "".equals(empMName)?true:false;
									if (toBeChecked || password.toLowerCase().indexOf(empMName.toLowerCase()) == -1)
									{
										toBeChecked = "".equals(empLName)?true:false;
										if (toBeChecked || password.toLowerCase().indexOf(empLName.toLowerCase()) == -1)
										{
											if(password.toLowerCase().indexOf(empCode.toLowerCase()) == -1)
											{
												//below code commented and Two new arguement added by sadique 25-6-2019 for change password
												//changePasswordBean.updatePassword( user,password, newPwdSHA256, userLang, userInfo )
												changePasswordBean.updatePassword( user,password, newPwdSHA256, userLang, userInfo, chgIp ,"" );//Added by Dnyaneshwar Chavan on 30-OCT-14 [ Change password not working in native interface ] Start
												responseStr = "UPDATED";
											}
											else
											{
												responseStr = "PWD_USES_EMP_DETAILS";
											}
										}
										else
										{
											responseStr = "PWD_USES_EMP_DETAILS";
										}
									}
									else
									{
										responseStr = "PWD_USES_EMP_DETAILS";
									}
								}
								else
								{
									responseStr = "PWD_USES_EMP_DETAILS";
								}
							}
							else
							{
								boolean toBeChecked = "".equals(userName)?true:false;
								if (toBeChecked || password.toLowerCase().indexOf(userName.toLowerCase()) == -1)
								{
									if(password.toLowerCase().indexOf(user.toLowerCase()) == -1)
									{
										//below code commented and Two new arguement added by sadique 25-6-2019 for change password
										//changePasswordBean.updatePassword( user,password, newPwdSHA256, userLang, userInfo )
										changePasswordBean.updatePassword( user,password, newPwdSHA256, userLang, userInfo ,chgIp,"");//Added by Dnyaneshwar Chavan on 30-OCT-14 [ Change password not working in native interface ] Start
										responseStr = "UPDATED";
									}
									else
									{
										responseStr = "PWD_USES_USER_DETAILS";
									}
								}
								else
								{
									responseStr = "PWD_USES_USER_DETAILS";
								}
							}
						}
						else
						{
							responseStr = "PWD_EXIST"; //$NON-NLS-1$
						}
					}
					else
					{
						responseStr = "INVALID_PWD";
					}
				}
				//Added By Pankaj T. on 04-06-2020 for sun vulnerabilities added server side validation of old & new password - end
				dbAccess = null;
				BaseLogger.log("3",null,null,"AuthenticateServlet >> in CHANGE_PASSWD responseStr["+responseStr+"]");
				OutputStream outputStream = response.getOutputStream();
				outputStream.write(responseStr.getBytes());
				outputStream.flush();
				outputStream.close();
			}
			else if( "SERVER_TEST".equals( action ))
			{
				String responseStr = "TESTED";
				OutputStream outputStream = response.getOutputStream();
				outputStream.write(responseStr.getBytes());
				outputStream.flush();
				outputStream.close();
			}
			//Added by Sagar B. for forgot password impl in APK[16/11/17]END
			//Added by Sandeep S. on 01-Feb-18 [To check session exist or not for same user in Mobile apk] Start
			else if( "REMOVE_MOBILE_SESSION".equals(action) )
			{
				String sessionIdToRemove = request.getParameter("mobileSessionId");
				String responseStr = "";
				if( sessionIdToRemove != null && sessionIdToRemove.length() > 0 )
				{
					SessionListener.removeUserInfoOfSession(sessionIdToRemove);
					responseStr = "Success";
				}
				OutputStream outputStream = response.getOutputStream();
				outputStream.write(responseStr.getBytes());
				outputStream.flush();
				outputStream.close();
			}
			//Added by Sandeep S. on 01-Feb-18 [To check session exist or not for same user in Mobile apk] End
			// Added by Abhishek T on 20-MAR-18 [For OTP based authentication] START
			else if ("SEND_OTP".equals(action))
			{
				String mobileNumber = request.getParameter("MN");
				String otpLength = request.getParameter("OTPLN");
				//Added by Pravin k on 1-MAR-19 [For appHash] START
				// For sending app hashcode with OTP message
				// Refer link: https://developers.google.com/identity/sms-retriever/verify
				String applicationHashCode = request.getParameter("APP_HASH");
				BaseLogger.log("2",null,null,"Application hash code :: " + applicationHashCode);
				//Added by Pravin k on 1-MAR-19 [For appHash] END
				String responseData = "1";

				int otpLengthInt = 5;
				if (otpLength != null && otpLength.length() > 0) {
					String length = otpLength.substring(0, 1);
					if (Character.isDigit(length.charAt(0))) {
						otpLengthInt = Integer.parseInt(length);
					}
				}

				char[] otpCode = generateOTP(otpLengthInt);

				String formatCode = "OTP_FORMAT";

				CommonDBAccessRemote dbAccessRemote = getCommonDBAccess();
				UserInfoBean basicUserInfo = dbAccessRemote.getBasicUserInfo(mobileNumber);
				String loginCode = basicUserInfo.getLoginCode();

				if (loginCode != null && ! "NOTMATCHED".equals(E12GenericUtility.checkNull(loginCode))) {
					E12SMSComp smsComp = new E12SMSComp();
					UserInfoBean userInfo = dbAccessRemote.createUserInfo(loginCode);
					String xtraParams = "loginCode=" + loginCode + "~~loginEmpCode" + loginCode;

					StringBuffer valueXmlString = new StringBuffer("<?xml version=\"1.0\" ?><Root><Header></Header><Errors></Errors>");
					valueXmlString.append("<Detail1 objName = 'user_authenticate'>");
					valueXmlString.append("<code><![CDATA[").append(loginCode).append("]]></code>");
					valueXmlString.append("<OTP><![CDATA[").append(otpCode).append("]]></OTP>");
					valueXmlString.append("<VALID_MIN><![CDATA[").append("5").append("]]></VALID_MIN>");
					//Added by Pravin k on 1-MAR-19 [For appHash] START
					valueXmlString.append("<APP_HASH><![CDATA[").append(applicationHashCode).append("]]></APP_HASH>");
					//Added by Pravin k on 1-MAR-19 [For appHash] END
					valueXmlString.append("</Detail1>");
					valueXmlString.append("</Root>");

					// Changed by Abhishek T onb 26-Nov-18 [Changes in API for sending OTP SMS, passing parameter "SMSType"] START
					String result = smsComp.sendSMS (
						valueXmlString.toString(), formatCode,
						xtraParams, SMSType.OTP, userInfo
					);
					// Changed by Abhishek T onb 26-Nov-18 [Changes in API for sending OTP SMS, passing parameter "SMSType"] END

					if ("SEND_SUCCESS".equals(result)) {
						HttpSession httpSession = request.getSession(true);

						httpSession.setAttribute("OTP_CHARS", otpCode);
						httpSession.setAttribute("OGT_" + String.valueOf(otpCode), System.currentTimeMillis());
						httpSession.setAttribute("MN", mobileNumber);

						responseData = "1";
					} else {
						responseData = "0:Failed to send OTP SMS";
					}
				} else {
					responseData = "0:Mobile number is not registered";
				}

				OutputStream responseWriter = response.getOutputStream();
				responseWriter.write(responseData.getBytes());
				responseWriter.flush();
				responseWriter.close();
			}
			else if ("VERIFY_OTP".equals(action))
			{
				verifyOTP(request, response);
			}
			// Added by Abhishek T on 20-MAR-18 [For OTP based authentication] END

			//Added By Pankaj T. on 18-06-18 for device security based on enterprise level [0-disabled, 1-strictly enforced, 2-OTP, 3-workflow invoked] - Start
			else if( "VERIFY_USER_DEVICE".equals( action ) )
			{
				BaseLogger.log("3",null,null,"In VERIFY_USER_DEVICE action");
				String userCode = request.getParameter("USER");
				String editor = request.getParameter("EDITOR");
				String deviceId = request.getParameter( "DEVICEID" );
				String active = request.getParameter( "ACTIVE" );
				String deviceOS = request.getParameter( "DEVICEOS" );
				String deviceUuId = request.getParameter( "DEVICEUUID" );
				String deviceType = E12GenericUtility.checkNull(request.getParameter( "DEVICETYPE" ));

				String deviceIMEINo = request.getParameter("IMEI_NO");
				String appName = request.getParameter("APP_NAME");
				String appVersion = request.getParameter("CURRENTAPKVERSION");
				//String chgIP = request.getRemoteAddr();
				//Changed By Pankaj T. on 21-05-2021 for getting actual client ip in case of load balancer - start
				String chgIP = request.getHeader("X-Forwarded-For");
				if (chgIP == null)
				{  
					chgIP = request.getRemoteAddr();
				}
				//Changed By Pankaj T. on 21-05-2021 for getting actual client ip in case of load balancer - end
				String conApplNm = request.getParameter("conApplNm");
				String fromCache = E12GenericUtility.checkNull(request.getParameter("FROM_CACHE"));
				String currentGeoPos = E12GenericUtility.checkNull(request.getParameter("CURRENT_GEO_POS"));
				conApplNm = ( conApplNm != null ) ? conApplNm : "SFA" ;
				BaseLogger.log("3",null,null,"application name for explorer@@@:[" + conApplNm+"]");
				ibase.utility.UserInfoBean userInfo = (ibase.utility.UserInfoBean)request.getSession().getAttribute("USER_INFO");
				//Added by Sainath on 20/09/18 [set deviceType in userInfo]
				userInfo.setDeviceType(deviceType);
				BaseLogger.log("3",null,null,"userInfo@@:["+userInfo+"]");
				String currentApkVersion = request.getParameter("CURRENTAPKVERSION");
				String batteryStatus = request.getParameter("BATTERY_STATUS");
				String upgradeMessage = "";
				String recommendedMessage = "";
				BaseLogger.log("3",null,null,"currentApkVersion " + currentApkVersion);
				boolean checkVersion = true;
				boolean checkRecommendedVersion = true;
				if( currentApkVersion != null && !"".equalsIgnoreCase(currentApkVersion) )
				{
					checkVersion = checkVersionComaptibility(currentApkVersion);
					if( !checkVersion )
					{
						//changed by vishal pathare on 7.8.18 as suggested by KB sir
						//upgradeMessage = "This version is no more compatible for this server, please upgrade from Google PlayStore";
						upgradeMessage = "This version of the app is out dated. Please update the version from Play Store/App Store.";
					}

					if( checkVersion )
					{
						checkRecommendedVersion = checkRecommendedVersionComaptibility(currentApkVersion);
						if( !checkRecommendedVersion )
						{
							recommendedMessage = "There is new version of APK ("+CommonConstants.APK_RECOMMENDED_VERSION+") available.<br>It is recommended to upgrade.";
						}
					}
				}
				HashMap<String, String> hashMap = getDeviceDetail(reqHeader, appName, appVersion);
				BrowserDetail browserDetail = new BrowserDetail(hashMap);
				editor = E12GenericUtility.checkNull(editor);
				BaseLogger.log("3",null,null,"VerifyUser device user:::"+userCode);
				getCommonDBAccess().getTransDB(userCode);
				String transDB = getCommonDBAccess().getTransDB();
				StringBuffer responseStrBuf = new StringBuffer();
				String devicevfCode = E12GenericUtility.checkNull(request.getParameter("DEVICE_VER_CODE"));
				BaseLogger.log("3",null,null,"sessionID in VERIFYUSERDEVICE method : "+request.getSession().getId());
				if(validateDeviceVFCode(request, devicevfCode))
				{
					E12GenericUtility genericUtility = new E12GenericUtility();
					String status = getCommonDBAccess().insertUserDevice( userCode, deviceId, deviceOS, deviceType, active, userCode, chgIP, browserDetail.getDeviceMake(), deviceIMEINo, true, userInfo.getEnterprise(), "MELOGIN", fromCache, currentGeoPos, userInfo.getTransDB(), userInfo, browserDetail.getOsName(), browserDetail.getOsVersion(), browserDetail.getClientApp(), browserDetail.getClientAppVersion() );
					BaseLogger.log("3",null,null,"after insert or update user_device status:["+status+"]");
					//Added By Pankaj T. on 14-04-20 to set unique id as a termId in userInfo & this termId in chg_term column - start
					if( status != null && status.startsWith("true") )
					{
						String[] statusArr = status.split("~~");
						status = "true";
						userInfo.setTermId(statusArr[1]);
					}
					//Added By Pankaj T. on 14-04-20 to set unique id as a termId in userInfo & this termId in chg_term column - end
					String authenticationStatus = "true";
					String columnName = " COUNT(1) ";
					String tableName = " ENTITY_CONTACT ";
					String condition = " WHERE USER_ID__PORTAL='"+ userInfo.getLoginCode() +"' AND ENTITY_TYPE='"+ userInfo.getUserType() +"' ";
					String countResult = getCommonDBAccess().getDBColumnValue( tableName.trim(), columnName.trim(), condition, userInfo.getTransDB() )  ;
					columnName = null;
					tableName = null;
					condition = null;
					String allowChgAccount = "N";
					if( countResult != null )
					{
						try
						{
							int cnt = (int) Double.parseDouble(countResult);
							if( cnt > 1 )
							{
								allowChgAccount = "Y";
							}
						}
						catch (Exception e)
						{
							allowChgAccount = "N";
						}
					}
					BaseLogger.log("3",null,null," Change Entity Details : ALLOW_CHG_ACCOUNT ["+ allowChgAccount +"]countResult["+countResult+"]");
					request.getSession().setAttribute( "ALLOW_CHG_ACCOUNT", allowChgAccount);

					String hostName = userInfo.getHostName();
					String hostIP = userInfo.getHostIP();
					String remoteHostName = userInfo.getRemoteHostName();

					if( deviceType == null || "".equalsIgnoreCase( deviceType ) )
					{
						BaseLogger.log("3",null,null,"AuthenticateServlet :: authenticate() : userInfo[" + userInfo + "]");
						BaseLogger.log("3",null,null,"batteryStatus :: "+batteryStatus);
						getCommonDBAccess().insertSessionTrace( userInfo.getLoginCode(), request.getSession().getId(), true,
								chgIP, userInfo.getTermId(), hostName, hostIP, userInfo.getEntryId(), userInfo.getEntryType(), userInfo.getTransDB(),
								batteryStatus, browserDetail.getOsName(), browserDetail.getOsVersion(), browserDetail.getClientApp(), browserDetail.getClientAppVersion());
					}
					else
					{
						getCommonDBAccess().insertSessionTrace( userInfo.getLoginCode(), request.getSession().getId(), true, chgIP,
								userInfo.getTermId(), deviceUuId, deviceType, hostName, hostIP, userInfo.getEntryId(), userInfo.getEntryType(),
								'@', userInfo.getTransDB(), batteryStatus, browserDetail.getOsName(), browserDetail.getOsVersion(), browserDetail.getClientApp(), browserDetail.getClientAppVersion());
					}

					if("true".equals(request.getAttribute("isReqFromRcp")))
					{
						request.getSession().setAttribute( "IS_EMP_INFO_SET", "true" );
					}
					//Added by gayatri [to identify the request from rcp]end
					//Added By Ajinkya Gopalkar on 6-Jan-16[For checking gps after defined interval]
					BaseLogger.log("3",null,null,"In AuthenticateServlet before insertGeoPosition....!!!!");
					if ( userInfo != null && "true".equalsIgnoreCase(authenticationStatus))
					{
						//BaseLogger.log("9",null,null, "USER_INFO :[" + userInfo.toString() + "]" );
						//Changed by Sagar B. for Geo position related changes for multi tenancy on [11Jan18]
						//if( "true".equalsIgnoreCase( CommonConstants.GEOPOS_ENABLE ) )
						if( !"0".equalsIgnoreCase(userInfo.getGeoPosOption()) )
		 				{
							//String currentGeoPos = request.getParameter("CURRENT_GEO_POS");
							String dataMode = request.getParameter("DATA_MODE");
							String currentGeoPosName = E12GenericUtility.checkNull( request.getParameter("CURRENT_GEO_POS_NAME") );		//Added by Sagar B. to track address of current geopos and store in table[10-Apr-18]
							String geoPosAccuracy = E12GenericUtility.checkNull( request.getParameter("GEOPOS_ACCURACY") );		//Added by Sagar B. to store accuracy of geo position[23-Jul-18]
							BaseLogger.log("3",null,null,"@AUTHENTICATE 1164 CURRENT_GEO_POS["+ currentGeoPos +"] dataMode["+ dataMode +"] CURRENT_GEO_POS_NAME["+currentGeoPosName+"] GEOPOS_ACCURACY["+geoPosAccuracy+"]");
							if( currentGeoPos != null && currentGeoPos.trim().length() > 0 )
		 					{
								userInfo.setCurrentGeoPOS(currentGeoPos);
								userInfo.setDeviceID(deviceUuId);

								userInfo.setDataMode(dataMode);
								userInfo.setCurrentGeoPOSName(currentGeoPosName);
								userInfo.setGeoPosAccuracy(geoPosAccuracy);		//Added by Sagar B. to store accuracy of geo position[23-Jul-18]
								request.getSession().setAttribute( "USER_INFO", userInfo );
								getCommonDBAccess().updateCurrentGeoPos(userCode, request.getSession().getId(), currentGeoPos, dataMode, ""); // Changed and Added by Pankaj R on 20-JAN-18
								BaseLogger.log("3",null,null,"@AUTHENTICATE 1170 After updateCurrentGeoPos.....!!!");
								//GeoPosition Logging in GEOPOS table - And in case of Web Access deviceUuId will be blank or null so setting RemoteHost
								if( E12GenericUtility.checkNull( deviceUuId ).length() == 0 )
								{
									deviceUuId = request.getRemoteHost();
								}
								//getCommonDBAccess().insertGeoPosition(userCode, deviceUuId, "", currentGeoPos, "1", dataMode);
								getCommonDBAccess().insertGeoPosition(userCode, deviceUuId, "", currentGeoPos, "1", dataMode, currentGeoPosName, geoPosAccuracy);
		 					}
		 				}

						//Added By Samadhan on 27-10-2017 [ set enterprise if blank for property editor] start
						String enterprise = userInfo.getEnterprise();
						if( enterprise == null || enterprise.length() <= 0 )
						{
							if(userInfo.getItemSer() == null || "".equalsIgnoreCase(userInfo.getItemSer()))
							{
								enterprise = userInfo.getSiteCode();
							}
							else
							{
								enterprise = userInfo.getSiteCode() + "" +userInfo.getItemSer();
							}

							userInfo.setEnterprise(enterprise);
							request.getSession().setAttribute( "USER_INFO", userInfo );
						}
						//Added By Samadhan on 27-10-2017 [ set enterprise if blank for property editor] end
					}

					responseStrBuf.append( "<Root>" );
					responseStrBuf.append( "<status><![CDATA[" ).append( authenticationStatus ).append( "]]></status>" );
					responseStrBuf.append( "<userID><![CDATA[" ).append( userInfo.getLoginCode() ).append( "]]></userID>" );
					responseStrBuf.append( "<userName><![CDATA[" ).append( userInfo.getUserName() ).append( "]]></userName>" );
					responseStrBuf.append( "<isPasswordStore><![CDATA[" ).append( userInfo.getIsPasswordStore() ).append( "]]></isPasswordStore>" );
					responseStrBuf.append( "<profileID><![CDATA[" ).append( userInfo.getProfileId() ).append( "]]></profileID>" );
					responseStrBuf.append( "<applnName><![CDATA[" ).append( conApplNm ).append( "]]></applnName>" );
					responseStrBuf.append( "<empDesignation><![CDATA[" ).append( userInfo.getDesignation() ).append( "]]></empDesignation>" );
					responseStrBuf.append( "<empDivision><![CDATA[" ).append( userInfo.getDivision() ).append( "]]></empDivision>" );
					responseStrBuf.append( "<empHeadQuat><![CDATA[" ).append( userInfo.getStanCode() ).append( "]]></empHeadQuat>" );
					responseStrBuf.append( "<empDOJ><![CDATA[" ).append( userInfo.getDateJoin() ).append( "]]></empDOJ>" );
					responseStrBuf.append( "<dispDate><![CDATA[" ).append( genericUtility.getDispDateFormat() ).append( "]]></dispDate>" );
					responseStrBuf.append( "<userLevel><![CDATA[" ).append( userInfo.getUserLevel() ).append( "]]></userLevel>" );
					responseStrBuf.append( "<deptCode><![CDATA[" ).append( userInfo.getDeptCode() ).append( "]]></deptCode>" );
					responseStrBuf.append( "<siteCode><![CDATA[" ).append( userInfo.getSiteCode() ).append( "]]></siteCode>" );
					responseStrBuf.append( "<siteDescr><![CDATA[" ).append( userInfo.getSiteDescr() ).append( "]]></siteDescr>" );
					responseStrBuf.append( "<entityCode><![CDATA[" ).append( userInfo.getEntityCode() ).append( "]]></entityCode>" );
					responseStrBuf.append( "<itemSer><![CDATA[" ).append( userInfo.getItemSer() ).append( "]]></itemSer>" );
					responseStrBuf.append( "<deptDescr><![CDATA[" ).append( userInfo.getDeptDescr() ).append( "]]></deptDescr>" );
					responseStrBuf.append( "<emailIdOff><![CDATA[" ).append( userInfo.getEmailIdOff() ).append( "]]></emailIdOff>" );
					responseStrBuf.append( "<empCode><![CDATA[" ).append( userInfo.getEmpCode() ).append( "]]></empCode>" );
					responseStrBuf.append( "<empName><![CDATA[" ).append( userInfo.getEmpName() ).append( "]]></empName>" );
					responseStrBuf.append( "<reportTo><![CDATA[" ).append( userInfo.getReportTo() ).append( "]]></reportTo>" );
					responseStrBuf.append( "<stanCode><![CDATA[" ).append( userInfo.getStanCode() ).append( "]]></stanCode>" );
					responseStrBuf.append( "<userCountry><![CDATA[" ).append( userInfo.getUserCountry() ).append( "]]></userCountry>" );
					responseStrBuf.append( "<userLanguage><![CDATA[" ).append( userInfo.getUserLanguage() ).append( "]]></userLanguage>" );
					responseStrBuf.append( "<minPwdLen><![CDATA[" ).append( getCommonDBAccess().getMinPwdLength(userInfo.getTransDB())).append( "]]></minPwdLen>" );
					responseStrBuf.append( "<applDateTimeFromat><![CDATA[" ).append( genericUtility.getApplDateTimeFormat() ).append( "]]></applDateTimeFromat>" );
					responseStrBuf.append( "<geoFenceEnabled><![CDATA[" ).append( userInfo.getUserGeoFence() ).append( "]]></geoFenceEnabled>" );
					responseStrBuf.append( "<geoFenceAccuracy><![CDATA[" ).append( CommonConstants.GEO_FENCE_ACCURACY ).append( "]]></geoFenceAccuracy>" );
					responseStrBuf.append( "<geoFenceRadius><![CDATA[" ).append( CommonConstants.GEO_FENCE_RADIUS ).append( "]]></geoFenceRadius>" );
					responseStrBuf.append( "<defaultMenu><![CDATA[" ).append( userInfo.getDefaultMenu() ).append( "]]></defaultMenu>" );
					responseStrBuf.append( "<features><![CDATA[" ).append( userInfo.getFeatures() ).append( "]]></features>" );
					responseStrBuf.append( "<userType><![CDATA[" ).append( userInfo.getUserType() ).append( "]]></userType>" );
					responseStrBuf.append( "<geoPosOption><![CDATA[" ).append( userInfo.getGeoPosOption() ).append( "]]></geoPosOption>" );
					//Added by Sagar B. to set network configuration[07-Feb-19]START
					responseStrBuf.append( "<networkOption><![CDATA[" ).append( userInfo.getUserNetworkOption() ).append( "]]></networkOption>" ); //$NON-NLS-1$ //$NON-NLS-2$
					//Added by Sagar B. to set network configuration[07-Feb-19]END
					responseStrBuf.append( "<enterprise><![CDATA[" ).append( userInfo.getEnterprise()).append( "]]></enterprise>" );
					//Added by Pankaj T. on 16-11-18 for console configuration if 1 then print console only
					responseStrBuf.append( "<clientDebugLevel><![CDATA[" ).append( CommonConstants.CLIENT_DEBUG_LEVEL).append( "]]></clientDebugLevel>" );
					//Added By Pankaj T. on 18-11--2020 for removing weak account lock vulnerability - if user wrongly enter password more than 5 times then lock the account and send new password on email/mobile and unlock account using new password
					responseStrBuf.append( "<wrongLoginCount><![CDATA[" ).append( CommonConstants.WRONG_LOGIN_COUNT).append( "]]></wrongLoginCount>" );
					//Added by Pankaj R on 25-FEB-19 to pass AUTO_SYNC data from ibase.xml[START]
					responseStrBuf.append( "<autoSync><![CDATA[" ).append( CommonConstants.AUTO_SYNC).append( "]]></autoSync>" );
					//Added by Pankaj R on 25-FEB-19 to pass AUTO_SYNC data from ibase.xml[END]
					if( !checkRecommendedVersion )
					{
						responseStrBuf.append( "<recommendedMessage><![CDATA[" ).append( recommendedMessage ).append( "]]></recommendedMessage>" );
					}
					responseStrBuf.append( "<buildNo><![CDATA[" ).append( CommonConstants.BUILD_NO ).append( "]]></buildNo>" );
					boolean isSessionExist = isSessionExistInMobile(request, userCode);
					if( isSessionExist )
					{
						String msgStr = "There is another session is running with this User ID. Terminate the running session?";
						String sessionIdToRemove = null;
						sessionIdToRemove = (String)request.getSession().getAttribute("mobileSessionIdToRemove");
						responseStrBuf.append( "<Message id= 'SESSEXIST' type ='W' column_name='' >" );
						responseStrBuf.append( "<message><![CDATA[" ).append( "Session Exist : " ).append( "]]></message>" );
						responseStrBuf.append( "<description><![CDATA[" ).append( msgStr ).append( "]]></description>" );
						responseStrBuf.append( "<trace><![CDATA[" ).append( msgStr ).append( "]]></trace>" );
						responseStrBuf.append( "</Message>" );
						responseStrBuf.append( "<mobileSessionIdToRemove><![CDATA[" ).append( sessionIdToRemove ).append( "]]></mobileSessionIdToRemove>" );
					}
					responseStrBuf.append( "</Root>" );
					BaseLogger.log("3",null,null, "responseStrBuf If:["+responseStrBuf.toString()+"]" );
				}
				else
				{
					String status = "INVALID_OTP";
					responseStrBuf.append( "<Root>" );
					responseStrBuf.append( "<DEVICE_STATUS><![CDATA[" ).append( status ).append( "]]></DEVICE_STATUS>" );
					responseStrBuf.append( "</Root>" );
					BaseLogger.log("3",null,null, "responseStrBuf else:["+responseStrBuf.toString()+"]" );
				}
				OutputStream outputStream = response.getOutputStream();
				outputStream.write(responseStrBuf.toString().getBytes());
				outputStream.flush();
				outputStream.close();
			}
			else if( "CANCEL_DEVICE_VREFN".equals( action ) )
			{
				BaseLogger.log("3",null,null,"In CANCEL_DEVICE_VREFN action");
				invalidateSession(request);
				String deviceType = request.getParameter("DEVICE_TYPE");
				BaseLogger.log("3",null,null,"Device Type:["+deviceType+"]");
				if( "Browser".equals(deviceType) )
				{
					String newHref = "/ibase/login/index.html";
					String responseString = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('You have cancelled OTP verification');window.location.href = '"+newHref+"'</SCRIPT></HEAD></HTML>";
					BaseLogger.log("3",null,null,"writeReponse    responseString    " + responseString);
					response.setBufferSize(responseString.length());
			        response.setContentType( "text/html; charset=UTF8,"+CommonConstants.ENCODING );
					OutputStream outputStream = response.getOutputStream();
					outputStream.write(responseString.getBytes());
					outputStream.flush();
					outputStream.close();
				}
			}
			//Added By Pankaj T. on 18-06-18 for device security based on enterprise level [0-disabled, 1-strictly enforced, 2-OTP, 3-workflow invoked] - End
			else
			{
				//changed by Gulzar on 29/01/15 to check for allowed session for login user. START
				//If it exceeds the defined maximum allow then will return with error message
				String responseStr = "";
				String loginUserID = request.getParameter("USER");
				boolean isAllowExceeded = isAllowSessionsExceeded(loginUserID);
				BaseLogger.log("3",null,null,"AuthenticateServlet >> isAllowExceeded =["+isAllowExceeded+"]");

				//Changed by Sandesh on 18/11/2016 [For Authentication API] Start
				String appId = request.getParameter("APPID");
				appId = E12GenericUtility.checkNull(appId);
				applicationBean = getCommonDBAccess().getExtAuthApplicationInfo(appId);
				boolean isAllowLoginAttempts  = isAllowLoginAttempts(loginUserID);
				BaseLogger.log("3",null,null,"AuthenticateServlet >> isAllowLoginAttempts =["+isAllowLoginAttempts+"]");
				// If user exceeds the Max failed login attempt then will return error message.
				if (isAUTHAPI.equalsIgnoreCase("true") && applicationBean != null && !isAllowLoginAttempts
						&& E12GenericUtility.checkNull(applicationBean.getEnableSecurity()).equalsIgnoreCase("T")
						&& E12GenericUtility.checkNull(applicationBean.getActive()).equalsIgnoreCase("T"))
				{
					responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"
							+ Messages.getString("AuthenticateServlet_maxAllowedLoginAttempts",
									getUserLangAndCountry(loginUserID))
							+ "');window.location.href = '"+href+"'</SCRIPT></HEAD></HTML>";

					BaseLogger.log("3",null,null,"writeReponse    responseString    " + responseStr);
					response.setBufferSize(responseStr.length());
					response.setContentType("text/html; charset=UTF8," + CommonConstants.ENCODING);

					OutputStream outputStream = response.getOutputStream();
					outputStream.write(responseStr.getBytes());
					outputStream.flush();
					outputStream.close();
				}
				//Changed by Sandesh on 18/11/2016 [For Authentication API] End
				else if(isAllowExceeded)
				{
					/*if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
					{
						responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_maxSessionAllowed",getUserLangAndCountry(loginUserID) )+"');window.location.href = '/ibase/jsp/login.jsp'</SCRIPT></HEAD></HTML>";
					}
					else
					{
						//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
						responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_maxSessionAllowed",getUserLangAndCountry(loginUserID) )+"');window.location.href = '"+href+"'</SCRIPT></HEAD></HTML>";
						//Changed by Sandesh on 05/12/2016 [For Authentication API] End
					}*/
					responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_maxSessionAllowed",getUserLangAndCountry(loginUserID) )+"');window.location.href = '"+href+"'</SCRIPT></HEAD></HTML>";
					BaseLogger.log("3",null,null,"writeReponse    responseString    " + responseStr);
					response.setBufferSize(responseStr.length());
			        response.setContentType( "text/html; charset=UTF8,"+CommonConstants.ENCODING );

					OutputStream outputStream = response.getOutputStream();
					outputStream.write(responseStr.getBytes());
					outputStream.flush();
					outputStream.close();
				}
				else
				{
				//changed by Gulzar on 29/01/15 to check for allowed session for login user. END

					//Added By Pankaj T. on 18-06-18 for device security based on enterprise level [0-disabled, 1-strictly enforced, 2-OTP, 3-workflow invoked] - Start
					String deviceVerified = E12GenericUtility.checkNull(request.getParameter("DEVICE_VERIFIED"));
		            BaseLogger.log("3",null,null,"deviceVerified:["+deviceVerified+"]");
		            String xmlInfo = "";
		            if( "true".equals(deviceVerified) )
		            {
		            	xmlInfo = E12GenericUtility.checkNull(request.getParameter("AUTH_STATUS"));
		            	UserInfoBean userInfo  = (ibase.utility.UserInfoBean)request.getSession().getAttribute("USER_INFO");
		            	String userCode = request.getParameter("USER");
		            	String active = "Y";
		            	//String chgIP = request.getRemoteAddr();
						//Changed By Pankaj T. on 21-05-2021 for getting actual client ip in case of load balancer - start
						String chgIP = request.getHeader("X-Forwarded-For");
						if(chgIP == null)
						{  
							chgIP = request.getRemoteAddr();
						}
						//Changed By Pankaj T. on 21-05-2021 for getting actual client ip in case of load balancer - end
		            	String deviceOS = System.getProperty("os.name");
		            	String deviceType = "Browser";
		            	String currentGeoPos = E12GenericUtility.checkNull(request.getParameter("CURRENT_GEO_POS"));
		            	String deviceIMEINo = request.getParameter("MAC_ADDRESS");
		            	String deviceId =  deviceIMEINo+"_"+userCode+"_"+chgIP+"_"+currentGeoPos;
		            	String fromCache = E12GenericUtility.checkNull(request.getParameter("FROM_CACHE"));
		            	// Changed and Added by Pankaj R on 20-JAN-18
		            	String appName = request.getParameter("APP_NAME");
						String appVersion = request.getParameter("CURRENTAPKVERSION");
						HashMap<String, String> hashMap = getDeviceDetail(reqHeader, appName, appVersion);
						BrowserDetail browserDetail = new BrowserDetail(hashMap);
						// Changed and Added by Pankaj R on 20-JAN-18
						String status = getCommonDBAccess().insertUserDevice( userCode, deviceId, deviceOS, deviceType, active, userCode, chgIP, browserDetail.getDeviceMake(), deviceIMEINo, true, userInfo.getEnterprise(), "BROWSERLOGIN", fromCache, currentGeoPos, userInfo.getTransDB(), userInfo, browserDetail.getOsName(), browserDetail.getOsVersion(), browserDetail.getClientApp(), browserDetail.getClientAppVersion() );
						BaseLogger.log("3",null,null,"status of verify device:["+status+"]");
						//Added By Pankaj T. on 14-04-20 to set unique id as a termId in userInfo & this termId in chg_term column - start
						if( status != null && status.startsWith("true") )
						{
							String[] statusArr = status.split("~~");
							status = "true";
							userInfo.setTermId(statusArr[1]);
						}
						//Added By Pankaj T. on 14-04-20 to set unique id as a termId in userInfo & this termId in chg_term column - end
						String columnName = " COUNT(1) ";
						String tableName = " ENTITY_CONTACT ";
						String condition = " WHERE USER_ID__PORTAL='"+ userInfo.getLoginCode() +"' AND ENTITY_TYPE='"+ userInfo.getUserType() +"' ";
						String countResult = getCommonDBAccess().getDBColumnValue( tableName.trim(), columnName.trim(), condition, userInfo.getTransDB() )  ;
						columnName = null;
						tableName = null;
						condition = null;
						String allowChgAccount = "N";
						if( countResult != null )
						{
							try
							{
								int cnt = (int) Double.parseDouble(countResult);
								if( cnt > 1 )
								{
									allowChgAccount = "Y";
								}
							}
							catch (Exception e)
							{
								allowChgAccount = "N";
							}
						}
						BaseLogger.log("3",null,null," Change Entity Details : ALLOW_CHG_ACCOUNT ["+ allowChgAccount +"]countResult["+countResult+"]");
						request.getSession().setAttribute( "ALLOW_CHG_ACCOUNT", allowChgAccount);

						String hostName = userInfo.getHostName();
						String hostIP = userInfo.getHostIP();
						String remoteHostName = userInfo.getRemoteHostName();

						if( deviceType == null || "".equalsIgnoreCase( deviceType ) )
						{
							BaseLogger.log("3",null,null,"AuthenticateServlet :: authenticate() : userInfo[" + userInfo + "]");
							getCommonDBAccess().insertSessionTrace( userInfo.getLoginCode(), request.getSession().getId(), true,
									chgIP, userInfo.getTermId(), hostName, hostIP, userInfo.getEntryId(), userInfo.getEntryType(), userInfo.getTransDB(),
									"", browserDetail.getOsName(), browserDetail.getOsVersion(), browserDetail.getClientApp(), browserDetail.getClientAppVersion());
						}
						else
						{
							getCommonDBAccess().insertSessionTrace( userInfo.getLoginCode(), request.getSession().getId(), true, chgIP,
									userInfo.getTermId(), "", deviceType, hostName, hostIP, userInfo.getEntryId(), userInfo.getEntryType(),
									'@', userInfo.getTransDB(), "", browserDetail.getOsName(), browserDetail.getOsVersion(), browserDetail.getClientApp(), browserDetail.getClientAppVersion());
						}

						if("true".equals(request.getAttribute("isReqFromRcp")))
						{
							request.getSession().setAttribute( "IS_EMP_INFO_SET", "true" );
						}
						//Added by gayatri [to identify the request from rcp]end
		            }
		            else
		            {
		            	xmlInfo = authenticate( request );
		            }
					BaseLogger.log("3",null,null,"Authentication status for browser:["+xmlInfo+"]");
                    //Added By Pankaj T on 15-09-2020 handle login related issue of invalid session and display alert to user for clearing browser cache - start
                    if( "INVALID_SESSION".equals(xmlInfo) )
                    {
                        generateResponse(request, response, xmlInfo, "", false);
                    }
                    //Added By Pankaj T on 15-09-2020 handle login related issue of invalid session and display alert to user for clearing browser cache - end
					else if( xmlInfo.contains("STRICTLY_ENFORCED") )
					{
						String newHref = "/ibase/login/index.html";
						String responseString = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('Only registered device is allow to login');window.location.href = '"+newHref+"'</SCRIPT></HEAD></HTML>";
						BaseLogger.log("3",null,null,"writeReponse    responseString    " + responseString);
						response.setBufferSize(responseString.length());
				        response.setContentType( "text/html; charset=UTF8,"+CommonConstants.ENCODING );
						OutputStream outputStream = response.getOutputStream();
						outputStream.write(responseString.getBytes());
						outputStream.flush();
						outputStream.close();
					}
					else if( xmlInfo.contains("WORKFLOW_INVOKED") )
					{
						String newHref = "/ibase/login/index.html";
						BaseLogger.log("2",null,null,"AuthenticateServlet.doPost() xmlInfo before replace:["+xmlInfo+"]");
						String detailXML = "";
						String userCode = "";
						String recExist = "";
						String status = xmlInfo;
						if( xmlInfo.indexOf("~~") != -1 )
						{
							status = xmlInfo.substring(0, xmlInfo.indexOf("~~"));
							BaseLogger.log("2",null,null,"AuthenticateServlet.doPost() status:["+status+"]");
							recExist = xmlInfo.substring(xmlInfo.indexOf("~~")+2, xmlInfo.lastIndexOf("~~"));
							BaseLogger.log("2",null,null,"AuthenticateServlet.doPost() recExist:["+recExist+"]");
							detailXML = xmlInfo.substring(xmlInfo.lastIndexOf("~~")+2);
							BaseLogger.log("2",null,null,"AuthenticateServlet.doPost() detailXML:["+detailXML+"]");
							UserInfoBean userInfo  = (ibase.utility.UserInfoBean)request.getSession().getAttribute("USER_INFO");
							BaseLogger.log("2",userInfo,null,"AuthenticateServlet.doPost() userInfo:["+userInfo+"]");
							userCode = request.getParameter("USER");
							BaseLogger.log("2",userInfo,null,"AuthenticateServlet.doPost() userCode:["+userCode+"]");
							StringBuffer responseStrBuf = new StringBuffer();
							responseStrBuf.append( "<Root>" );
							responseStrBuf.append( "<DEVICE_STATUS><![CDATA[" ).append( status ).append( "]]></DEVICE_STATUS>" );
							responseStrBuf.append( "</Root>" );
							xmlInfo = responseStrBuf.toString();
						}
						BaseLogger.log("2",null,null,"AuthenticateServlet.doPost() xmlInfo after replace:["+xmlInfo+"]");
						detailXML = URLEncoder.encode(detailXML);
						String updateHref = "/ibase/jsp/UpdateUserDevice.jsp?DETAIL_XML="+detailXML+"&USER_CODE="+userCode+"&REMOTE_HOST="+request.getRemoteHost();
						String responseString = "";
						//String responseString = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('Workflow have send to admin for approval. After approved by admin you will able to login');window.location.href = '"+newHref+"'</SCRIPT></HEAD></HTML>";
						if("true".equals(recExist)) 
						{
							responseString = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('This device approval is pending from admin.');window.location.href = '"+newHref+"'</SCRIPT></HEAD></HTML>";
						}
						else
						{
							responseString   = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>if(confirm('This is not a registered device. Admin approval is required to use this request for approval?')){window.location.href = '"+updateHref+"'}else{window.location.href = '"+newHref+"'} </SCRIPT></HEAD></HTML>";
						}
						BaseLogger.log("3",null,null,"writeReponse    responseString    " + responseString);
						response.setBufferSize(responseString.length());
				        response.setContentType( "text/html; charset=UTF8,"+CommonConstants.ENCODING );
						OutputStream outputStream = response.getOutputStream();
						outputStream.write(responseString.getBytes());
						outputStream.flush();
						outputStream.close();
					}
					else if( xmlInfo.contains("VERIFY_USER_DEVICE") )
					{
						request.getSession().setAttribute("USERNAME", request.getParameter("USER"));
						request.getSession().setAttribute("loginMode", request.getParameter("loginMode"));
						request.getSession().setAttribute("AUTH_MODE", request.getParameter("AUTH_MODE"));
						request.getSession().setAttribute("APPL_NAME", request.getParameter("APPL_NAME"));
						request.getSession().setAttribute("HREF", href);
						request.getSession().setAttribute("MAC_ADDRESS", request.getParameter("MAC_ADDRESS"));
						request.getSession().setAttribute("CURRENT_GEO_POS", request.getParameter("CURRENT_GEO_POS"));
						request.getSession().setAttribute("DEVICE_VER_CODE", request.getSession().getAttribute("DEVICE_VER_CODE"));
						request.getSession().setAttribute("AUTH_STATUS", request.getSession().getAttribute("AUTH_STATUS"));
						RequestDispatcher reqDis = request.getRequestDispatcher( "/jsp/VerifyDeviceSecurity.jsp" ); //$NON-NLS-1$
						reqDis.forward( request, response );
					}
					if( xmlInfo.indexOf("<error") != -1 )
					{
						E12GenericUtility e12GenericUtility = new E12GenericUtility();
						String errorString = E12GenericUtility.checkNull( e12GenericUtility.getErrorString(xmlInfo) );
						BaseLogger.log("3",null,null,"errorString in Browser authentication:["+errorString+"]");
						String newHref = "/ibase/login/index.html";
						String responseString = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+errorString+"');window.location.href = '"+newHref+"'</SCRIPT></HEAD></HTML>";
						BaseLogger.log("3",null,null,"writeReponse responseString:[" + responseString+"]");
						response.setBufferSize(responseString.length());
				        response.setContentType( "text/html; charset=UTF8,"+CommonConstants.ENCODING );
						OutputStream outputStream = response.getOutputStream();
						outputStream.write(responseString.getBytes());
						outputStream.flush();
						outputStream.close();
					}
					//Added By Pankaj T. on 18-06-18 for device security based on enterprise level [0-disabled, 1-strictly enforced, 2-OTP, 3-workflow invoked] - End
					else if( xmlInfo.equals( "true" ) ) //$NON-NLS-1$
					{
                        //Added By Pankaj T. on 28-09-2020 shown different messages, for the cases of session timeout, session terminated and no session available when accessing application - start
                        InetAddress inetAddress;
                        inetAddress = InetAddress.getLocalHost();
                        String hostName = inetAddress.getHostName();
                        String hostIP = inetAddress.getHostAddress();
                        String authenticatedIP = "";
                        if( hostIP != null && hostIP.indexOf(".") != -1 )
                        {
                            authenticatedIP = hostIP.substring( hostIP.lastIndexOf(".") + 1 );
                        }
                        BaseLogger.log("3",null,null,"AuthenticateServlet hostIP : ["+ hostIP +"]");
                        BaseLogger.log("3",null,null,"AuthenticateServlet authenticatedIP : ["+ authenticatedIP +"]");
                        Cookie cookie = new Cookie("authenticatedIP", authenticatedIP);
                        //Added by Pankaj T. on 07-01-2022 for removing vulnerability set httponly and secure flag for cookie - start
                        //cookie.setPath("; HttpOnly;");
                        //cookie.setSecure(true);
                        //Added by Pankaj T. on 07-01-2022 for removing vulnerability set httponly and secure flag for cookie - end
                        response.addCookie(cookie);
                        //Added By Pankaj T. on 28-09-2020 shown different messages, for the cases of session timeout, session terminated and no session available when accessing application - end
                        
                        //Added by sunny soni for adding userName cookie in session on 15-02-2022 Start
                        BaseLogger.log("3",null,null,"line no 1688 AuthenticateServlet loginUserID : ["+ loginUserID +"]");
                        Cookie userNamecookie = new Cookie("userName", loginUserID);
                        response.addCookie(userNamecookie);
                        //Added by sunny soni for adding userName cookie in session on 15-02-2022 End
						//Changed by Rupali [for mobile login].Start
						//RequestDispatcher reqDis = request.getRequestDispatcher( "/jsp/Welcome.jsp" );
						//reqDis.forward( request, response );
						//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]start
						//Added By Mahesh Patidar on 27/JUN/13 [to resolve page redirection issue according login mode which is used in welcome page]
						//Added by Sandesh on 11/04/2017 [For Authentication API: Improper Error handling] Start
						loginMode = loginMode != null ? loginMode : "RIA Lite";
						//Added by Sandesh on 11/04/2017 [For Authentication API: Improper Error handling] End
						request.getSession().setAttribute("LOGINMODE",loginMode);
						if( loginClient != null && loginClient.equalsIgnoreCase("TABPC") ){ //$NON-NLS-1$
							RequestDispatcher reqDis = request.getRequestDispatcher( "/ME/ME12GWT.jsp" ); //$NON-NLS-1$
							reqDis.forward( request, response );
						}
						//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]end
						else if( loginMode != null && loginMode.equalsIgnoreCase("MOBILE") ){ //$NON-NLS-1$
							RequestDispatcher reqDis = request.getRequestDispatcher( "/mobile/jsp/MobileMenu.html" ); //$NON-NLS-1$
							reqDis.forward( request, response );
						}
						//Changed by Sandesh on 29/11/2016 [For Authentication API] Start
						else if (isAUTHAPI.equalsIgnoreCase("true") && applicationBean != null && E12GenericUtility.checkNull(applicationBean.getActive()).equalsIgnoreCase("T") )
						{
							String userCode = request.getParameter( "USER" );
							redirectToURL(userCode, response, request);
						}
						else if (isAUTHAPI.equalsIgnoreCase("true") && applicationBean != null  && !E12GenericUtility.checkNull(applicationBean.getActive()).equalsIgnoreCase("T"))
						{
							HttpSession session = request.getSession(false);
							if (session != null)
								session.setAttribute( "USER_INFO", null );

							//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
							responseStr = "alert('"+Messages.getString("AuthenticateServlet_InAccessibleSite",getUserLangAndCountry(loginUserID))+"');window.location.href = '"+href+"';";
							//Changed by Sandesh on 05/12/2016 [For Authentication API] End

							responseStr = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>"+responseStr+"</SCRIPT></HEAD></HTML>";
							response.setBufferSize(responseStr.length());

							BaseLogger.log("3",null,null,"writeReponse    responseString    " + responseStr);
							response.setBufferSize(responseStr.length());
					        response.setContentType( "text/html; charset=UTF8,"+CommonConstants.ENCODING );

							OutputStream outputStream = response.getOutputStream();
							outputStream.write(responseStr.getBytes());
							outputStream.flush();
							outputStream.close();
						}
						//Changed by Sandesh on 29/11/2016 [For Authentication API] End
						else{
							RequestDispatcher reqDis = request.getRequestDispatcher( "/jsp/Welcome.jsp" ); //$NON-NLS-1$
							reqDis.forward( request, response );
						}
						//Changed by Rupali [for mobile login].End
					}
					else if( xmlInfo.equals( "false" ) ) //$NON-NLS-1$
					{

					}
					//Added By Mahesh Patidar on 08/MAR/13[WI2LSUN001 || to show message for only single user is allowed from one client]
					else if(xmlInfo.equals("UserSessionExist"))
					{
						//Changed By Mahesh Patidar on 06-SEP-13 [to redirect back to login.jsp if callerPage is JSP]
						// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
						//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
						String responseString  = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_SingleUserAllowed",getUserLangAndCountry(request.getParameter("USER")) )+"');window.location.href = '"+href+"'</SCRIPT></HEAD></HTML>";
						//Changed by Sandesh on 05/12/2016 [For Authentication API] End
						/*if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
						{
							// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
							responseString = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('"+Messages.getString("AuthenticateServlet_SingleUserAllowed",getUserLangAndCountry(request.getParameter("USER")) )+"');window.location.href = '/ibase/jsp/login.jsp'</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						}*/
						//Ended By Mahesh Patidar on 06-SEP-13 [to redirect back to login.jsp if callerPage is JSP]
						BaseLogger.log("3",null,null,"writeReponse    responseString    " + responseString);
						response.setBufferSize(responseString.length());
						//Added by Dnyaneshwar Chavan on 24-OCT-13 [CO3ASUN005] [ Resolved the issue of when response in Russian language or etc.  ] START
						//response.setContentType("text/html");
				        response.setContentType( "text/html; charset=UTF8,"+CommonConstants.ENCODING );
				        //Added by Dnyaneshwar Chavan on 24-OCT-13 [CO3ASUN005] [ Resolved the issue of when response in Russian language or etc.  ] END

						OutputStream outputStream = response.getOutputStream();
						outputStream.write(responseString.getBytes());
						outputStream.flush();
						outputStream.close();
					}
					//Ended By Mahesh Patidar
					else
					{
                        //Added By Pankaj T. on 26-09-2020 shown different messages, for the cases of session timeout, session terminated and no session available when accessing application - start
                        InetAddress inetAddress;
                        inetAddress = InetAddress.getLocalHost();
                        String hostName = inetAddress.getHostName();
                        String hostIP = inetAddress.getHostAddress();
                        String authenticatedIP = "";
                        if( hostIP != null && hostIP.indexOf(".") != -1 )
                        {
                            authenticatedIP = hostIP.substring( hostIP.lastIndexOf(".") + 1 );
                        }
                        BaseLogger.log("3",null,null,"AuthenticateServlet authenticatedIP : ["+ authenticatedIP +"]");
                        Cookie cookie = new Cookie("authenticatedIP", authenticatedIP);
                        //Added by Pankaj T. on 07-01-2022 for removing vulnerability set httponly and secure flag for cookie - start
                        //cookie.setPath("; HttpOnly;");
                        //cookie.setSecure(true);
                        //Added by Pankaj T. on 07-01-2022 for removing vulnerability set httponly and secure flag for cookie - end
                        response.addCookie(cookie);
                        //Added By Pankaj T. on 26-09-2020 shown different messages, for the cases of session timeout, session terminated and no session available when accessing application - end
                        //Added by sunny soni for adding userName cookie in session on 15-02-2022 Start
                        BaseLogger.log("3",null,null,"1797*** AuthenticateServlet loginUserID : ["+ loginUserID +"]");
                        Cookie userNamecookie = new Cookie("userName", loginUserID);
                        response.addCookie(userNamecookie);
                        //Added by sunny soni for adding userName cookie in session on 15-02-2022 End

						//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To pass targetCustomer
						//generateResponse( request, response, xmlInfo );
//						generateResponse( request, response, xmlInfo,targetCustomer );
						//Changed by Sandeep S. on 19-JAN-17 [To check session exist or not for same user on same or on another machine] Start
						//generateResponse( request, response, xmlInfo, "" );
						String sameUserSession = null;
						if( request.getSession().getAttribute("SameUserSessionExist") != null )
						{
							sameUserSession = (String)request.getSession().getAttribute("SameUserSessionExist");
							BaseLogger.log("3",null,null,"\n sameUserSession "+sameUserSession);
							if( sameUserSession != null && "true".equalsIgnoreCase(sameUserSession) )
							{
								generateResponse( request, response, xmlInfo, "" ,true);
							}
							else
							{
								generateResponse( request, response, xmlInfo, "" ,false);
							}
						}
						else
						{
							generateResponse( request, response, xmlInfo, "" ,false);
						}
						//Changed by Sandeep S. on 19-JAN-17 [To check session exist or not for same user on same or on another machine] End
					}

					//Added by Pravin K on 12-JAN-19 [Add user in system_support group if not present] START
					UserInfoBean userInfo  = (ibase.utility.UserInfoBean)request.getSession().getAttribute("USER_INFO");
					if(userInfo != null)
					{
						SocialEntEJB socialEntEJB = new SocialEntEJB();
						BaseLogger.log("3",null,null,"Inside MELogin action response str ==>  userInfo.getLoginCode() : "+userInfo.getLoginCode());
						socialEntEJB.createSystemSupportGroup(userInfo, userInfo.getLoginCode()  );
					}
					//Added by Pravin K on 12-JAN-19 [Add user in system_support group if not present] END
				}
			}
		}
		catch( BaseException be )
		{
			isError = true;//Gulzar on 30/01/15
			be.printStackTrace();
			BaseLogger.log("0",null,null, "BaseException: doPost 1 :==>\n"+be ); //$NON-NLS-1$
			try
			{
				// Changed by Sandesh Shinde on 17-MAY-2017 [ Authentication API: Improper Error handling] Start
				PrintWriter writer = response.getWriter();
				//Added by Dnyaneshwar Chavan on 24-OCT-13 [CO3ASUN005] [ Resolved the issue of when response in Russian language or etc.  ] START
				//response.setContentType("text/html"); //$NON-NLS-1$
      		    response.setContentType( "text/html; charset="+CommonConstants.ENCODING );
		        //Added by Dnyaneshwar Chavan on 24-OCT-13 [CO3ASUN005] [ Resolved the issue of when response in Russian language or etc.  ] END
				if("MELOGIN".equals(action) || "VERIFY_USER_DEVICE".equals(action))
				{
					//Added by Bhupendra M for on click login button user was not getting any proper indication of any exception occurs Start
					String errMsg = "<?xml version='1.0' encoding='"+CommonConstants.ENCODING+"'?>"+be.getMessage()+"</xml>";
					response.setContentLength(errMsg.length());
					writer.println(errMsg);
					writer.flush();
					writer.close();
					//Added by Bhupendra M for on click login button user was not getting any proper indication of any exception occurs End
				}
				else
				{
                    //Added By Pankaj T on 15-09-2020 display system exception message if in authentication execption  occur - start
                    String exceMsg = "";
                    RequestDispatcher dispatcher =  request.getRequestDispatcher("/jsp/BaseError.jsp");
                    if( be.getMessage() != null && be.getMessage().contains("System Exception") )
                    {
                        Document document = new E12GenericUtility().getDocument(be.getMessage());
                        if( document != null )
                        {
                            Node msgDescrNode = document.getElementsByTagName( "description" ).item(0);
                            if( msgDescrNode != null && msgDescrNode.getFirstChild() != null && msgDescrNode.getFirstChild().getNodeValue() != null )
                            {
                                exceMsg = msgDescrNode.getFirstChild().getNodeValue();
                            }
                        }
                    }
                    //Added By Pankaj T on 15-09-2020 display system exception message if in authentication execption  occur - end
                    else
                    {
                        String fileName = E12GenericUtility.updateLog(be.getMessage(), "" , "");
                        // Default error message to display.
                        String defaultMsg ="An exception ~ has been generated. Please contact administrator.";
                        //String exceMsg = "";
                        //RequestDispatcher dispatcher =  request.getRequestDispatcher("/jsp/BaseError.jsp");
                        // Get error message from messages table.
                        ibase.utility.UserInfoBean userInfo = (ibase.utility.UserInfoBean)request.getSession().getAttribute("USER_INFO");
                        exceMsg = getCommonDBAccess().getExceptionMsg("E12EXCPMSG", userInfo);

                        exceMsg = E12GenericUtility.checkNull(exceMsg).length() > 0 ?  exceMsg : defaultMsg;

                        exceMsg = exceMsg.replace("~", "(" +fileName +")");
                    }
					request.setAttribute("errorMsg", exceMsg);
					dispatcher.forward(request, response);
				}
//				response.setContentLength(errMsg.length());
//				writer.println(errMsg);
//				writer.flush();
//				writer.close();
				// Changed by Sandesh Shinde on 17-MAY-2017 [ Authentication API: Improper Error handling] End
			}
			catch( Exception ex )
			{
				BaseLogger.log("0",null,null,"Exception: doPost:==>in writing response from BaseException\n"+ex); //$NON-NLS-1$
				ex.printStackTrace();
			}
		}
		catch(Exception e)
		{
			isError = true;//Gulzar on 30/01/15

			e.printStackTrace();
			BaseLogger.log("0",null,null,"Exception: doPost:==>\n"+e); //$NON-NLS-1$
			try
			{
				PrintWriter writer = response.getWriter();

				//Added by Dnyaneshwar Chavan on 24-OCT-13 [CO3ASUN005] [ Resolved the issue of when response in Russian language or etc.  ] START
				//response.setContentType("text/html"); //$NON-NLS-1$
		        response.setContentType( "text/html; charset="+CommonConstants.ENCODING );
		        //Added by Dnyaneshwar Chavan on 24-OCT-13 [CO3ASUN005] [ Resolved the issue of when response in Russian language or etc.  ] END

		        //Commented By Pankaj T. on 14-07-2020 for removing vulnerability of Improper Error Handling - start
		        //ByteArrayOutputStream baos = new ByteArrayOutputStream();
				//e.printStackTrace(new PrintStream(baos));
				//response.setContentLength(baos.toString().length());
				//writer.println(baos.toString());
				//writer.flush();
				//writer.close();
				//baos.close();
		        //Commented By Pankaj T. on 14-07-2020 for removing vulnerability of Improper Error Handling - end
		        
		        //Added By Pankaj T. on 14-07-2020 for removing vulnerability of Improper Error Handling - start
		        E12GenericUtility genericUtility = new E12GenericUtility();
				String errMsg = genericUtility.createErrorString(e);
				BaseLogger.log("0",null,null,"AuthenticateServlet.doPost() Exception :["+errMsg+"]");
				if("MELOGIN".equals(action) || "VERIFY_USER_DEVICE".equals(action))
				{
					response.setContentLength(errMsg.length());
					writer.println(errMsg);
					writer.flush();
					writer.close();
				}
				else
				{
                    //Added By Pankaj T on 15-09-2020 display system exception message if in authentication execption  occur - start
                    String exceMsg = "";
                    RequestDispatcher dispatcher =  request.getRequestDispatcher("/jsp/BaseError.jsp");
                    if( errMsg != null && errMsg.contains("System Exception") )
                    {
                        Document document = new E12GenericUtility().getDocument( errMsg );
                        if( document != null )
                        {
                            Node msgDescrNode = document.getElementsByTagName( "description" ).item(0);
                            if( msgDescrNode != null && msgDescrNode.getFirstChild() != null && msgDescrNode.getFirstChild().getNodeValue() != null )
                            {
                                exceMsg = msgDescrNode.getFirstChild().getNodeValue();
                            }
                        }
                    }
                    //Added By Pankaj T on 15-09-2020 display system exception message if in authentication execption  occur - end
                    else
                    {
                        String fileName = E12GenericUtility.updateLog(errMsg, "" , "");
                        // Default error message to display.
                        String defaultMsg ="An exception ~ has been generated. Please contact administrator.";
                        //String exceMsg = "";
                        //RequestDispatcher dispatcher =  request.getRequestDispatcher("/jsp/BaseError.jsp");
                        // Get error message from messages table.
                        ibase.utility.UserInfoBean userInfo = (ibase.utility.UserInfoBean)request.getSession().getAttribute("USER_INFO");
                        exceMsg = getCommonDBAccess().getExceptionMsg("E12EXCPMSG", userInfo);
                        exceMsg = E12GenericUtility.checkNull(exceMsg).length() > 0 ?  exceMsg : defaultMsg;
                        exceMsg = exceMsg.replace("~", "(" +fileName +")");
                    }
					request.setAttribute("errorMsg", exceMsg);
					dispatcher.forward(request, response);
				}
				//Added By Pankaj T. on 14-07-2020 for removing vulnerability of Improper Error Handling - end
			}
			catch(Exception ex)
			{
				BaseLogger.log("0",null,null,"Exception: doPost:==>in writing response from Exception\n"+ex); //$NON-NLS-1$
				ex.printStackTrace();
			}
		}
		//Finally block is added by Gulzar on 30/01/15 to invalidate and update the login trace if any exception occurs
		finally
		{
			try
			{
				BaseLogger.log("3",null,null,"AuthenticateServlet >> finally >> isError =["+isError+"]");
				if(isError)
				{
					HttpSession sessObj = request.getSession(false);
					if(sessObj != null)
					{
						BaseLogger.log("3",null,null,"AuthenticateServlet >> Invalidating the session and updating the logintrace............::"+request.getParameter("USER"));
						sessObj.invalidate();
						getCommonDBAccess().updateLoginTrace(""+request.getParameter("USER"), sessObj.getId());
					}
				}
			}
			catch(Exception e1)
			{
				e1.printStackTrace();
			}
		}
	}

	protected String authenticate( HttpServletRequest request ) throws BaseException, IOException
	{
		//Uncommented by Sandeep S. on 16-APR-18 [If request received from login page then it must revalidate] Start
		/* Chnaged by Prasad on 28/02/18
		 * [to resolve login issue - one user login and close the window and again login from another user, previous user login appear]
		 * START */
		//Changed by Gulzar on 30/01/15 : START
		//HttpSession sessObj = request.getSession(false);
		HttpSession sessObj = null;
		String referrer = E12GenericUtility.checkNull( request.getHeader( "referer" ) );
        BaseLogger.log("2",null,null, "authenticate - referrer - ["+ referrer +"]" );
        //Added By Pankaj T on 15-09-2020 handle login related issue of invalid session and display alert to user for clearing browser cache - start
        try
        {
            if ( referrer.indexOf( "/ibase/login/index.html" ) != -1 )
            {
                sessObj = request.getSession( false );
                //Added By Pankaj T. on 21-09-2020  resolved issue of invalid session after after 2nd login - start
                if ( sessObj != null )
                {
                    UserInfoBean userInfoBean = ( ibase.utility.UserInfoBean )sessObj.getAttribute( "USER_INFO" );
                    BaseLogger.log("3",null,null, "Invalidate session in authenticate userInfoBean : ["+userInfoBean+"]" );
                    if( userInfoBean != null )
                    {
                        sessObj.invalidate();
                        BaseLogger.log("3",null,null, "Invalidate session in authenticate" );
                        sessObj = request.getSession( true );
                    }
                }
                //Added By Pankaj T. on 21-09-2020  resolved issue of invalid session after after 2nd login - start
            }
            else
            {
                sessObj = request.getSession( false );
            }
        }
        catch( Exception e )
        {
            BaseLogger.log("2",null,null, "In authenticate() Exception in creating session ["+ E12GenericUtility.getStackTrace(e) +"]" );
            return "INVALID_SESSION";
        }
        //Added By Pankaj T on 15-09-2020 handle login related issue of invalid session and display alert to user for clearing browser cache - end
		/* Chnaged by Prasad on 28/02/18
		 * [to resolve login issue - one user login and close the window and again login from another user, previous user login appear]
		 * END */
		//Uncommented by Sandeep S. on 16-APR-18 [If request received from login page then it must revalidate] End
		ibase.utility.UserInfoBean userInfo = null;
		//Changed by Gulzar on 30/01/15 : END

		//Added by Prajyot On 17MAY2013 [For Encoding issue on Russian Server]
		request.setCharacterEncoding( CommonConstants.ENCODING );

		BaseLogger.log("3",null,null,"Called AuthenticateServlet authentication....."); //$NON-NLS-1$

		//Commented ,changed and moved below by Gulzar on 30/01/15 : START
		//Purpose: to create the new session only after successful authentication not in this state
		/*
		//Added by gayatri [to identify the request from rcp]start
		if("true".equals(request.getAttribute("isReqFromRcp")))
		{
			request.getSession().setAttribute( "IS_EMP_INFO_SET", "true" );
		}
		//Added by gayatri [to identify the request from rcp]end
		 */

		//Commented and moved below by Gulzar on 30/01/15 : END

		String authenticationStatus = "false"; //$NON-NLS-1$
		try
		{
			//CommonConstants.setAPPLICATION_CONTEXT( getServletContext().getRealPath("/"));
			//Danish on 13-JUL-2010 [ SY90SUN004 ]
			// Changed by Hrusikesh on 13-Nov-2010 [WI01SUN015 ||  to upload excel sheet data for auto-generated PK value] Start.
			if( this.servletContext != null )
			{
				BaseLogger.log("3",null,null,"AuthenticateServlet::this.servletContext.getRealPath(/)["+this.servletContext.getRealPath("/")+"]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
				CommonConstants.setAPPLICATION_CONTEXT(this.servletContext.getRealPath("/")); //$NON-NLS-1$
			}
			// Changed by Hrusikesh on 13-Nov-2010 [WI01SUN015] If PK is auto then it should pick up all the details tables data against the PK generated for the header.
			//String userCode = request.getParameter( "USER" ); //$NON-NLS-1$

			String userCode = "";

			if( request.getParameter( "USER" ) != null )
			{
				userCode = getDecodedStr( new String( request.getParameter( "USER" )));
			}

			userCode = ( "null".equalsIgnoreCase( userCode ) || "".equalsIgnoreCase( userCode ) ) ? null : userCode; //$NON-NLS-1$ //$NON-NLS-2$
			BaseLogger.log("3",null,null,"userCode: [" + userCode +"]");
			//Commented and changed by Gulzar on 30/01/15 : START
			//Get the USER_INFO value from existing session and not to create new session now
			//and will create later after successful authentication
			//ibase.utility.UserInfoBean userInfo = ( ibase.utility.UserInfoBean )request.getSession().getAttribute( "USER_INFO" ); //$NON-NLS-1$
			if( sessObj != null )
			{
                //Added By Pankaj T on 15-09-2020 handle login related issue of invalid session and display alert to user for clearing browser cache - start
                try
                {
                    userInfo = ( ibase.utility.UserInfoBean )sessObj.getAttribute( "USER_INFO" ); //$NON-NLS-1$
                }
                catch( Exception e )
                {
                    BaseLogger.log("2",null,null, "In authenticate() Exception in getting attribute from session ["+ E12GenericUtility.getStackTrace(e) +"]" );
                    return "INVALID_SESSION";
                }
                //Added By Pankaj T on 15-09-2020 handle login related issue of invalid session and display alert to user for clearing browser cache - end
				//Added by Abhishek on 22/01/18 [to resolve authentication issue in documentHandlerServlet] START
				if ( userInfo != null && userCode == null )
				{
					userCode = userInfo.getLoginCode();
					BaseLogger.log("3",null,null,"loginID from session: [" + userInfo.getLoginCode()+"]");
				}
				//Added by Abhishek on 22/01/18 [to resolve authentication issue in documentHandlerServlet] END
				//Added by Pankaj T on 07-03-18 [to invalidate session when enter loginId & session loginId is mismatch] - Start
				else if( userInfo != null && userCode != null && !(userCode.equals(userInfo.getLoginCode())) )
				{
					sessObj.invalidate();
				    BaseLogger.log("3",null,null, "Invalidate session in authenticate if userId mismatch" );
				    sessObj = request.getSession( true );
				    userInfo = null;
				}
				//Added by Pankaj T on 07-03-18 [to invalidate session when enter loginId & session loginId is mismatch] - End
			}
			//Commented and changed by Gulzar on 30/01/15 : END
			/*
			Cases		userCode		userInfo
			Case 1:		null				null
			Case 2:		not null			null
			Case 3:		null				not null
			Case 4:		not null			not null
			*/
			boolean toAuthenticate = false;
			if( userCode == null && userInfo == null )
			{
				BaseLogger.log("3",null,null, "throwing new Exception( INVALID_ACCESS )" ); //$NON-NLS-1$
				//change by shrutika on 19-12-2020 for Exception in application start
				//throw new BaseException( new Exception( "INVALID_ACCESS" ) ); //$NON-NLS-1$
                ITMDBAccessEJB itmDbAccess = new ITMDBAccessEJB();
                return itmDbAccess.getErrorString("","SESSIONOUT"," ", userInfo);
        		//change by shrutika on 19-12-2020 for Exception in application end
            }
			else if( userCode != null && userInfo == null )
			{
				BaseLogger.log("3",null,null,"UserCode is not null...");
				toAuthenticate = true;
				//Changed by Sandeep S. on 19-JAN-17 [To check session exist or not for same user on same or on another machine] Start
				if( isSessionExist(request, userCode) )
				{
					toAuthenticate = true;
					//authenticationStatus = "SameUserSessionExist";
					request.getSession().setAttribute("SameUserSessionExist", "true");
				}
				//Changed by Sandeep S. on 19-JAN-17 [To check session exist or not for same user on same or on another machine] End
			}
			else if( userCode == null && userInfo != null )
			{
				BaseLogger.log("3",null,null,"UserInfo is not null...");
				authenticationStatus = "true"; //$NON-NLS-1$
				//Changed by Sandeep S. on 19-JAN-17 [To check session exist or not for same user on same or on another machine] Start
				if( isSessionExist(request, userCode) )
				{
					toAuthenticate = true;
					//authenticationStatus = "SameUserSessionExist";
					request.getSession().setAttribute("SameUserSessionExist", "true");
				}
				//Changed by Sandeep S. on 19-JAN-17 [To check session exist or not for same user on same or on another machine] End
			}
			else if( userCode != null && userInfo != null )
			{
				BaseLogger.log("3",null,null,"UserCode and UserInfo both are not null...");
				//Changed By Mahesh Patidar on 08/MAR/13[WI2LSUN001 || to change condition for only single user is allowed from one client]
//				if( ! userCode.equals( userInfo.getLoginCode() ) )
//				{
//					toAuthenticate = true;
//				}
//				else
//				{
//					authenticationStatus = "true"; //$NON-NLS-1$
//				}
				if( userCode.equals( userInfo.getLoginCode() ) )
				{
					authenticationStatus = "true";
				}
				/*else if( isSessionExist(request, userCode) )
				{
					//authenticationStatus = "SameUserSessionExist";
					request.getSession().setAttribute("SameUserSessionExist", "true");
				}*/
				else
				{
					authenticationStatus = "UserSessionExist";
				}
				//Ended By Mahesh Patidar
			}
			//BaseLogger.log("9",null,null, "AuthenticateServlet authenticationStatus :["+authenticationStatus+"] toAuthenticate :["+toAuthenticate+"]" );
			//Added by Ajinkya Gopalkar on 6-Jan-16[For insert geo position after authenticate]
			String deviceUuId = request.getParameter( "DEVICEUUID" );
			if( toAuthenticate )
			{
				// Updated By Saitej D on 21 Nov 2018 [To Check Server License] START
				String remoteHost = request.getHeader("Host");// 192.168.0.231 or test.base231.com
				int portIndex = remoteHost.indexOf(":");
				if( portIndex != -1 )
				{
					remoteHost = remoteHost.substring(0, portIndex);
				}
				BaseLogger.log("3",userInfo,null,"get local host getLocalName "+request.getHeader("Host")+"   "+request.getHeaderNames());

				//Commented by Prajyot on 16-APR-19 [ As Server License validation is not required ] Start
				/*
				//Temporarily commented by [Saitej D] on 26Dec18 START
				//boolean isSerLicUser = getCommonDBAccess().checkServerLicence( userCode, remoteHost );
				boolean isSerLicUser = true;
				//Temporarily commented by [Saitej D] on 26Dec18 END

				BaseLogger.log("2",null,null,"isSerLicUser...["+isSerLicUser+"]");

				if( !isSerLicUser )
				{
					StringBuffer statusBuf = new StringBuffer();
					statusBuf.append("<Root>");
					statusBuf.append("<STATUS><![CDATA[false]]></STATUS>");
					statusBuf.append("<STATUS_CODE><![CDATA[INVALID_LICENCE]]></STATUS_CODE>");
					statusBuf.append("</Root>");
					return statusBuf.toString();
				}
				// Updated By Saitej D on 21 Nov 2018 [To Check Server License] END
				*/
				//Commented by Prajyot on 16-APR-19 [ As Server License validation is not required ] End

				//added by vishal pathare on 18.6.18 for[users licence related validation]Start
				/*boolean isLicUser = getCommonDBAccess().checkUserLicence( userCode );
				BaseLogger.log("3",userInfo,null,"Inside authenticate survlet else isLicUser "+isLicUser);
				if( !isLicUser )
				{
					BaseLogger.log("3",userInfo,null,"Inside authenticate survlet else isLicUser inside ");
					StringBuffer statusBuf = new StringBuffer();
					statusBuf.append("<Root>");
					statusBuf.append("<STATUS><![CDATA[false]]></STATUS>");
					statusBuf.append("<STATUS_CODE><![CDATA[INVALID_LICENCE]]></STATUS_CODE>");
					statusBuf.append("</Root>");
					BaseLogger.log("3",userInfo,null,"Inside authenticate survlet else statusBuf "+statusBuf);
					return statusBuf.toString();
				}*/
				//added by vishal pathare on 18.6.18 for[users licence related validation]END

				String password = request.getParameter( "PASSWORD" ); //$NON-NLS-1$
				String siteCode = request.getParameter( "SITE_CODE" ); //$NON-NLS-1$
				String authMode = request.getParameter( "AUTH_MODE" ); //$NON-NLS-1$
				String loginCode1 = request.getParameter( "loginMode" ); //$NON-NLS-1$
				//Changed by Gayatri Yadav on 16-Sept-2010 [ WI01SUN006 ] [ To implement SHA-256 while login ]
				String isSHA256Appld= request.getParameter( "isSHA256Appld" ); //$NON-NLS-1$
				//Change By Nilesh on 21-Mar-2011 [MF01SUN037][To add machine name into logintrace]Start
				String remoteHostName = request.getParameter("MACHINENAME"); //$NON-NLS-1$
				//Added by Dnyaneshwar Chavan on 02-OCT-13 [WS3GSUN002]  [ Device ID & type store in LoginTrace table ] START
				String deviceType = E12GenericUtility.checkNull(request.getParameter( "DEVICETYPE" ));

//				String deviceUuId = request.getParameter( "DEVICEUUID" );
				//Added by Dnyaneshwar Chavan on 02-OCT-13 [WS3GSUN002] [ Device ID & type store in LoginTrace table ] END
				//Added by Dnyaneshwar Chavan on 29-Apr-15 [Implement Push Notification in E12MOBILE] Start
				String deviceId = request.getParameter( "DEVICEID" );

				String active = request.getParameter( "ACTIVE" );
				String deviceOS = request.getParameter( "DEVICEOS" );
				//Added by Dnyaneshwar Chavan on 29-Apr-15 [Implement Push Notification in E12MOBILE] End
				// Changed and Added by Pankaj R on 20-JAN-18
				String batteryStatus = request.getParameter("BATTERY_STATUS");
				String appName = request.getParameter("APP_NAME");
				String appVersion = request.getParameter("CURRENTAPKVERSION");
				String action = E12GenericUtility.checkNull(request.getParameter("action"));
				BaseLogger.log("3",null,null,"action @@:: ["+action+"]");
				String deviceIMEINo = request.getParameter("IMEI_NO");
				BaseLogger.log("3",null,null,"IMEI_NO @@:: ["+deviceIMEINo+"]");
                // Changed and Added by Pankaj R on 20-JAN-18
                //Added by sunny soni for set device appId on 04-FEB-21 [Start]
				String deviceAppID = request.getParameter("DEVICE_APP_ID");
				deviceAppID = E12GenericUtility.checkNull(deviceAppID);
				BaseLogger.log("3",null,null,"device AppID -::- ["+deviceAppID+"]");
				if (deviceAppID != null && deviceAppID.trim().length() > 0) {					
					CommonConstants.DEVICE_APP_ID = deviceAppID;
				}
				//Added by sunny soni for set device appId on 04-FEB-21 [End]
				if( remoteHostName != null && remoteHostName.length() > 60 )
				{
					remoteHostName = remoteHostName.substring( 0, 60 );
				}
				else if ( remoteHostName == null || remoteHostName.length() == 0 )
				{
					remoteHostName = ""; //$NON-NLS-1$
				}
				//String chgIP = request.getRemoteAddr();
				//Changed By Pankaj T. on 21-05-2021 for getting actual client ip in case of load balancer - start
				String chgIP = request.getHeader("X-Forwarded-For");
				BaseLogger.log("3",null,null,"X-Forwarded-For : ["+chgIP+"]");
				if(chgIP == null)
				{  
					chgIP = request.getRemoteAddr();
				}
				//Changed By Pankaj T. on 21-05-2021 for getting actual client ip in case of load balancer - end
				BaseLogger.log("3",null,null,"Remote Address:["+chgIP+"]");
				//changed by gayatri on [ 25-08-2011][to add mac id in security feature]
				String macIds[] ={ request.getParameter("macAddress"),request.getParameter("macAddressAddnl")}  ; //$NON-NLS-1$ //$NON-NLS-2$
				// Changed and Added by Pankaj R on 20-JAN-18
				String reqHeader = request.getHeader("User-Agent");
				HashMap<String, String> hashMap = getDeviceDetail(reqHeader, appName, appVersion);
				BrowserDetail browserDetail = new BrowserDetail(hashMap);
				// Changed and Added by Pankaj R on 20-JAN-18
				//Change By Nilesh on 21-Mar-2011 [MF01SUN037][To add machine name into logintrace]End
				//BaseLogger.log("9",null,null,"Authenticating Requestor for userCode ["+userCode+"] siteCode ["+siteCode+"] loginmode ["+loginCode1+"] isSHA256Appld ["+isSHA256Appld+"]");

				//Changed by Gayatri Yadav on 16-Sept-2010 [ WI01SUN006 ] [ To implement SHA-256 while login ]
				//authenticationStatus = getCommonDBAccess().authenticate( userCode, password, siteCode, authMode );

				//Changed by Gayatri Yadav on 18-Aug2011 [ CR1DPOL001 ] [To add mac address in users table ]
				//authenticationStatus = getCommonDBAccess().authenticate( userCode, password, siteCode, authMode, isSHA256Appld );
				//authenticationStatus = getCommonDBAccess().authenticate( userCode, password, siteCode, authMode, isSHA256Appld ,macIds );
				//Added By Pankaj T. on 18-11--2020 for removing weak account lock vulnerability - if user wrongly enter password more than 5 times then lock the account and send new password on email/mobile and unlock account using new password
				authenticationStatus = getCommonDBAccess().authenticate( userCode, password, siteCode, authMode, isSHA256Appld , macIds, action, request );		//Added action parameter by Sagar B. on[13-May-19]
				request.getSession().setAttribute("AUTH_STATUS", authenticationStatus);
				BaseLogger.log("3",null,null,"authenticationStatus ["+authenticationStatus+"]");
				//Added by Dnyaneshwar Chavan on 15-JAN-15  [ Host name & IP store in LoginTrace table ] START
				String hostName="", hostIP="";
				InetAddress inetAddress;
				inetAddress = InetAddress.getLocalHost();
				hostName = inetAddress.getHostName();
				hostIP = inetAddress.getHostAddress();
				//Added by Dnyaneshwar Chavan on 15-JAN-15  [ Host name & IP store in LoginTrace table ] End
				//Changed by Manish on 07/11/2006 to hold login status in a variable to later update login trace on this basis.
				boolean isValidLogin = getAuthenticationStatus( authenticationStatus );
				if( isValidLogin )
				{
					//added by vishal pathare on 18.6.18 for[users licence related validation]Start
					boolean isLicUser = getCommonDBAccess().checkUserLicence( userCode );
					BaseLogger.log("3",userInfo,null,"Inside authenticate survlet else isLicUser "+isLicUser);
					if( !isLicUser )
					{
						BaseLogger.log("3",userInfo,null,"Inside authenticate survlet else isLicUser inside ");
						StringBuffer statusBuf = new StringBuffer();
						statusBuf.append("<Root>");
						statusBuf.append("<STATUS><![CDATA[false]]></STATUS>");
						statusBuf.append("<STATUS_CODE><![CDATA[INVALID_LICENCE]]></STATUS_CODE>");
						statusBuf.append("</Root>");
						BaseLogger.log("3",userInfo,null,"Inside authenticate survlet else statusBuf "+statusBuf);
						return statusBuf.toString();
					}
					//added by vishal pathare on 18.6.18 for[users licence related validation]END
					
					Document document = new E12GenericUtility().parseString( authenticationStatus );
					userInfo = createUserInfo( userCode, password, document );
					//Added by Sainath on 20/09/18 [set deviceType and deviceId in userInfo] START
					userInfo.setDeviceType(deviceType);
					userInfo.setDeviceID(deviceId);
					//Added by Sainath on 20/09/18 [set deviceType and deviceId in userInfo] END
					//Added by Dnyaneshwar Chavan on 4-Apr-14 [Add timeZone Data member in user info been as per Danish sir  ] Start
					String timeZone = request.getParameter("timeZone");
					if(  timeZone != null && !"null".equalsIgnoreCase( timeZone ) )
					{
						userInfo.setTimeZone( timeZone );
					}
					//Added by Dnyaneshwar Chavan on 4-Apr-14 [Add timeZone Data member in user info been as per Danish sir  ] End

					String clientIP = request.getParameter( "CLIENT_IP" ); //$NON-NLS-1$
					//BaseLogger.log("9",null,null,"authenticate:clientIP["+clientIP+"]");
					//Changed by Dayanand on 06/05/10[ SY89SUN112 || Machine IP is getting updated as �172.16.12.25� in chg_term field from all browser based applications ]start
					if ( clientIP == null || clientIP == "" || clientIP.trim().length() < 0 ) //$NON-NLS-1$
					{
						clientIP = request.getRemoteHost();
					}
					//Changed by Dayanand on 06/05/10[ SY89SUN112 || Machine IP is getting updated as �172.16.12.25� in chg_term field from all browser based applications ]end
					//Change by shrutika on 15-03-19[Start] for to identify the source of entry ie[save value for chg_term as MAC_ADDRESS if browser otherwise deviceIMEINo]
					//change by shrutika on 22-03-19 for issue in MSI related screens..
					userInfo.setRemoteHost( ( clientIP != null && clientIP.trim().length() > 0 && ! "NULL".equalsIgnoreCase( clientIP ) ) ? clientIP : "SYSTEM" ); //$NON-NLS-1$ //$NON-NLS-2$
					/*if( "I".equals( authMode ) )
					{
						String deviceIMEINoBrowser  = request.getParameter("MAC_ADDRESS");
						userInfo.setRemoteHost( ( deviceIMEINoBrowser != null && deviceIMEINoBrowser.trim().length() > 0 && ! "NULL".equalsIgnoreCase( deviceIMEINoBrowser ) ) ? deviceIMEINoBrowser : "SYSTEM" ); //$NON-NLS-1$ //$NON-NLS-2$
					}
					else if( "MELOGIN".equalsIgnoreCase(action))
					{
						userInfo.setRemoteHost( ( deviceIMEINo != null && deviceIMEINo.trim().length() > 0 && ! "NULL".equalsIgnoreCase( deviceIMEINo ) ) ? deviceIMEINo : "SYSTEM" ); //$NON-NLS-1$ //$NON-NLS-2$
					}
					else
					{
						userInfo.setRemoteHost( ( clientIP != null && clientIP.trim().length() > 0 && ! "NULL".equalsIgnoreCase( clientIP ) ) ? clientIP : "SYSTEM" ); //$NON-NLS-1$ //$NON-NLS-2$
					}*/
					//Change by shrutika on 15-03-19[End] for to identify the source of entry ie[save value for chg_term as MAC_ADDRESS if browser otherwise deviceIMEINo]
					BaseLogger.log("3",null,null, "Setting USER_INFO in session....." ); //$NON-NLS-1$
					// Added by Raju K on02-05-14 for Event log and Transaction lock as per danish sir START--
					//changed By Mahesh Patidar on 01/AUG/13[WI3DSUN001|to set session id to userInfo]
					if ( userInfo != null )
					{
						try
						{
							userInfo.setSessionId(request.getSession().getId());
							//Changed by Sandeep S. on 24-JAN-17 [To check session exist or not for same user on same or on another machine] Start
							//String action = E12GenericUtility.checkNull(request.getParameter("action"));
							if("MELOGIN".equalsIgnoreCase(action))
							{
								userInfo.setLogInInterface("Mobile");
							}
							//Changed by Sandeep S. on 24-JAN-17 [To check session exist or not for same user on same or on another machine] Start
						}
						catch(Exception e)
						{
							e.printStackTrace();
						}
					}
					//Ended By Mahesh Patidar on 01/AUG/13[WI3DSUN001|to set session id to userInfo]
					// Ended by Raju K on02-05-14 for Event log and Transaction lock as per danish sir END--
					BaseLogger.log("3",null,null,"After authenticate loginID:["+userCode+"]");
					BaseLogger.log("3",null,null,"After authenticate set userInfo:["+userInfo.toString()+"]");
					request.getSession().setAttribute( "USER_INFO", userInfo ); //$NON-NLS-1$

					String columnName = " PROP_VALUE ";
					String tableName = " PROPERTIES ";
					String condition = " WHERE PROP_NAME='IS_TNC_INITIATED' ";
					String isTNCInitiated = getCommonDBAccess().getDBColumnValue( tableName.trim(), columnName.trim(), condition, userInfo.getTransDB() )  ;
					columnName = null;
					tableName = null;
					condition = null;
					BaseLogger.log("3",null,null," Terms And Condition : IS_TNC_INITIATED ["+ isTNCInitiated +"]");
					request.getSession().setAttribute( "IS_TNC_INITIATED", isTNCInitiated);

					if( ! "I".equals( authMode ) ) //$NON-NLS-1$
					{
						authenticationStatus = "true"; //$NON-NLS-1$
					}
					//changed by rajeshp 12/27/2007 [setting application level info  ].start
					//AppConnectParm appConnect = new AppConnectParm();
					//InitialContext ctx = new InitialContext(appConnect.getProperty());

					//Changed By Rupali Hande on 24/03/08 [Remove dependacy of AuthenticateServlet from webitem].Request ID[BI78SUN047].Start
					//DBAccessHome dbAccessHome = (DBAccessHome) ctx.lookup( "DBAccess" );
					//DBAccessRemote dbAccess = dbAccessHome.create();
					/*CommonDBAccessHome dbAccessHome = (CommonDBAccessHome) ctx.lookup( "CommonDBAccess" );
					CommonDBAccess dbAccess = dbAccessHome.create();*/
					// Commented and Added by Pankaj R on 20-JUL-18 to change calling of EJB to JB [START]
					//CommonDBAccessRemote dbAccess = (CommonDBAccessRemote)ctx.lookup("ibase/CommonDBAccessEJB/remote"); //$NON-NLS-1$
					CommonDBAccessEJB dbAccess = new CommonDBAccessEJB();
					// Commented and Added by Pankaj R on 20-JUL-18 to change calling of EJB to JB [END]
					//Changed By Rupali Hande on 24/03/08 [Remove dependacy of AuthenticateServlet from webitem].Request ID[BI78SUN047].End
					//Added by Nilesh on 18-Mar-2011 [MF01SUN037][To add remote host name into userInfo]
					userInfo.setRemoteHostName( remoteHostName );
					userInfo.setEmpInfo( dbAccess.getEmpInfo( userInfo.getLoginCode(), userInfo.getSiteCode(), userInfo.getTransDB() ) );

					//Commented by Prajyot [To pass UserLanguage and UserCountry as it is which present in USERS table, no need to overwrite it] Starts
					/*
					//Changed by Pramod on 08-01-11[WS01SUN030 || Generating country wise, language wise xsl and reading the same|| Getting user language and country from locale.Keeping in session]starts
					//userInfo.setUserLanguage(request.getLocale().getLanguage());
					//userInfo.setUserCountry(request.getLocale().getCountry());
					//Changed by Pramod on 08-01-11[WS01SUN030 ||Getting user language and country from locale.Keeping in session]ends
					*/
					//Commented by Prajyot [To pass UserLanguage and UserCountry as it is which defined in USERS table no need to overwrite it] Ends
					// Added by Raju K on02-05-14 for Event log and Transaction lock as per danish sir START--
					//Added by Mahesh Patidar on 01/AUG/13[WI3DSUN001|to set session id to userInfo]
					//Added By Pankaj T on 1-Dec-2016 [For Recent Activity related changes]Start
					ApplicationTO.setHostInfo( request.getServerName()+":"+request.getServerPort());
					//Added By Pankaj T on 1-Dec-2016 [For Recent Activity related changes]End
					if ( userInfo != null )
					{
						try
						{
							userInfo.setSessionId(request.getSession().getId());
							userInfo.setHostName( hostName );
							userInfo.setHostIP( hostIP );
						}
						catch(Exception e)
						{
							e.printStackTrace();
						}
					}
					//Added by Dnyaneshwar Chavan on 24-FEB-15 [ if devicetype is null then check the loggin in 'Browser' or 'RCP' and set to device type value  ] Start\
					BaseLogger.log("3",null,null,"P deviceType :: ["+deviceType+"]");
					if( deviceType.length() == 0 )
					{
						String userAgent =  request.getHeader("User-Agent") == null ? "" : request.getHeader("User-Agent");
						if( userAgent.indexOf( "Java" ) != 0 )
						{
							deviceType = "Browser";
						}
						else
						{
							deviceType = "RCP";
						}
					}
					//Added by Dnyaneshwar Chavan on 24-FEB-15 [ if devicetype is null then check the loggin in 'Browser' or 'RCP' and set to device type value  ] End
					//Ended By Mahesh Patidar on 01/AUG/13[WI3DSUN001|to set session id to userInfo]
					// Ended by Raju K on02-05-14 for Event log and Transaction lock as per danish sir END--
					request.getSession().setAttribute( "USER_INFO", userInfo ); //$NON-NLS-1$
					setApplLevelUserInfo(request,hostName, hostIP, deviceType);
					//changed by rajeshp 12/27/2007 [setting application level info ].end
					//Added by Dnyaneshwar Chavan on 29-Apr-15 [Implement Push Notification] Start
					//We will do later
					BaseLogger.log("3",null,null,"Device Maker :: ["+browserDetail.getDeviceMake()+"]");
					//Added By Pankaj T. on 18-06-18 for device security based on enterprise level [0-disabled, 1-strictly enforced, 2-OTP, 3-workflow invoked] - Start
					//if( deviceType != null && !"null".equalsIgnoreCase( deviceType ) )
					if( deviceType.length() > 0 )
					{
						String fromCache = "";
						String currentGeoPos = "";
						if( "I".equals( authMode ) )
						{
							currentGeoPos = E12GenericUtility.checkNull(request.getParameter("CURRENT_GEO_POS"));
							deviceIMEINo = request.getParameter("MAC_ADDRESS");
							deviceId = deviceIMEINo+"_"+userCode+"_"+chgIP+"_"+currentGeoPos;
							//Added by Sainath on 20/09/18 [set deviceId in userInfo] START
							userInfo.setDeviceID(deviceId);
							deviceOS =  System.getProperty("os.name");
							fromCache = E12GenericUtility.checkNull(request.getParameter("FROM_CACHE"));
							action = "BROWSERLOGIN";
						}
						//Added by shrutika [start] on 26-10-18 for display change ip and mac address in audit trail.
						userInfo.setMacAddress(deviceIMEINo);
						userInfo.setRemoteAddress(chgIP);
						//Added by shrutika [end] on 26-10-18 for display change ip and mac address in audit trail.
						//Added by Sainath on 20/09/18 [set deviceType in userInfo] START
						userInfo.setDeviceType(deviceType);
						String status = getCommonDBAccess().insertUserDevice( userCode, deviceId, deviceOS, deviceType, active, userCode, chgIP, browserDetail.getDeviceMake(), deviceIMEINo, false, userInfo.getEnterprise(), action, fromCache, currentGeoPos, userInfo.getTransDB(), userInfo, browserDetail.getOsName(), browserDetail.getOsVersion(), browserDetail.getClientApp(), browserDetail.getClientAppVersion() ); // Changed and Added by Pankaj R on 20-JAN-18
						//Added By Pankaj T. on 14-04-20 to set unique id as a termId in userInfo & this termId in chg_term column - start
						BaseLogger.log( "3", userInfo, null, "AuthenticateServlet.authenticate() user_device status:["+status+"]");
						if( status != null && status.startsWith("true") )
						{
							String[] statusArr = status.split("~~");
							status = "true";
							//Change by shrutika on 17-04-2020[Start] for issue occur while login the E12Mobile.
							if( statusArr.length > 1 )
							{
								userInfo.setTermId(statusArr[1]);
							}
							//Change by shrutika on 17-04-2020[End] for issue occur while login the E12Mobile.
						}
						//Added By Pankaj T. on 14-04-20 to set unique id as a termId in userInfo & this termId in chg_term column - end
						if( "VERIFY_USER_DEVICE".equals(status) )
						{
							String user = request.getParameter("USER");
							BaseLogger.log("3",null,null,"UserCode:["+user+"]");
							String entityCode = getCommonDBAccess().getDBColumnValue("USERS", "ENTITY_CODE", "WHERE CODE = '"+user+"'");
							BaseLogger.log("3",null,null,"EntityCode:["+entityCode+"]");
							int number = 1;
							number = new Random().nextInt(9000) + 1000;
							String verCode = Integer.toString( number );
							BaseLogger.log("3",null,null,"verCode =["+verCode+"]");
							E12SMSComp smsComp = new E12SMSComp();
							String xtraParams = "loginCode=" + user + "~~loginEmpCode" + user;
							String formatCode = "USER_FORMAT";
							StringBuffer valueXmlString = new StringBuffer("<?xml version=\"1.0\" ?><Root><Header></Header><Errors></Errors>");
							valueXmlString.append("<Detail1 objName = 'user_authenticate'>");
							valueXmlString.append("<code><![CDATA[").append(entityCode).append("]]></code>");
							valueXmlString.append("<verfnCode><![CDATA[").append(verCode).append("]]></verfnCode>");
							String userName = E12GenericUtility.checkNull(userInfo.getUserName());
							valueXmlString.append("<name><![CDATA[").append(userName).append("]]></name>");
							valueXmlString.append("</Detail1>");
							valueXmlString.append("</Root>");
							String result = smsComp.sendSMS(valueXmlString.toString(), formatCode, xtraParams, userInfo);
							BaseLogger.log("3",null,null,"Result of sendSMS:["+result+"]");
							String deviceStatus = "VERIFY_USER_DEVICE";
							if( "SEND_SUCCESS".equals(result) )
							{
								request.getSession().setAttribute("DEVICE_VER_CODE", verCode);
								StringBuffer responseStrBuf = new StringBuffer();
								responseStrBuf.append( "<Root>" );
								responseStrBuf.append( "<DEVICE_STATUS><![CDATA[" ).append( deviceStatus ).append( "]]></DEVICE_STATUS>" );
								responseStrBuf.append( "</Root>" );
								authenticationStatus = responseStrBuf.toString();
								request.getSession().setAttribute( "USER_INFO", userInfo );
								return authenticationStatus;
							}
							else
							{
								invalidateSession(request);
								StringBuffer responseStrBuf = new StringBuffer();
								//responseStrBuf.append( "<Root>" );
								//responseStrBuf.append( "<DEVICE_STATUS><![CDATA[" ).append( deviceStatus ).append( "]]></DEVICE_STATUS>" );
								responseStrBuf.append(result);
								//responseStrBuf.append( "</Root>" );
								authenticationStatus = responseStrBuf.toString();
								//authenticationStatus = result;
								return authenticationStatus;
							}
						}
						else if( "STRICTLY_ENFORCED".equals(status) )
						{
							String deviceStatus = "STRICTLY_ENFORCED";
							StringBuffer responseStrBuf = new StringBuffer();
							responseStrBuf.append( "<Root>" );
							responseStrBuf.append( "<DEVICE_STATUS><![CDATA[" ).append( deviceStatus ).append( "]]></DEVICE_STATUS>" );
							responseStrBuf.append( "</Root>" );
							authenticationStatus = responseStrBuf.toString();
							invalidateSession(request);
							return authenticationStatus;
						}
						//else if( "WORKFLOW_INVOKED".equals(status) )
						else if( status.startsWith("WORKFLOW_INVOKED") )
						{
							String deviceStatus = "WORKFLOW_INVOKED";
							/*StringBuffer responseStrBuf = new StringBuffer();
							responseStrBuf.append( "<Root>" );
							responseStrBuf.append( "<DEVICE_STATUS><![CDATA[" ).append( deviceStatus ).append( "]]></DEVICE_STATUS>" );
							responseStrBuf.append( "</Root>" );
							authenticationStatus = responseStrBuf.toString();*/
							invalidateSession(request);
							return status;
						}
					}
					//Added By Pankaj T. on 18-06-18 for device security based on enterprise level [0-disabled, 1-strictly enforced, 2-OTP, 3-workflow invoked] - End
					//Added by Dnyaneshwar Chavan on 29-Apr-15 [Implement Push Notification] End

					//Added by Prajyot on 04JUN2015[To detect Entity Contact exists or not for login user]Start
					//Commented by Sagar B. as per KB sir[12-12-17]
//					columnName = " descr ";
//					tableName = " profile ";
//					condition = " WHERE profile_id = '" + userInfo.getProfileId() + "' ";
//					String profileDescr = getCommonDBAccess().getDBColumnValue( tableName.trim(), columnName.trim(), condition, userInfo.getTransDB() ) ;
					columnName = null;
					tableName = null;
					condition = null;
//					BaseLogger.log("9",null,null," User Profile Descr["+ profileDescr +"]");
//					userInfo.setProfileDescr(profileDescr);
					request.getSession().setAttribute( "USER_INFO", userInfo );

					columnName = " COUNT(1) ";
					tableName = " ENTITY_CONTACT ";
					condition = " WHERE USER_ID__PORTAL='"+ userInfo.getLoginCode() +"' AND ENTITY_TYPE='"+ userInfo.getUserType() +"' ";
					String countResult = getCommonDBAccess().getDBColumnValue( tableName.trim(), columnName.trim(), condition, userInfo.getTransDB() )  ;
					columnName = null;
					tableName = null;
					condition = null;
					String allowChgAccount = "N";
					if( countResult != null )
					{
						try
						{
							int cnt = (int) Double.parseDouble(countResult);
							if( cnt > 1 )
							{
								allowChgAccount = "Y";
							}
						}
						catch (Exception e)
						{
							allowChgAccount = "N";
						}
					}
					BaseLogger.log("3",null,null," Change Entity Details : ALLOW_CHG_ACCOUNT ["+ allowChgAccount +"]countResult["+countResult+"]");
					request.getSession().setAttribute( "ALLOW_CHG_ACCOUNT", allowChgAccount);
					//Added by Prajyot on 04JUN2015[To detect Entity Contact exists or not for login user]End
					if ( userInfo != null )
					{
						//Added by shrutika on 10-10-19 [Start] for avoid server call for getting all user prefrance value.
						ObjUserPrefDao objUserPrefDao = new ObjUserPrefDao();
						String userPreference = objUserPrefDao.getUserPreference(userCode, userInfo );
						userInfo.setUserPrefList(userPreference);
						//Added by shrutika on 10-10-19 [End] for avoid server call for getting all user prefrance value.
					}
				}
				//Changed by Manish on 07/11/2006 to update login trace whether or not login is valid.
				//Changed by Nilesh on 18-Mar-2011 [MF01SUN037][To add client IP & chg_term into Logintrace]
				//getCommonDBAccess().insertSessionTrace( userCode, request.getSession().getId(), isValidLogin );
				//Added by Dnyaneshwar Chavan on 02-OCT-13 [WS3GSUN002] [ Device ID & type store in LoginTrace table ] START

				// Added by Abhishek on 11.03.2016 [For Authentication changes] START
				if (userInfo == null) {
					userInfo = getCommonDBAccess().getBasicUserInfo(userCode);
				}
				// Added by Abhishek on 11.03.2016 [For Authentication changes] END

				if( deviceType == null || "".equalsIgnoreCase( deviceType ) )
				{
					// Change by Abhishek on 11.03.2016 [Req Id : S15LBAS004 Authentication changes ] START
					// Changed and Added by Pankaj R on 20-JAN-18
					BaseLogger.log("3",null,null,"AuthenticateServlet :: authenticate() : userInfo[" + userInfo + "]");
					BaseLogger.log("3",null,null,"batteryStatus :: "+batteryStatus);
					getCommonDBAccess().insertSessionTrace( userInfo.getLoginCode(), request.getSession().getId(), isValidLogin,
							chgIP, userInfo.getTermId(), hostName, hostIP, userInfo.getEntryId(), userInfo.getEntryType(), userInfo.getTransDB(),
							batteryStatus, browserDetail.getOsName(), browserDetail.getOsVersion(), browserDetail.getClientApp(), browserDetail.getClientAppVersion());
					// Changed and Added by Pankaj R on 20-JAN-18
					// Change by Abhishek on 11.03.2016 [Req Id : S15LBAS004 Authentication changes ] END
				}
				else
				{
					// Change by Abhishek on 11.03.2016 [Req Id : S15LBAS004 Authentication changes ] START
					// Changed and Added by Pankaj R on 20-JAN-18
					getCommonDBAccess().insertSessionTrace( userInfo.getLoginCode(), request.getSession().getId(), isValidLogin, chgIP,
							userInfo.getTermId(), deviceUuId, deviceType, hostName, hostIP, userInfo.getEntryId(), userInfo.getEntryType(),
							/*dummy parameter*/'@', userInfo.getTransDB(), batteryStatus, browserDetail.getOsName(), browserDetail.getOsVersion(), browserDetail.getClientApp(), browserDetail.getClientAppVersion());
					// Changed and Added by Pankaj R on 20-JAN-18
					// Change by Abhishek on 11.03.2016 [Req Id : S15LBAS004 Authentication changes ] END

				}
				//Request ID : W15BMIT003 - Set Current Geo Position in Login trace and USER_INFO.
				//Commented and moved below by Ajinkya Gopalkar on 6-Jan-16[For insert geo position after authenticate]
				/*if( "true".equalsIgnoreCase( CommonConstants.GEOPOS_ENABLE ) )
 				{
					String currentGeoPos = request.getParameter("CURRENT_GEO_POS");
					BaseLogger.log("9",null,null,"@AUTHENTICATE CURRENT_GEO_POS["+ currentGeoPos +"]");
					if( currentGeoPos != null && currentGeoPos.trim().length() > 0 )
 					{
						userInfo.setCurrentGeoPOS(currentGeoPos);
						request.getSession().setAttribute( "USER_INFO", userInfo );
						getCommonDBAccess().updateCurrentGeoPos(userCode, request.getSession().getId(), currentGeoPos);

						//GeoPosition Logging in GEOPOS table - And in case of Web Access deviceUuId will be blank or null so setting RemoteHost
						if( E12GenericUtility.checkNull( deviceUuId ).length() == 0 )
						{
							deviceUuId = request.getRemoteHost();
						}
						getCommonDBAccess().insertGeoPosition(userCode, deviceUuId, "", currentGeoPos, "1");
 					}
 				}*/
				//Added by Dnyaneshwar Chavan on 02-OCT-13 [WS3GSUN002] [ Device ID & type store in LoginTrace table ] END
			}
			//Added by gayatri [to identify the request from rcp]start
			if("true".equals(request.getAttribute("isReqFromRcp")))
			{
				request.getSession().setAttribute( "IS_EMP_INFO_SET", "true" );
			}
			//Added by gayatri [to identify the request from rcp]end
			//Added By Ajinkya Gopalkar on 6-Jan-16[For checking gps after defined interval]
			BaseLogger.log("3",null,null,"In AuthenticateServlet before insertGeoPosition....!!!!");
			if ( userInfo != null && "true".equalsIgnoreCase(authenticationStatus))
			{
				//BaseLogger.log("9",null,null, "USER_INFO :[" + userInfo.toString() + "]" );
				//Changed by Sagar B. for Geo position related changes for multi tenancy on [11Jan18]
				//if( "true".equalsIgnoreCase( CommonConstants.GEOPOS_ENABLE ) )
				if( !"0".equalsIgnoreCase(userInfo.getGeoPosOption()) )
 				{
					String currentGeoPos = request.getParameter("CURRENT_GEO_POS");
					String dataMode = request.getParameter("DATA_MODE");
					String currentGeoPosName = E12GenericUtility.checkNull( request.getParameter("CURRENT_GEO_POS_NAME") );		//Added by Sagar B. to track address of current geopos and store in table[10-Apr-18]
					String geoPosAccuracy = E12GenericUtility.checkNull( request.getParameter("GEOPOS_ACCURACY") );		//Added by Sagar B. to store accuracy of geo position[23-Jul-18]
					BaseLogger.log("3",null,null,"@AUTHENTICATE 1164 CURRENT_GEO_POS["+ currentGeoPos +"] dataMode["+ dataMode +"] CURRENT_GEO_POS_NAME["+currentGeoPosName+"] GEOPOS_ACCURACY["+geoPosAccuracy+"]");
					if( currentGeoPos != null && currentGeoPos.trim().length() > 0 )
 					{
						userInfo.setCurrentGeoPOS(currentGeoPos);
						userInfo.setDeviceID(deviceUuId);
						userInfo.setDataMode(dataMode);
						userInfo.setCurrentGeoPOSName(currentGeoPosName);
						userInfo.setGeoPosAccuracy(geoPosAccuracy);		//Added by Sagar B. to store accuracy of geo position[23-Jul-18]
						request.getSession().setAttribute( "USER_INFO", userInfo );
						getCommonDBAccess().updateCurrentGeoPos(userCode, request.getSession().getId(), currentGeoPos, dataMode, ""); // Changed and Added by Pankaj R on 20-JAN-18
						BaseLogger.log("3",null,null,"@AUTHENTICATE 1170 After updateCurrentGeoPos.....!!!");
						//GeoPosition Logging in GEOPOS table - And in case of Web Access deviceUuId will be blank or null so setting RemoteHost
						if( E12GenericUtility.checkNull( deviceUuId ).length() == 0 )
						{
							deviceUuId = request.getRemoteHost();
						}
						//getCommonDBAccess().insertGeoPosition(userCode, deviceUuId, "", currentGeoPos, "1", dataMode);
						getCommonDBAccess().insertGeoPosition(userCode, deviceUuId, "", currentGeoPos, "1", dataMode, currentGeoPosName, geoPosAccuracy);
 					}
 				}

				//Added By Samadhan on 27-10-2017 [ set enterprise if blank for property editor] start
				String enterprise = userInfo.getEnterprise();
				if( enterprise == null || enterprise.length() <= 0 )
				{
					if(userInfo.getItemSer() == null || "".equalsIgnoreCase(userInfo.getItemSer()))
					{
						enterprise = userInfo.getSiteCode();
					}
					else
					{
						enterprise = userInfo.getSiteCode() + "" +userInfo.getItemSer();
					}

					userInfo.setEnterprise(enterprise);
					request.getSession().setAttribute( "USER_INFO", userInfo );
				}
				//Added By Samadhan on 27-10-2017 [ set enterprise if blank for property editor] end
				//Added by Prasad on 24/07/19 [to store userinfo string in session] START
				if ( userInfo != null )
				{
					request.getSession().setAttribute( "USER_INFO_STR", userInfo.toString() );
				}
				//Added by Prasad on 24/07/19 [to store userinfo string in session] END
			}
			
			
		}
		catch( BaseException be )
		{
			BaseLogger.log("0",null,null,"BaseException: authenticate:==>\n"+be); //$NON-NLS-1$
			invalidateSession(request);
			throw be;
		}
		catch( Exception e )
		{
			BaseLogger.log("0",null,null,"Exception: authenticate:==>\n"+e); //$NON-NLS-1$
			invalidateSession(request);
			throw new BaseException( e );
		}
		return authenticationStatus;
	}

	//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To pass targetCustomer
	//private boolean generateResponse( HttpServletRequest request, HttpServletResponse response, String xmlInfo )throws BaseException
	//Changed by Sandeep S. on 19-JAN-17 [To check session exist or not for same user on same or on another machine]
	//private boolean generateResponse( HttpServletRequest request, HttpServletResponse response, String xmlInfo,String  targetCustomer)throws BaseException
	private boolean generateResponse( HttpServletRequest request, HttpServletResponse response, String xmlInfo,String  targetCustomer, boolean userSessionExist)throws BaseException
	{
		BaseLogger.log("2",null,null, "Generating Response...." ); //$NON-NLS-1$
		boolean  isUserAuthentic = false;
		boolean isFirstLogin = false;
		boolean isPwdExpired = false;
		String responseString =""; //$NON-NLS-1$
		String userCode = null;
		String siteCode = null;
		String passwd = null;
		//Changed by Rupali on 21/08/2008 to check the loginMode whether HTML /RIA version for RIA.Request ID[BI89BAS010]
		String loginMode = null;
		//Changed by Rupali Hande on 20-10-2008 [modified the profile.xml for RIA ].RequestID [BI89SUN008]
		String riaCacheStatus ="0"; //$NON-NLS-1$
		String profId = ""; //$NON-NLS-1$
		boolean isBiuser = false;
		//Changed by Dayanand on 16/08/10[To generate menu application wise || MF01SUN001]
		String applName = ""; //$NON-NLS-1$
		try
		{
			//Changed by Sandesh on 18/11/2016 [For Authentication API] Start
			String isAUTHAPI =  E12GenericUtility.checkNull(request.getParameter("ISAUTHAPI"));
			String appID = E12GenericUtility.checkNull(request.getParameter("APPID"));
			String appUrl = appID.length() > 0 ? "/ibase/login/ExtAuth.jsp?appId="+appID  : "/ibase/login/ExtAuth.jsp";
			String href = isAUTHAPI.equalsIgnoreCase("true") ? appUrl : "/ibase/jsp/login.html" ;
			//Changed by Sandesh on 18/11/2016 [For Authentication API] End

			userCode = request.getParameter( "USER" ); //$NON-NLS-1$
			siteCode = request.getParameter( "SITE_CODE" ); //$NON-NLS-1$
			passwd = request.getParameter( "PASSWORD" ); //$NON-NLS-1$
			HttpSession session = request.getSession();
			//Changed by Rupali on 21/08/2008 to check the loginMode whether HTML /RIA version for RIA.Request ID[BI89BAS010].Start
			loginMode = (String)request.getParameter("loginMode"); //$NON-NLS-1$
			//Changed by Dayanand on 16/08/10[To generate menu application wise || MF01SUN001]
			applName = request.getParameter( "APPL_NAME" ); //$NON-NLS-1$
			//applName = request.getParameter( "conApplNm" ); //$NON-NLS-1$
			BaseLogger.log("3",null,null,"Harshada 14th Dec 2012... loginMode["+loginMode+"]");
			if(loginMode == null){
				BaseLogger.log("3",null,null,"LoginMode setting ..."); //$NON-NLS-1$
				loginMode=""; //$NON-NLS-1$
			}
			//Changed by Rupali on 21/08/2008 to check the loginMode whether HTML /RIA version for RIA.Request ID[BI89BAS010].End

			//Added By Mahesh Patidar on 06-SEP-13 [to get value of caller page used for redirect if login failed]
			String callerPage =  request.getParameter("callerPage"); //$NON-NLS-1$

			//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]
			String loginClient = (String)request.getParameter("loginClient"); //$NON-NLS-1$

            //Added By Pankaj T on 15-09-2020 handle login related issue of invalid session and display alert to user for clearing browser cache - start
            if( "INVALID_SESSION".equals(xmlInfo) )
            {
                String referer = request.getParameter("REFERER");
                BaseLogger.log("3",null,null,"referer[Before] =["+referer+"]");
                if(referer != null && referer.trim().length() > 0 && referer.indexOf("&") != -1 )
                {
                    referer = referer.replaceAll("&", "~~");
                }
                if("MOBILE".equalsIgnoreCase(loginMode))
                {
                    responseString = "alert('"+Messages.getString("AuthenticateServlet_Invalid_Session",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/mobile/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                }
                else if("TABPC".equalsIgnoreCase(loginClient))
                {
                    responseString = "alert('"+Messages.getString("AuthenticateServlet_Invalid_Session",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/ME/Login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                }
                else if( request.getParameter("REFERER") != null && request.getParameter("REFERER").length() !=0 )
                {
                    responseString = "alert('"+Messages.getString("AuthenticateServlet_Invalid_Session",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp?REFERER="+referer+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                }
                else
                {
                    if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
                    {
                        responseString = "alert('"+Messages.getString("AuthenticateServlet_Invalid_Session",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp';";
                    }
                    else
                    {
                        responseString = "alert('"+Messages.getString("AuthenticateServlet_Invalid_Session",getUserLangAndCountry(userCode))+"');window.location.href = '"+href+"';";
                    }
                }
                responseString = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>"+responseString+"</SCRIPT></HEAD></HTML>";
                response.setBufferSize(responseString.length());
                response.setContentType( "text/html; charset=UTF8,"+CommonConstants.ENCODING );
                OutputStream outputStream = response.getOutputStream();
                outputStream.write(responseString.getBytes());
                outputStream.flush();
                outputStream.close();
            }
            //Added By Pankaj T on 15-09-2020 handle login related issue of invalid session and display alert to user for clearing browser cache - end
			else if(xmlInfo != null)
			{
				//
				Document document = new E12GenericUtility().parseString(xmlInfo);
				//Changed by Rupali Hande on 20-10-2008 [modified the profile.xml for RIA ].RequestID [BI89SUN008].Start
				if(document.getElementsByTagName( "RIA_CACHE_STATUS" ).item(0) != null){ //$NON-NLS-1$
					riaCacheStatus = document.getElementsByTagName("RIA_CACHE_STATUS").item(0).getFirstChild().getNodeValue(); //$NON-NLS-1$
				}
				if(document.getElementsByTagName( "PROFILE_ID" ).item(0) != null){ //$NON-NLS-1$
					profId = document.getElementsByTagName("PROFILE_ID").item(0).getFirstChild().getNodeValue(); //$NON-NLS-1$
				}
				if(document.getElementsByTagName( "IS_BI_USER" ).item(0) != null){ //$NON-NLS-1$
					isBiuser = Boolean.valueOf(document.getElementsByTagName("IS_BI_USER").item(0).getFirstChild().getNodeValue()).booleanValue(); //$NON-NLS-1$
				}

				//Changed by Rupali Hande on 20-10-2008 [modified the profile.xml for RIA ].RequestID [BI89SUN008].End
				if (document.getElementsByTagName( "STATUS" ).item(0) != null) //$NON-NLS-1$
				{
					isUserAuthentic = (Boolean.valueOf(document.getElementsByTagName("STATUS").item(0).getFirstChild().getNodeValue())).booleanValue(); //$NON-NLS-1$
				}

				if(document.getElementsByTagName( "STATUS_CODE" ).item(0) != null) //$NON-NLS-1$
				{
					String statusCode = document.getElementsByTagName("STATUS_CODE").item(0).getFirstChild().getNodeValue(); //$NON-NLS-1$
					if (statusCode.equalsIgnoreCase("RESIGNED")) //$NON-NLS-1$
					{
						//Changed by Rupali on 21/08/2008 to send the control to login.html for RIA.Request ID[BI89BAS010].Start
						//responseString = "alert('Employee has resigned !');window.location.href = '/ibase/jsp/login.jsp';";
						//Changed by Rupali for mobile login.Start
						//responseString = "alert('Employee has resigned !');window.location.href = '/ibase/jsp/login.html';";
						//Changed by Rupali on 21/08/2008 to send the control to login.html for RIA.Request ID[BI89BAS010].End
						if("MOBILE".equalsIgnoreCase(loginMode)){ //$NON-NLS-1$
							// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
							responseString = "alert('"+Messages.getString("AuthenticateServlet_employeeHasResigned",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/mobile/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						}
						//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]start
						else if("TABPC".equalsIgnoreCase(loginClient)) //$NON-NLS-1$
						{
							// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
							responseString = "alert('"+Messages.getString("AuthenticateServlet_employeeHasResigned",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/ME/Login.html';";							 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						}
						//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]end
						else{
							//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.start
							//responseString = "alert('"+Messages.getString("AuthenticateServlet_employeeHasResigned")+"');window.location.href = '/ibase/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							//Changed By Mahesh Patidar on 06-SEP-13 [to redirect back to login.jsp if callerPage is JSP]
//							if(targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer))
							if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
							{
								// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
								responseString = "alert('"+Messages.getString("AuthenticateServlet_employeeHasResigned",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							}
							else
							{
								// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
								//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
								responseString = "alert('"+Messages.getString("AuthenticateServlet_employeeHasResigned",getUserLangAndCountry(userCode))+"');window.location.href = '"+href+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
								//Changed by Sandesh on 05/12/2016 [For Authentication API] End
							}
							//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.end

						}
						//Changed by Rupali for mobile login.End
					}//added by vishal pathare on 18.6.18 for[users licence related validation]Start
					else if (statusCode.equalsIgnoreCase("INVALID_LICENCE"))
					{
						BaseLogger.log("3",null,null,"statusCode final["+statusCode+"]");
						String referer = request.getParameter("REFERER");
						BaseLogger.log("3",null,null,"referer[Before] =["+referer+"]");
						if(referer != null && referer.trim().length() > 0 && referer.indexOf("&") != -1 )
						{
							referer = referer.replaceAll("&", "~~");
						}
						if("MOBILE".equalsIgnoreCase(loginMode))
						{
							responseString = "alert('"+Messages.getString("Invalid Activation Code",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/mobile/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						}
						else if("TABPC".equalsIgnoreCase(loginClient))
						{
							responseString = "alert('"+Messages.getString("Invalid Activation Code",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/ME/Login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						}
						else if( request.getParameter("REFERER") != null && request.getParameter("REFERER").length() !=0 )
						{
							responseString = "alert('"+Messages.getString("Invalid Activation Code",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp?REFERER="+referer+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
						}
						else
						{
							if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
							{
								responseString = "alert('"+Messages.getString("Invalid Activation Code",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							}
							else
							{
								responseString = "alert('"+Messages.getString("Invalid Activation Code",getUserLangAndCountry(userCode))+"');window.location.href = '"+href+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							}
						}
					}//added by vishal pathare on 18.6.18 for[users licence related validation]END
					else if (statusCode.equalsIgnoreCase("LOCKED")) //$NON-NLS-1$
					{
						//Changed by Rupali on 21/08/2008 to send the control to login.html for RIA.Request ID[BI89BAS010].Start
						//responseString = "alert('Your account is locked ! Please, contact your administrator for further assistance.');window.location.href = '/ibase/jsp/login.jsp';";
						//Changed by Rupali for mobile login.Start
						//responseString = "alert('Your account is locked ! Please, contact your administrator for further assistance.');window.location.href = '/ibase/jsp/login.html';";
						//Changed by Rupali on 21/08/2008 to send the control to login.html for RIA.Request ID[BI89BAS010].End
						if("MOBILE".equalsIgnoreCase(loginMode)){ //$NON-NLS-1$
							// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
							responseString = "alert('"+Messages.getString("AuthenticateServlet_accountIsLockedContactAdmin",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/mobile/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						}
						//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]start
						else if("TABPC".equalsIgnoreCase(loginClient)) //$NON-NLS-1$
						{
							// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
							responseString = "alert('"+Messages.getString("AuthenticateServlet_accountIsLockedContactAdmin",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/ME/Login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						}
						//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]end
						else{

							//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.start
							//responseString = "alert('"+Messages.getString("AuthenticateServlet_accountIsLockedContactAdmin")+"');window.location.href = '/ibase/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							//Changed By Mahesh Patidar on 06-SEP-13 [to redirect back to login.jsp if callerPage is JSP]
//							if(targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer))
							if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
							{
								// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
								responseString = "alert('"+Messages.getString("AuthenticateServlet_accountIsLockedContactAdmin",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							}
							else
							{
								// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
								//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
								responseString = "alert('"+Messages.getString("AuthenticateServlet_accountIsLockedContactAdmin",getUserLangAndCountry(userCode))+"');window.location.href = '"+href+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
								//Changed by Sandesh on 05/12/2016 [For Authentication API] End
							}
							//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.end
						}
						//Changed by Rupali for mobile login.End
					}
					//Added By Pankaj T. on 18-11--2020 for removing weak account lock vulnerability - if user wrongly enter password more than 5 times then lock the account and send new password on email/mobile and unlock account using new password - start
					else if (statusCode.equalsIgnoreCase("ACCOUNT_LOCKED"))
					{
						if("MOBILE".equalsIgnoreCase(loginMode))
						{
							responseString = "alert('"+Messages.getString("AuthenticateServlet_accountIsLocked",getUserLangAndCountry(request.getParameter("USER")))+" "+CommonConstants.WRONG_LOGIN_COUNT+" times. "+Messages.getString("AuthenticateServlet_newPasswordIsSentToYourEmaiID",getUserLangAndCountry(request.getParameter("USER")))+" "+Messages.getString("AuthenticateServlet_accountUnlocked",getUserLangAndCountry(request.getParameter("USER")))+"');window.location.href = '/ibase/mobile/jsp/login.html';";
						}
						else if("TABPC".equalsIgnoreCase(loginClient))
						{
							responseString = "alert('"+Messages.getString("AuthenticateServlet_accountIsLocked",getUserLangAndCountry(request.getParameter("USER")))+" "+CommonConstants.WRONG_LOGIN_COUNT+" times. "+Messages.getString("AuthenticateServlet_newPasswordIsSentToYourEmaiID",getUserLangAndCountry(request.getParameter("USER")))+" "+Messages.getString("AuthenticateServlet_accountUnlocked",getUserLangAndCountry(request.getParameter("USER")))+"');window.location.href = '/ibase/ME/Login.html';";
						}
						else
						{
							if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
							{
								responseString = "alert('"+Messages.getString("AuthenticateServlet_accountIsLocked",getUserLangAndCountry(request.getParameter("USER")))+" "+CommonConstants.WRONG_LOGIN_COUNT+" times. "+Messages.getString("AuthenticateServlet_newPasswordIsSentToYourEmaiID",getUserLangAndCountry(request.getParameter("USER")))+" "+Messages.getString("AuthenticateServlet_accountUnlocked",getUserLangAndCountry(request.getParameter("USER")))+"');window.location.href = '/ibase/jsp/login.jsp';";
							}
							else
							{
								responseString = "alert('"+Messages.getString("AuthenticateServlet_accountIsLocked",getUserLangAndCountry(request.getParameter("USER")))+" "+CommonConstants.WRONG_LOGIN_COUNT+" times. "+Messages.getString("AuthenticateServlet_newPasswordIsSentToYourEmaiID",getUserLangAndCountry(request.getParameter("USER")))+" "+Messages.getString("AuthenticateServlet_accountUnlocked",getUserLangAndCountry(request.getParameter("USER")))+" ');window.location.href = '"+href+"';";
							}
						}
					}
					else if (statusCode.equalsIgnoreCase("WRONG_LOGIN_COUNT_EXCEED"))
					{
						if("MOBILE".equalsIgnoreCase(loginMode))
						{
							responseString = "alert('"+Messages.getString("AuthenticateServlet_passwordBlockedSinceWronglyEntered",getUserLangAndCountry(request.getParameter("USER")))+CommonConstants.WRONG_LOGIN_COUNT+Messages.getString("AuthenticateServlet_newPasswordSentToEmailID",getUserLangAndCountry(request.getParameter("USER")))+"');window.location.href = '/ibase/mobile/jsp/login.html';";
						}
						else if("TABPC".equalsIgnoreCase(loginClient))
						{
							responseString = "alert('"+Messages.getString("AuthenticateServlet_passwordBlockedSinceWronglyEntered",getUserLangAndCountry(request.getParameter("USER")))+CommonConstants.WRONG_LOGIN_COUNT+Messages.getString("AuthenticateServlet_newPasswordSentToEmailID",getUserLangAndCountry(request.getParameter("USER")))+"');window.location.href = '/ibase/ME/Login.html';";
						}
						else
						{
							if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
							{
								responseString = "alert('"+Messages.getString("AuthenticateServlet_passwordBlockedSinceWronglyEntered",getUserLangAndCountry(request.getParameter("USER")))+CommonConstants.WRONG_LOGIN_COUNT+Messages.getString("AuthenticateServlet_newPasswordSentToEmailID",getUserLangAndCountry(request.getParameter("USER")))+"');window.location.href = '/ibase/jsp/login.jsp';";
							}
							else
							{
								responseString = "alert('"+Messages.getString("AuthenticateServlet_passwordBlockedSinceWronglyEntered",getUserLangAndCountry(request.getParameter("USER")))+CommonConstants.WRONG_LOGIN_COUNT+Messages.getString("AuthenticateServlet_newPasswordSentToEmailID",getUserLangAndCountry(request.getParameter("USER")))+" ');window.location.href = '"+href+"';";
							}
						}
					}
					//Added By Pankaj T. on 18-11--2020 for removing weak account lock vulnerability - if user wrongly enter password more than 5 times then lock the account and send new password on email/mobile and unlock account using new password - end
					else if (statusCode.indexOf("INVALID") != -1) //$NON-NLS-1$
					{
						String referer = request.getParameter("REFERER"); //$NON-NLS-1$

						//Changed by Gulzar on 03/DEC/13 - to solve the link issue : START
						BaseLogger.log("3",null,null,"referer[Before] =["+referer+"]");

						if(referer != null && referer.trim().length() > 0 && referer.indexOf("&") != -1 )
						{
							referer = referer.replaceAll("&", "~~");
						}

						BaseLogger.log("3",null,null,"referer[After] =["+referer+"]");

						//Changed by Gulzar on 03/DEC/13 - to solve the link issue : END

						if (statusCode.equalsIgnoreCase("INVALID_USR")) //$NON-NLS-1$
						{
							//Changed by Rupali on 21/08/2008 to send the control to login.html for RIA.Request ID[BI89BAS010].Start
							//responseString = "alert('Please enter the valid User Name and Password');window.location.href = '/ibase/jsp/login.jsp';";
							//Changed by Rupali for mobile login.Start
							//responseString = "alert('Please enter the valid User Name and Password');window.location.href = '/ibase/jsp/login.html';";
							//Changed by Rupali on 21/08/2008 to send the control to login.html for RIA.Request ID[BI89BAS010].End
							if("MOBILE".equalsIgnoreCase(loginMode)){ //$NON-NLS-1$
								// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
								responseString = "alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUserNameAndPassword",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/mobile/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							}
							//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]start
							else if("TABPC".equalsIgnoreCase(loginClient)) //$NON-NLS-1$
							{
								// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
								responseString = "alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUserNameAndPassword",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/ME/Login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							}
							//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]end
							//Change by Nilesh on 10-May-2011[DI01SUN093][redirect to login.jsp]Start
							else if( request.getParameter("REFERER") != null && request.getParameter("REFERER").length() !=0 ) //$NON-NLS-1$ //$NON-NLS-2$
							{
								// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
								responseString = "alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUserNameAndPassword",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp?REFERER="+referer+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
							}
							//Change by Nilesh on 10-May-2011[DI01SUN093][redirect to login.jsp]End
							else
							{
								//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.start
								//responseString = "alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUserNameAndPassword")+"');window.location.href = '/ibase/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//Changed By Mahesh Patidar on 06-SEP-13 [to redirect back to login.jsp if callerPage is JSP]
//								if(targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer))
								if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
								{
									// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
									responseString = "alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUserNameAndPassword",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
								}
								else
								{
									// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
									//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
									responseString = "alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUserNameAndPassword",getUserLangAndCountry(userCode))+"');window.location.href = '"+ href+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
									//Changed by Sandesh on 05/12/2016 [For Authentication API] End
								}
								//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.end
							}
							//Changed by Rupali for mobile login.End
						}
						else if (statusCode.equalsIgnoreCase("INVALID_PWD")) //$NON-NLS-1$
						{
							//Changed by Rupali on 21/08/2008 to send the control to login.html for RIA.Request ID[BI89BAS010].Start
							//responseString = "alert('Please enter the valid User Name and Password');window.location.href = '/ibase/jsp/login.jsp';";
							//Changed by Rupali for mobile login.Start
							//responseString = "alert('Please enter the valid User Name and Password');window.location.href = '/ibase/jsp/login.html';";
							//Changed by Rupali on 21/08/2008 to send the control to login.html for RIA.Request ID[BI89BAS010].End
							if("MOBILE".equalsIgnoreCase(loginMode)){ //$NON-NLS-1$
								// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
								responseString = "alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUserNameAndPassword",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/mobile/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							}
							//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]start
							else if("TABPC".equalsIgnoreCase(loginClient)) //$NON-NLS-1$
							{
								// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
								responseString = "alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUserNameAndPassword",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/ME/Login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							}
							//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]end
							//Change by Nilesh on 10-May-2011[DI01SUN093][redirect to login.jsp]Start
							else if( request.getParameter("REFERER") != null && request.getParameter("REFERER").length() !=0 ) //$NON-NLS-1$ //$NON-NLS-2$
							{
								// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
								responseString = "alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUserNameAndPassword",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp?REFERER="+referer+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
							}
							//Change by Nilesh on 10-May-2011[DI01SUN093][redirect to login.jsp]End
							else
							{
								//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.start
								//responseString = "alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUserNameAndPassword")+"');window.location.href = '/ibase/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$//Changed By Mahesh Patidar on 06-SEP-13 [to redirect back to login.jsp if callerPage is JSP]
//								if(targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer))
								if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
								{
									// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
									responseString = "alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUserNameAndPassword",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
								}
								else
								{
									// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
									//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
									responseString = "alert('"+Messages.getString("AuthenticateServlet_pleaseEnterValidUserNameAndPassword",getUserLangAndCountry(userCode))+"');window.location.href = '"+href+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
									//Changed by Sandesh on 05/12/2016 [For Authentication API] End
								}
								//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.end
							}
							//Changed by Rupali for mobile login.End
							//Changed by rahul on 25-apr-2016 [Request ID : W15LSUN010 for updatind date as well as time in LAST_PWD_CHGDATE column in users table]
							//Commented By Pankaj T. on 18-11--2020 for removing weak account lock vulnerability - if user wrongly enter password more than 5 times then lock the account and send new password on email/mobile and unlock account using new password - start
							/*int wrongLoginCount = CommonConstants.WRONG_LOGIN_COUNT;
							String userId = request.getParameter("USER");
							//Changed By Pankaj T. on 13-07-2020 for removing vulnerability of weak account lock policy - start
							userCode = getCommonDBAccess().getUserCode(userCode);
							String acctLock = getCommonDBAccess().getDBColumnValue("USERS", "ACCT_LOCK", "WHERE CODE='"+userCode+"'");
							BaseLogger.log("3",null,null,"acctLock......"+acctLock);
							if( E12GenericUtility.checkNull(acctLock).length() > 0 && "Y".equalsIgnoreCase(acctLock) )
							{
								responseString = "alert('"+Messages.getString("AuthenticateServlet_accountIsLocked",getUserLangAndCountry(request.getParameter("USER")))+" "+CommonConstants.WRONG_LOGIN_COUNT+" times. "+Messages.getString("AuthenticateServlet_newPasswordIsSentToYourEmaiID",getUserLangAndCountry(request.getParameter("USER")))+" "+Messages.getString("AuthenticateServlet_accountUnlocked",getUserLangAndCountry(request.getParameter("USER")))+" ');window.location.href = '"+href+"';";
							}
							else
							{
								//Added by sadique shaikh 24-6-2019
								String deviceId=request.getParameter("MAC_ADDRESS");
								if( deviceId == null || deviceId.trim().length() == 0 )
								{
									deviceId = request.getParameter("DEVICEID");
								}
								String chgIP = request.getRemoteAddr();
								BaseLogger.log("3",null,null,"wrongLoginCount....."+wrongLoginCount+".....userId......"+userId+"......chgIP....."+chgIP+"userCode......"+userCode);
								boolean resetPassword = isResetPassword(wrongLoginCount,userId,chgIP);
								BaseLogger.log("3",null,null,"resetPassword......"+resetPassword);
								if(resetPassword)
								{
									//below code commented and Two new arguement added by sadique 25-6-2019 for change password
									//secureAccount( userId,"0");
									secureAccount(userCode,"0",request.getRemoteAddr(),deviceId);
									//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
									//Changed By Pankaj T. on 13-07-2020 for removing vulnerability of weak account lock policy - start
									getCommonDBAccess().lockAccount(userId);
									//Changed By Pankaj T. on 13-07-2020 for removing vulnerability of weak account lock policy - end
									responseString = "alert('"+Messages.getString("AuthenticateServlet_passwordBlockedSinceWronglyEntered",getUserLangAndCountry(request.getParameter("USER")))+wrongLoginCount+Messages.getString("AuthenticateServlet_newPasswordSentToEmailID",getUserLangAndCountry(request.getParameter("USER")))+" ');window.location.href = '"+href+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
									//Changed by Sandesh on 05/12/2016 [For Authentication API] End
								}
							}*/
							//Commented By Pankaj T. on 18-11--2020 for removing weak account lock vulnerability - if user wrongly enter password more than 5 times then lock the account and send new password on email/mobile and unlock account using new password - end
							//Changed By Pankaj T. on 13-07-2020 for removing vulnerability of weak account lock policy - end
							//Changed by rahul on 25-apr-2016 [Request ID : W15LSUN010 for updatind date as well as time in LAST_PWD_CHGDATE column in users table]
						}

						if ( session.getAttribute( "INVALID_COUNT" ) == null ) //$NON-NLS-1$
						{
							session.setAttribute( "INVALID_COUNT", new Integer( 1 ) ); //$NON-NLS-1$
						}
						else
						{
							int maxCount = 5;
							int invaildCount = ( ( Integer )session.getAttribute( "INVALID_COUNT" ) ).intValue(); //$NON-NLS-1$
							if (invaildCount == maxCount-1)
							{
								if (document.getElementsByTagName( "RES_TYPE" ) != null && document.getElementsByTagName( "RES_TYPE" ).item( 0 ) != null) //$NON-NLS-1$ //$NON-NLS-2$
								{
									//below code added by sadique 25-6-2019 for change password
									//String chgIP = request.getRemoteAddr();
									//Changed By Pankaj T. on 21-05-2021 for getting actual client ip in case of load balancer - start
									String chgIP = request.getHeader("X-Forwarded-For");
									if(chgIP == null)
									{  
										chgIP = request.getRemoteAddr();
									}
									//Changed By Pankaj T. on 21-05-2021 for getting actual client ip in case of load balancer - end
									//change by sadique
									String deviceId = request.getParameter("MAC_ADDRESS");
									if( deviceId == null || deviceId.trim().length() == 0 )
									{
										deviceId = request.getParameter("DEVICEID");
									}
									//end on 25-6-2019(sadique)
									String resType = document.getElementsByTagName("RES_TYPE").item(0).getFirstChild().getNodeValue(); //$NON-NLS-1$
									//below code commented and Two new arguement added by sadique 25-6-2019 for change password
									//secureAccount(userCode, resType);
									secureAccount(userCode, resType,chgIP,deviceId);
									//end on 25-6-2019(sadique)
									if ( Integer.parseInt( resType ) == 0 )
									{
										String emailIdOff = null;
										if (document.getElementsByTagName("EMAIL_ID") != null && document.getElementsByTagName("EMAIL_ID").item(0) != null) //$NON-NLS-1$ //$NON-NLS-2$
										{
											emailIdOff = document.getElementsByTagName("EMAIL_ID").item(0).getFirstChild().getNodeValue(); //$NON-NLS-1$
										}
										//Changed by Rupali on 21/08/2008 to send the control to login.html for RIA.Request ID[BI89BAS010].Start
										//responseString = "alert('Your Password has been blocked since it was wrongly entered "+maxCount+" times new password is sent to your e-mail id "+emailIdOff+" ');window.location.href = '/ibase/jsp/login.jsp';";
										//Changed by Rupali for mobile login.Start
										//responseString = "alert('Your Password has been blocked since it was wrongly entered "+maxCount+" times new password is sent to your e-mail id "+emailIdOff+" ');window.location.href = '/ibase/jsp/login.html';";
										//Changed by Rupali on 21/08/2008 to send the control to login.html for RIA.Request ID[BI89BAS010].End
										if("MOBILE".equalsIgnoreCase(loginMode)){ //$NON-NLS-1$
											// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
											responseString = "alert('"+Messages.getString("AuthenticateServlet_passwordBlockedSinceWronglyEntered",getUserLangAndCountry(request.getParameter("USER")))+maxCount+Messages.getString("AuthenticateServlet_newPasswordSentToEmailID",getUserLangAndCountry(request.getParameter("USER")))+emailIdOff+" ');window.location.href = '/ibase/mobile/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
										}
										//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]start
										else if("TABPC".equalsIgnoreCase(loginClient)) //$NON-NLS-1$
										{
											// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
											responseString = "alert('"+Messages.getString("AuthenticateServlet_passwordBlockedSinceWronglyEntered",getUserLangAndCountry(request.getParameter("USER")))+maxCount+Messages.getString("AuthenticateServlet_newPasswordSentToEmailID",getUserLangAndCountry(request.getParameter("USER")))+emailIdOff+" ');window.location.href = '/ibase/ME/Login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
										}
										//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]end
										else{
											//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.start
											//responseString = "alert('"+Messages.getString("AuthenticateServlet_passwordBlockedSinceWronglyEntered")+maxCount+Messages.getString("AuthenticateServlet_newPasswordSentToEmailID")+emailIdOff+" ');window.location.href = '/ibase/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
											//Changed By Mahesh Patidar on 06-SEP-13 [to redirect back to login.jsp if callerPage is JSP]
//											if(targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer))
											if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
											{
												// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
												responseString = "alert('"+Messages.getString("AuthenticateServlet_passwordBlockedSinceWronglyEntered",getUserLangAndCountry(request.getParameter("USER")))+maxCount+Messages.getString("AuthenticateServlet_newPasswordSentToEmailID",getUserLangAndCountry(request.getParameter("USER")))+emailIdOff+" ');window.location.href = '/ibase/jsp/login.jsp';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
											}
											else
											{
												// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
												//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
												responseString = "alert('"+Messages.getString("AuthenticateServlet_passwordBlockedSinceWronglyEntered",getUserLangAndCountry(request.getParameter("USER")))+maxCount+Messages.getString("AuthenticateServlet_newPasswordSentToEmailID",getUserLangAndCountry(request.getParameter("USER")))+emailIdOff+" ');window.location.href = '"+href+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
												//Changed by Sandesh on 05/12/2016 [For Authentication API] End
											}
											//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.end

										}
										//Changed by Rupali for mobile login.End
									}
									else if ( Integer.parseInt( resType ) == 1)
									{
										//Changed by Rupali on 21/08/2008 to send the control to login.html for RIA.Request ID[BI89BAS010]
										//responseString = "alert('Your account is locked ! Please, contact your administrator for further assistance.');window.location.href = '/ibase/jsp/login.jsp';";
										//Changed by Rupali for mobile login.Start
										//responseString = "alert('Your account is locked ! Please, contact your administrator for further assistance.');window.location.href = '/ibase/jsp/login.html';";
										if("MOBILE".equalsIgnoreCase(loginMode)){ //$NON-NLS-1$
											// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
											responseString = "alert('"+Messages.getString("AuthenticateServlet_accountIsLockedContactAdmin",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/mobile/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
										}
										//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]start
										else if("TABPC".equalsIgnoreCase(loginClient)) //$NON-NLS-1$
										{
											// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
											responseString = "alert('"+Messages.getString("AuthenticateServlet_accountIsLockedContactAdmin",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/ME/Login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
										}
										//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]end
										else{

											//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.start
											//responseString = "alert('"+Messages.getString("AuthenticateServlet_accountIsLockedContactAdmin")+"');window.location.href = '/ibase/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
											//Changed By Mahesh Patidar on 06-SEP-13 [to redirect back to login.jsp if callerPage is JSP]
//											if(targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer))
											if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
											{
												// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
												responseString = "alert('"+Messages.getString("AuthenticateServlet_accountIsLockedContactAdmin",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
											}
											else
											{
												// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
												//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
												responseString = "alert('"+Messages.getString("AuthenticateServlet_accountIsLockedContactAdmin",getUserLangAndCountry(userCode))+"');window.location.href = '"+href+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
												//Changed by Sandesh on 05/12/2016 [For Authentication API] End
											}
											//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.end
										}
										//Changed by Rupali for mobile login.End
									}
									else
									{
										BaseLogger.log("3",null,null,"Invaild Response Type(resType) Found :"+resType); //$NON-NLS-1$
									}
								}
								session.setAttribute( "INVALID_COUNT", new Integer( 0 ) ); //$NON-NLS-1$
							}
							else
							{
								session.setAttribute( "INVALID_COUNT", new Integer( invaildCount+1 ) ); //$NON-NLS-1$
							}
						}
					}
					else if(statusCode.indexOf("PASS_EXP") != -1) //$NON-NLS-1$
					{
						isPwdExpired = true;

						//Changed by Gulzar on 03/DEC/13 - to solve the link issue : START
						String referer = request.getParameter("REFERER"); //$NON-NLS-1$
						BaseLogger.log("3",null,null,"referer[Before] =["+referer+"]");

						if(referer != null && referer.trim().length() > 0 && referer.indexOf("&") != -1 )
						{
							referer = referer.replaceAll("&", "~~");
						}

						BaseLogger.log("3",null,null,"referer[After] =["+referer+"]");

						//Changed by Gulzar on 03/DEC/13 - to solve the link issue : END

						//Changed by Hatim on 06/04/2007 to not pick up MIN_PWD_LENGTH at this stage, instead only when needed in case of change password.
						/*
						int minPwdLen = -1;
						if (document.getElementsByTagName("MIN_PWD_LENGTH") != null && document.getElementsByTagName("MIN_PWD_LENGTH").item(0) != null)
						{
							minPwdLen = Integer.parseInt(document.getElementsByTagName("MIN_PWD_LENGTH").item(0).getFirstChild().getNodeValue());
						}
						*/
						if (statusCode.equalsIgnoreCase("PASS_EXP_GRACE")) //$NON-NLS-1$
						{
							//Changed by Hatim on 06/04/2007 to not pick up MIN_PWD_LENGTH at this stage, instead only when needed in case of change password.
							//responseString = "if(confirm('Your password is expired !, Would you like to change your password now?')){window.location.href='/ibase/jsp/ChangePassword.jsp?user="+userCode+"&site="+siteCode+"&minPwdLen="+minPwdLen+"&fromPage=welcome';}else{window.location.href='/ibase/AuthenticateServlet?USER="+userCode+"&action=UPDATE_GRACE_COUNT';}";
							//responseString = "if(confirm('Your password is expired !, Would you like to change your password now?')){window.location.href='/ibase/jsp/ChangePassword.jsp?user="+userCode+"&site="+siteCode+"&fromPage=welcome';}else{window.location.href='/ibase/AuthenticateServlet?USER="+userCode+"&action=UPDATE_GRACE_COUNT';}";

							//Commented and changed by Gulzar on 03/DEC/13 to add REFERER parameter to solve the link issue : START
							//responseString = "if(confirm('"+Messages.getString("AuthenticateServlet_passwordExpiredWouldYouLikeToChange")+"')){window.location.href='/ibase/jsp/ChangePassword.jsp?user="+userCode+"&site="+siteCode+"&loginMode="+loginMode+"&fromPage=welcome';}else{window.location.href='/ibase/AuthenticateServlet?USER="+userCode+"&action=UPDATE_GRACE_COUNT';}";	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
							// commented by Raju K on 30-01-14 for changing from ChangePassword to E12ChangePassword
							//responseString = "if(confirm('"+Messages.getString("AuthenticateServlet_passwordExpiredWouldYouLikeToChange")+"')){window.location.href='/ibase/jsp/ChangePassword.jsp?user="+userCode+"&site="+siteCode+"&loginMode="+loginMode+"&fromPage=welcome';}else{window.location.href='/ibase/AuthenticateServlet?USER="+userCode+"&REFERER="+referer+"&action=UPDATE_GRACE_COUNT';}";	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
							// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
							//Changed By Pankaj T. on 18-09-19 for getting PASSWORD_COMPLEXITY against user defined ENTERPRISE instead of ibase.xml - start
							String passWdComplexity = "";
							BaseLogger.log("3", null, null, "#### PASS_EXP_GRACE In AuthenticateServlet generateResponse CODE:["+userCode+"]");
							CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
							//Added by AMOL S. on 24-Jan-2020 [To resolve issue, if login other than code] START.
							userCode = commonDBAccessEJB.getBasicUserInfo(userCode).getLoginCode();
							//Added by AMOL S. on 24-Jan-2020 [To resolve issue, if login other than code] END.
							String transDB = commonDBAccessEJB.getDBColumnValue("USERS", "TRANS_DB", "WHERE CODE = '"+userCode+"'");
							BaseLogger.log("3", null, null, "In AuthenticateServlet generateResponse TRANS_DB:["+transDB+"]");
							
							String enterprise = commonDBAccessEJB.getDBColumnValue("USERS", "ENTERPRISE", "WHERE CODE = '"+userCode+"'");
							BaseLogger.log("3", null, null, "In AuthenticateServlet generateResponse ENTERPRISE against CODE:["+enterprise+"]");
							
							if( "".equals(E12GenericUtility.checkNull(enterprise)) )
							{
								BaseLogger.log("3", null, null, "In AuthenticateServlet generateResponse SITE_CODE against CODE:["+siteCode+"]");
								
								enterprise = commonDBAccessEJB.getDBColumnValue("SITE", "ENTERPRISE", "WHERE SITE_CODE = '"+siteCode+"'", transDB);
								BaseLogger.log("3", null, null, "In AuthenticateServlet generateResponse ENTERPRISE against SITE_CODE:["+enterprise+"]");
							}
							
							passWdComplexity = commonDBAccessEJB.getDBColumnValue("ENTERPRISE", "PASSWORD_COMPLEXITY", "WHERE ENTERPRISE = '"+enterprise+"'", transDB);
							BaseLogger.log("3",null,null,"In AuthenticateServlet generateResponse PASSWORD_COMPLEXITY against  ENTERPRISE:["+passWdComplexity+"]");
							//responseString = "if(confirm('"+Messages.getString("AuthenticateServlet_passwordExpiredWouldYouLikeToChange",getUserLangAndCountry(userCode))+"')){window.location.href='/ibase/jsp/E12ChangePassword.jsp?user="+userCode+"&site="+siteCode+"&loginMode="+loginMode+"&fromPage=welcome';}else{window.location.href='/ibase/AuthenticateServlet?USER="+userCode+"&REFERER="+referer+"&action=UPDATE_GRACE_COUNT';}";	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
							responseString = "if(confirm('"+Messages.getString("AuthenticateServlet_passwordExpiredWouldYouLikeToChange",getUserLangAndCountry(userCode))+"')){window.location.href='/ibase/jsp/E12ChangePassword.jsp?user="+userCode+"&site="+siteCode+"&passwordComplexity="+passWdComplexity+"&loginMode="+loginMode+"&fromPage=welcome';}else{window.location.href='/ibase/AuthenticateServlet?USER="+userCode+"&REFERER="+referer+"&action=UPDATE_GRACE_COUNT';}";	 //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
							//Changed By Pankaj T. on 18-09-19 for getting PASSWORD_COMPLEXITY against user defined ENTERPRISE instead of ibase.xml - end
							//Commented and changed by Gulzar on 03/DEC/13 to add REFERER parameter to solve the link issue : END
						}
						else if (statusCode.equalsIgnoreCase("PASS_EXP_NOGRACE")) //$NON-NLS-1$
						{
							//Changed by Hatim on 06/04/2007 to not pick up MIN_PWD_LENGTH at this stage, instead only when needed in case of change password.
							//responseString = "alert('Your password is expired !, Please change your password now');window.location.href='/ibase/jsp/ChangePassword.jsp?user="+userCode+"&site="+siteCode+"&minPwdLen="+minPwdLen+"&fromPage=welcome';";
							//responseString = "alert('Your password is expired !, Please change your password now');window.location.href='/ibase/jsp/ChangePassword.jsp?user="+userCode+"&site="+siteCode+"&fromPage=welcome';";
							//Commented by Raju K on 30-01-14 for changing from ChangePassword to E12ChangePassword
							//responseString = "alert('"+Messages.getString("AuthenticateServlet_passwordExpiredChangeIt")+"');window.location.href='/ibase/jsp/ChangePassword.jsp?user="+userCode+"&site="+siteCode+"&loginMode="+loginMode+"&fromPage=welcome';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
							// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
							//Changed By Pankaj T. on 18-09-19 for getting PASSWORD_COMPLEXITY against user defined ENTERPRISE instead of ibase.xml - start
							String passWdComplexity = "";
							BaseLogger.log("3", null, null, "#### PASS_EXP_NOGRACE In AuthenticateServlet generateResponse CODE:["+userCode+"]");
							CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
							//Added by AMOL S. on 24-Jan-2020 [To resolve issue, if login other than code] START.
							userCode = commonDBAccessEJB.getBasicUserInfo(userCode).getLoginCode();
							//Added by AMOL S. on 24-Jan-2020 [To resolve issue, if login other than code] END.
							String transDB = commonDBAccessEJB.getDBColumnValue("USERS", "TRANS_DB", "WHERE CODE = '"+userCode+"'");
							BaseLogger.log("3", null, null, "In AuthenticateServlet generateResponse TRANS_DB:["+transDB+"]");
							
							String enterprise = commonDBAccessEJB.getDBColumnValue("USERS", "ENTERPRISE", "WHERE CODE = '"+userCode+"'");
							BaseLogger.log("3", null, null, "In AuthenticateServlet generateResponse ENTERPRISE against CODE:["+enterprise+"]");
							
							if( "".equals(E12GenericUtility.checkNull(enterprise)) )
							{
								BaseLogger.log("3", null, null, "In AuthenticateServlet generateResponse SITE_CODE against CODE:["+siteCode+"]");
								
								enterprise = commonDBAccessEJB.getDBColumnValue("SITE", "ENTERPRISE", "WHERE SITE_CODE = '"+siteCode+"'", transDB);
								BaseLogger.log("3", null, null, "In AuthenticateServlet generateResponse ENTERPRISE against SITE_CODE:["+enterprise+"]");
							}
							
							passWdComplexity = commonDBAccessEJB.getDBColumnValue("ENTERPRISE", "PASSWORD_COMPLEXITY", "WHERE ENTERPRISE = '"+enterprise+"'", transDB);
							BaseLogger.log("3",null,null,"In AuthenticateServlet generateResponse PASSWORD_COMPLEXITY against  ENTERPRISE:["+passWdComplexity+"]");
							//responseString = "alert('"+Messages.getString("AuthenticateServlet_passwordExpiredChangeIt",getUserLangAndCountry(userCode))+"');window.location.href='/ibase/jsp/E12ChangePassword.jsp?user="+userCode+"&site="+siteCode+"&loginMode="+loginMode+"&fromPage=welcome';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
							responseString = "alert('"+Messages.getString("AuthenticateServlet_passwordExpiredChangeIt",getUserLangAndCountry(userCode))+"');window.location.href='/ibase/jsp/E12ChangePassword.jsp?user="+userCode+"&site="+siteCode+"&passwordComplexity="+passWdComplexity+"&loginMode="+loginMode+"&fromPage=welcome';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
							//Changed By Pankaj T. on 18-09-19 for getting PASSWORD_COMPLEXITY against user defined ENTERPRISE instead of ibase.xml - end
						}
					}
					else if(statusCode.equalsIgnoreCase("VALID")) //$NON-NLS-1$
					{
						//BaseLogger.log("9",null,null," dnyaneshwar ---- statusCode["+statusCode+"]");
						//Added by Dnyaneshwar Chavan on 7-MAY-14 [ User should not be login when site value are 'INVALID_SITE' and 'INACCESSIBLE_SITE'  ] Start
						if(document.getElementsByTagName( "SITE_CODE" ).item(0) != null)
						{
							String siteCodeValue = document.getElementsByTagName("SITE_CODE").item(0).getFirstChild().getNodeValue();
							BaseLogger.log("3",null,null," dnyaneshwar ---- siteCodeValue["+siteCodeValue+"]");
							String referer1 = request.getParameter("REFERER"); //$NON-NLS-1$
							if ( siteCodeValue.equalsIgnoreCase("INVALID_SITE") )
							{
								isUserAuthentic = false;
								if("MOBILE".equalsIgnoreCase(loginMode))
								{
									responseString = "alert('"+Messages.getString("AuthenticateServlet_NotValidSite",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/mobile/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
								}
								else if("TABPC".equalsIgnoreCase(loginClient))
								{
									responseString = "alert('"+Messages.getString("AuthenticateServlet_NotValidSite",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/ME/Login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
								}
								else if( request.getParameter("REFERER") != null && request.getParameter("REFERER").length() !=0 ) //$NON-NLS-1$ //$NON-NLS-2$
								{
									responseString = "alert('"+Messages.getString("AuthenticateServlet_NotValidSite",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp?REFERER="+referer1+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
								}
								else
								{
									if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
									{
										responseString = "alert('"+Messages.getString("AuthenticateServlet_NotValidSite",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
									}
									else
									{
										//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
										responseString = "alert('"+Messages.getString("AuthenticateServlet_NotValidSite",getUserLangAndCountry(userCode))+"');window.location.href = '"+href+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
										//Changed by Sandesh on 05/12/2016 [For Authentication API] End
									}
								}
								session.setAttribute( "USER_INFO", null ); //Added by Umakanta Das on 20-AUG-14[ Invalid site not working when loging 2nd time ]
							}
							else if ( siteCodeValue.equalsIgnoreCase("INACCESSIBLE_SITE")  )
							{
								isUserAuthentic = false;
								if("MOBILE".equalsIgnoreCase(loginMode))
								{
									responseString = "alert('"+Messages.getString("AuthenticateServlet_InAccessibleSite",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/mobile/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
								}
								else if("TABPC".equalsIgnoreCase(loginClient))
								{
									responseString = "alert('"+Messages.getString("AuthenticateServlet_InAccessibleSite",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/ME/Login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
								}
								else if( request.getParameter("REFERER") != null && request.getParameter("REFERER").length() !=0 ) //$NON-NLS-1$ //$NON-NLS-2$
								{
									responseString = "alert('"+Messages.getString("AuthenticateServlet_InAccessibleSite",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp?REFERER="+referer1+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
								}
								else
								{
									if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
									{
										responseString = "alert('"+Messages.getString("AuthenticateServlet_InAccessibleSite",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
									}
									else
									{
										//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
										responseString = "alert('"+Messages.getString("AuthenticateServlet_InAccessibleSite",getUserLangAndCountry(userCode))+"');window.location.href = '"+href+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
										//Changed by Sandesh on 05/12/2016 [For Authentication API] End
									}
								}
								session.setAttribute( "USER_INFO", null ); //Added by Umakanta Das on 20-AUG-14[ Invalid site not working when loging 2nd time ]
							}
							else if (isAUTHAPI.equalsIgnoreCase("true") && !E12GenericUtility.checkNull(applicationBean.getActive()).equalsIgnoreCase("T"))
							{
								isUserAuthentic = false;
								//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
								responseString = "alert('"+Messages.getString("AuthenticateServlet_InAccessibleSite",getUserLangAndCountry(userCode))+"');window.location.href = '"+href+"';";
								//Changed by Sandesh on 05/12/2016 [For Authentication API] End
								session.setAttribute( "USER_INFO", null );
							}
						}
						else
						{
							String profileID = ""; //$NON-NLS-1$
							if (document.getElementsByTagName("PROFILE_ID") != null && document.getElementsByTagName("PROFILE_ID").item(0) != null) //$NON-NLS-1$ //$NON-NLS-2$
							{
								profileID = document.getElementsByTagName("PROFILE_ID").item(0).getFirstChild().getNodeValue(); //$NON-NLS-1$
							}
						}
						//Added by Dnyaneshwar Chavan on 7-MAY-14 [ User should not be login when site value are 'INVALID_SITE' and 'INACCESSIBLE_SITE'  ] End

					}
					else if (statusCode.equalsIgnoreCase("FIRST_LOGIN")) //$NON-NLS-1$
					{
						// Changed by Abhishek T on 09-Oct-2019 [USER value can be email id, mobile etc.] START
						UserInfoBean basicUserInfo = getCommonDBAccess().getBasicUserInfo(userCode);
						userCode = basicUserInfo.getLoginCode();
						basicUserInfo = null;
						// Changed by Abhishek T on 09-Oct-2019 [USER value can be email id, mobile etc.] END
						
						isFirstLogin = true;
						//Changed by Hatim on 06/04/2007 to not pick up MIN_PWD_LENGTH at this stage, instead only when needed in case of change password.
						/*
						int minPwdLen = -1;
						if (document.getElementsByTagName("MIN_PWD_LENGTH") != null && document.getElementsByTagName("MIN_PWD_LENGTH").item(0) != null)
						{
							minPwdLen = Integer.parseInt(document.getElementsByTagName("MIN_PWD_LENGTH").item(0).getFirstChild().getNodeValue());
						}
						responseString = "alert('You have to compulsorily change your password , please do so');window.location.href='/ibase/jsp/ChangePassword.jsp?user="+userCode+"&site="+siteCode+"&minPwdLen="+minPwdLen+"&fromPage=welcome';";
						*/
						//Change by Nilesh on 17-01-11 [pass loginMode parameter]
						// Commented by Raju K on 30-01-14 for changing from ChangePassword to E12ChangePassword
						// responseString = "alert('"+Messages.getString("AuthenticateServlet_compulsoryChangePasswordPleaseDoSo")+"');window.location.href='/ibase/jsp/ChangePassword.jsp?user="+userCode+"&loginMode="+loginMode+"&site="+siteCode+"&fromPage=welcome';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
						//Changes made by Pratheek on 18-07-19[ passing passwordComplexity to differentiate the simple[1] and complex[2] values so to stop validation in changing password]-Start
						//Changed By Pankaj T. on 18-09-19 for getting PASSWORD_COMPLEXITY against user defined ENTERPRISE instead of ibase.xml - start
						String passWdComplexity = "";
						BaseLogger.log("3", null, null, "#### FIRST_LOGIN In AuthenticateServlet generateResponse CODE:["+userCode+"]");
						CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
						//Added by AMOL S. on 24-Jan-2020 [To resolve issue, if login other than code] START.
						userCode = commonDBAccessEJB.getBasicUserInfo(userCode).getLoginCode();
						//Added by AMOL S. on 24-Jan-2020 [To resolve issue, if login other than code] END.
						String transDB = commonDBAccessEJB.getDBColumnValue("USERS", "TRANS_DB", "WHERE CODE = '"+userCode+"'");
						BaseLogger.log("3", null, null, "In AuthenticateServlet generateResponse TRANS_DB:["+transDB+"]");
						
						String enterprise = commonDBAccessEJB.getDBColumnValue("USERS", "ENTERPRISE", "WHERE CODE = '"+userCode+"'");
						BaseLogger.log("3", null, null, "In AuthenticateServlet generateResponse ENTERPRISE against CODE:["+enterprise+"]");
						
						if( "".equals(E12GenericUtility.checkNull(enterprise)) )
						{
							BaseLogger.log("3", null, null, "In AuthenticateServlet generateResponse SITE_CODE against CODE:["+siteCode+"]");
							
							enterprise = commonDBAccessEJB.getDBColumnValue("SITE", "ENTERPRISE", "WHERE SITE_CODE = '"+siteCode+"'", transDB);
							BaseLogger.log("3", null, null, "In AuthenticateServlet generateResponse ENTERPRISE against SITE_CODE:["+enterprise+"]");
						}
						
						passWdComplexity = commonDBAccessEJB.getDBColumnValue("ENTERPRISE", "PASSWORD_COMPLEXITY", "WHERE ENTERPRISE = '"+enterprise+"'", transDB);
						BaseLogger.log("3",null,null,"In AuthenticateServlet generateResponse PASSWORD_COMPLEXITY against  ENTERPRISE:["+passWdComplexity+"]");
						//responseString = "alert('"+Messages.getString("AuthenticateServlet_compulsoryChangePasswordPleaseDoSo",getUserLangAndCountry(userCode))+"');window.location.href='/ibase/jsp/E12ChangePassword.jsp?user="+userCode+"&loginMode="+loginMode+"&site="+siteCode+"&passwordComplexity="+CommonConstants.PASSWORDCOMPLEXITY+"&fromPage=welcome';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
						responseString = "alert('"+Messages.getString("AuthenticateServlet_compulsoryChangePasswordPleaseDoSo",getUserLangAndCountry(userCode))+"');window.location.href='/ibase/jsp/E12ChangePassword.jsp?user="+userCode+"&loginMode="+loginMode+"&site="+siteCode+"&passwordComplexity="+passWdComplexity+"&fromPage=welcome';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
						//Changed By Pankaj T. on 18-09-19 for getting PASSWORD_COMPLEXITY against user defined ENTERPRISE instead of ibase.xml - end
						//Changes made by Pratheek on 18-07-19[ passing passwordComplexity to differentiate the simple[1] and complex[2] values so to stop validation in changing password]-End
					}
					//changed by gayatri on 12-03-2011 [MF01SUN034] start
					else if(statusCode.equalsIgnoreCase("ATTENDANCE_MISSING")) //$NON-NLS-1$
					{
						//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.start
						//responseString = "alert('"+Messages.getString("AuthenticateServlet_entryInDailyAttendanceNotFound")+"');window.location.href = '/ibase/jsp/login.html';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						//Changed By Mahesh Patidar on 06-SEP-13 [to redirect back to login.jsp if callerPage is JSP]
//						if(targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer))
						if((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer)) || (callerPage != null && "JSP".equalsIgnoreCase(callerPage)))
						{
							// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
							responseString = "alert('"+Messages.getString("AuthenticateServlet_entryInDailyAttendanceNotFound",getUserLangAndCountry(userCode))+"');window.location.href = '/ibase/jsp/login.jsp';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
						}
						else
						{
							// Changed by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
							//Changed by Sandesh on 05/12/2016 [For Authentication API] Start
							responseString = "alert('"+Messages.getString("AuthenticateServlet_entryInDailyAttendanceNotFound",getUserLangAndCountry(userCode))+"');window.location.href = '"+href+"';"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
							//Changed by Sandesh on 05/12/2016 [For Authentication API] End
						}
						//Changed by sumit sarkar on 11/11/11 [SY1GNOV001] To check target Customer.end

					}
					//changed by gayatri on 12-03-2011 [MF01SUN034] end

					//Added By Nilesh For RELEASE statusCode Start :: 15-02-18
					else if (statusCode.equalsIgnoreCase("RELEASE")) //$NON-NLS-1$
					{
						if ("MOBILE".equalsIgnoreCase(loginMode)) { //$NON-NLS-1$

							responseString = "alert('" //$NON-NLS-1$
									+ Messages.getString("AuthenticateServlet_employeeHasResigned", //$NON-NLS-1$
											getUserLangAndCountry(userCode))
									+ "');window.location.href = '/ibase/mobile/jsp/login.html';"; //$NON-NLS-1$
						}

						else if ("TABPC".equalsIgnoreCase(loginClient)) //$NON-NLS-1$
						{

							responseString = "alert('" //$NON-NLS-1$
									+ Messages.getString("AuthenticateServlet_employeeHasResigned", //$NON-NLS-1$
											getUserLangAndCountry(userCode))
									+ "');window.location.href = '/ibase/ME/Login.html';"; //$NON-NLS-1$
						}
						// Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve
						// the transactions from BlackBerry Phones and other handsets]end
						else {

							if ((targetCustomer != null && "NOVARTIS".equalsIgnoreCase(targetCustomer))
									|| (callerPage != null && "JSP".equalsIgnoreCase(callerPage))) {

								responseString = "alert('" //$NON-NLS-1$
										+ Messages.getString("AuthenticateServlet_employeeHasResigned", //$NON-NLS-1$
												getUserLangAndCountry(userCode))
										+ "');window.location.href = '/ibase/jsp/login.jsp';"; //$NON-NLS-1$
							} else {

								BaseLogger.log("3",null,null,"AuthenticateServlet_employeeHasResigned::"+responseString);
								responseString = "alert('" //$NON-NLS-1$
										+ Messages.getString("AuthenticateServlet_employeeHasResigned", //$NON-NLS-1$
												getUserLangAndCountry(userCode))
										+ "');window.location.href = '" + href + "';"; //$NON-NLS-1$

							}

						}
					}
					//Added By Nilesh For RELEASE statusCode End :: 15-02-18
					
					//Added By Nilesh For JOINDATE statusCode Start :: 15-02-18
					else if (statusCode.equalsIgnoreCase("JOINDATE")) //$NON-NLS-1$
					{
						
						BaseLogger.log("3",null,null,"AuthenticateServlet_employeeHas JOINDATE is blank statusCode::"+statusCode);
						if ("MOBILE".equalsIgnoreCase(loginMode)) { //$NON-NLS-1$

							responseString = "alert('" //$NON-NLS-1$
									+ Messages.getString("AuthenticateServlet_datejoinIsnull", //$NON-NLS-1$
											getUserLangAndCountry(userCode))
									+ "');window.location.href = '/ibase/mobile/jsp/login.html';"; //$NON-NLS-1$
						}

						else if ("TABPC".equalsIgnoreCase(loginClient)) //$NON-NLS-1$
						{

							responseString = "alert('" //$NON-NLS-1$
									+ Messages.getString("AuthenticateServlet_datejoinIsnull", //$NON-NLS-1$
											getUserLangAndCountry(userCode))
									+ "');window.location.href = '/ibase/ME/Login.html';"; //$NON-NLS-1$
						}
						// Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve
						// the transactions from BlackBerry Phones and other handsets]end
						else {


							BaseLogger.log("3",null,null,"AuthenticateServlet_employeeHas JOINDATE is blank::"+responseString);
							responseString = "alert('" //$NON-NLS-1$
									+ Messages.getString("AuthenticateServlet_datejoinIsnull", //$NON-NLS-1$
											getUserLangAndCountry(userCode))
									+ "');window.location.href = '" + href + "';"; //$NON-NLS-1$


						}
					}
					//Added By Nilesh For JOINDATE statusCode End :: 15-02-18
				}
				boolean writeResponse = true;

				if (document.getElementsByTagName( "DEVICE_STATUS" ).item(0) != null)
				{
					isUserAuthentic = false;
					writeResponse = false;
				}

				if( isUserAuthentic )
				{
					//Changed by as empInfo needs to be set always
					//Changed by Hatim on 19/09/2007 to reslove Unable to give feedback if password in grace period.Start
					/*if( request.getRequestURL().toString().indexOf( "/webitm/" ) != -1
							||
							( session.getAttribute( "REFERER" ) != null && ( ( String )session.getAttribute( "REFERER" ) ).indexOf( "/webitm/" ) != -1 ) )
					{*/
						/*reqDis = request.getRequestDispatcher( "/WebITMAuthenticateServlet" );
						reqDis.include( request, response );*/
						AppConnectParm appConnect = new AppConnectParm();
						InitialContext ctx = new InitialContext(appConnect.getProperty());
						//Changed By Rupali Hande on 24/03/08 [Remove dependacy of AuthenticateServlet from webitem].Request ID[BI78SUN047].Start
						//DBAccessHome dbAccessHome = (DBAccessHome) ctx.lookup( "DBAccess" );
						//DBAccessRemote dbAccess = dbAccessHome.create();
						/*CommonDBAccessHome dbAccessHome = (CommonDBAccessHome) ctx.lookup( "CommonDBAccess" );
						CommonDBAccess dbAccess = dbAccessHome.create();*/
						// Commented and Added by Pankaj R on 20-JUL-18 to change calling of EJB to JB [START]
						//CommonDBAccessRemote dbAccess = (CommonDBAccessRemote)ctx.lookup("ibase/CommonDBAccessEJB/remote"); //$NON-NLS-1$
						CommonDBAccessEJB dbAccess = new CommonDBAccessEJB();
						// Commented and Added by Pankaj R on 20-JUL-18 to change calling of EJB to JB [END]
						//Changed By Rupali Hande on 24/03/08 [Remove dependacy of AuthenticateServlet from webitem].Request ID[BI78SUN047].End
						//Commented global userinfo object by Pankaj T on 18-01-18 for resolving issue of display data of another user
						ibase.utility.UserInfoBean userInfo = ( ibase.utility.UserInfoBean )session.getAttribute( "USER_INFO" ); //$NON-NLS-1$
						//userInfo = ( ibase.utility.UserInfoBean )session.getAttribute( "USER_INFO" );
                        //change by shrutika on 19-12-2020 for Exception in application start 
                        //userInfo.setEmpInfo( dbAccess.getEmpInfo( userInfo.getLoginCode(), userInfo.getSiteCode(), userInfo.getTransDB() ) );
						if( userInfo != null )
						{
							userInfo.setEmpInfo( dbAccess.getEmpInfo( userInfo.getLoginCode(), userInfo.getSiteCode(), userInfo.getTransDB() ) );
                        }
                        //change by shrutika on 19-12-2020 for Exception in application end 
						session.setAttribute( "IS_EMP_INFO_SET", "true" ); //$NON-NLS-1$ //$NON-NLS-2$
					//}
					//Changed by Hatim on 19/09/2007 to reslove Unable to give feedback if password in grace period.End

					//Added by Dnyaneshwar Chavan on 17-JAN-14 [ Resolving the issue : Bug fixing, When 'Login_First' coloumn value is 'Y' in User table then not display message for change the password.  ]	Start
				    if ( ! isFirstLogin &&  isPwdExpired )
					{
						if(userInfo != null && ((String)session.getAttribute("IS_EMP_INFO_SET")).equalsIgnoreCase("true")) //$NON-NLS-1$ //$NON-NLS-2$
						{
							if(loginMode==null || loginMode.length()== 0 ){
								loginMode ="HTML version"; //$NON-NLS-1$
							}
							session.setAttribute("LOGINMODE", loginMode); //$NON-NLS-1$
						}
					}
					//Added by Dnyaneshwar Chavan on 17-JAN-14 [ Resolving the issue : Bug fixing, When 'Login_First' coloumn value is 'Y' in User table then not display message for change the password.  ]	End
					else if( ! isFirstLogin &&  ! isPwdExpired )
					{
						RequestDispatcher reqDis  = null;

						//Changed by Sandesh on 28/11/2016 [For Authentication API] Start
						 if (applicationBean != null && E12GenericUtility.checkNull(applicationBean.getActive()).equalsIgnoreCase("T") )
						 {
							redirectToURL(userCode, response, request);
						 }
						 // Changed by Sandesh on 06/01/2017 [For Authentication API: resolve authentication issue] Start
						 else
						 {
							 CommonConstants.isRedirect = false;
						 }
						 // Changed by Sandesh on 06/01/2017 [For Authentication API: resolve authentication issue] End
						//Changed by Sandesh on 28/11/2016 [For Authentication API] Start

						/*//Changed by Hatim on 19/09/2007 to reslove Unable to give feedback if password in grace period.Start
						BaseLogger.log("9",null,null, "request.getRequestURL() :["+request.getRequestURL()+"]");
						BaseLogger.log("9",null,null, "session.getAttribute( REFERER ) :["+session.getAttribute( "REFERER" )+"]");
						BaseLogger.log("9",null,null, "CONDN VALUE :["+( session.getAttribute( "REFERER" ) != null && ( ( String )session.getAttribute( "REFERER" ) ).indexOf( "/webitm/" ) != -1 ) +"]");
						if( request.getRequestURL().toString().indexOf( "/webitm/" ) != -1
							||
							( session.getAttribute( "REFERER" ) != null && ( ( String )session.getAttribute( "REFERER" ) ).indexOf( "/webitm/" ) != -1 ) )
						{
							/*reqDis = request.getRequestDispatcher( "/WebITMAuthenticateServlet" );
							reqDis.include( request, response );*/
							/*
							AppConnectParm appConnect = new AppConnectParm();
							InitialContext ctx = new InitialContext(appConnect.getProperty());
							DBAccessHome dbAccessHome = (DBAccessHome) ctx.lookup( "DBAccess" );
							DBAccessRemote dbAccess = dbAccessHome.create();
							ibase.utility.UserInfoBean userInfo = ( ibase.utility.UserInfoBean )session.getAttribute( "USER_INFO" );
							userInfo.setEmpInfo( dbAccess.getEmpInfo( userInfo.getLoginCode(), userInfo.getSiteCode() ) );
							session.setAttribute( "IS_EMP_INFO_SET", "true" );
						}*/
						//Changed by Hatim on 19/09/2007 to reslove Unable to give feedback if password in grace period.End

						//Changed by Rupali on 21/08/2008 to check the loginMode whether HTML /RIA version for RIA.Request ID[BI89BAS010].Start
						if(userInfo != null && ((String)session.getAttribute("IS_EMP_INFO_SET")).equalsIgnoreCase("true")) //$NON-NLS-1$ //$NON-NLS-2$
						{
							if(loginMode==null || loginMode.length()== 0 ){
								loginMode ="HTML version"; //$NON-NLS-1$
							}
							session.setAttribute("LOGINMODE", loginMode); //$NON-NLS-1$

							//Changed by Rupali for mobile login.Start
							if(loginMode.equalsIgnoreCase("MOBILE")){ //$NON-NLS-1$
								reqDis = request.getRequestDispatcher( "/mobile/jsp/MobileMenu.html" ); //$NON-NLS-1$
								reqDis.forward( request, response );
								writeResponse = false;
							}
							//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]start
							else if("TABPC".equalsIgnoreCase(loginClient)) //$NON-NLS-1$
							{
								reqDis = request.getRequestDispatcher( "/ME/ME12Redirect.jsp" ); //$NON-NLS-1$
								reqDis.forward( request, response );
								writeResponse = false;
							}
							//Changed by Rakesh on 31/08/10[MO90SUN032 || Enable users to view and approve the transactions from BlackBerry Phones and other handsets]end
							else{
									boolean isRebuild = false;
									if((riaCacheStatus.trim()).equalsIgnoreCase("1")) //$NON-NLS-1$
									{
										DashboardBean dashboarBean = new DashboardBean();
										dashboarBean.checkForBIUser(userCode, isBiuser);
										BaseLogger.log("3",null,null,"passing control to rebuildDashBorad function....................."); //$NON-NLS-1$
										TabManagerBean tabManagerbean = new TabManagerBean();
										isRebuild = tabManagerbean.rebuildDashboard(userCode,profId);
										BaseLogger.log("3",null,null,"isRebuild   ["+isRebuild+"]"); //$NON-NLS-1$ //$NON-NLS-2$
									}
									if(loginMode.equalsIgnoreCase("RIA version") || loginMode.equalsIgnoreCase("RIA Lite") ){ //$NON-NLS-1$ //$NON-NLS-2$
										//Changed by Dayanand on 16/08/10[To generate menu application wise || MF01SUN001]start
										/*if ( getMenuTree(userCode,profId,riaCacheStatus))
										{
											getCommonDBAccess().updadateRIACacheStatus(userCode,"0","S");
										}*/

										BaseLogger.log("3",null,null,"Bulding Menu tree");

										//Added by Dnyaneshwar on 6-Feb-2013 Start
										//if ( getMenuTree( userCode, profId, riaCacheStatus, applName) )
										//Commented and chnaged by Gulzar on 10/10/13 to pass userInfo for multidb connection: START
										//if ( getMenuTree( userCode, profId, riaCacheStatus, applName, false ) )
										if ( getMenuTree( userCode, profId, riaCacheStatus, applName, false, userInfo ) )
										{
											getCommonDBAccess().updadateRIACacheStatus(userCode,"0","S"); //$NON-NLS-1$ //$NON-NLS-2$
										}
										//Changed by Dayanand on 16/08/10[To generate menu application wise || MF01SUN001]end
									}
									else{
										if(isRebuild ==true){
											getCommonDBAccess().updadateRIACacheStatus(userCode,"0","S"); //$NON-NLS-1$ //$NON-NLS-2$
										}
									}
								}//loginMode.equalsIgnoreCase("MOBILE")
						//Changed by Rupali on 21/08/2008 to check the loginMode whether HTML /RIA version for RIA.Request ID[BI89BAS010].End
						}
						//Changed by Rupali for mobile login.End
						//Changed by Rupali on 21-11-2008 [taken the REFERER value from the request instead of session].Request ID[BI89SUN008]
						//if( session.getAttribute( "REFERER" ) != null  )
						//BaseLogger.log("9",null,null,"AuthenticateServlet : REFERER   ["+ request.getParameter("REFERER")+"]");
						//Changed by Rupali for mobile login
						if(!loginMode.equalsIgnoreCase("MOBILE")){ //$NON-NLS-1$
							String referer = request.getParameter("REFERER"); //$NON-NLS-1$
							if( request.getParameter("REFERER") != null && request.getParameter("REFERER").length() !=0 ) //$NON-NLS-1$ //$NON-NLS-2$
							{
								request.getSession().setAttribute("REFERER", referer); //$NON-NLS-1$
								reqDis = request.getRequestDispatcher( "/jsp/DirectAccess.jsp" ); //$NON-NLS-1$
								reqDis.forward( request, response );
								writeResponse = false;
							}
							else
							{
								if (!CommonConstants.isRedirect)
								{
									//Changed by Sandeep S. on 19-JAN-17 [To check session exist or not for same user on same or on another machine] Start
									if( !userSessionExist )
									{
										BaseLogger.log("3",null,null,"Called welcome.jsp if session exist");
										request.getSession().setAttribute("ACTION", "BROWSERLOGIN");
										request.getSession().setAttribute("USER", request.getParameter("USER"));
										request.getSession().setAttribute("MAC_ADDRESS", request.getParameter("MAC_ADDRESS"));
										reqDis = request.getRequestDispatcher( "/jsp/Welcome.jsp" ); //$NON-NLS-1$
										reqDis.forward( request, response );
									}
									else
									{
										BaseLogger.log("3",null,null,"Called welcome.jsp if session not exist");
										request.getSession().setAttribute("ACTION", "BROWSERLOGIN");
										request.getSession().setAttribute("USER", request.getParameter("USER"));
										request.getSession().setAttribute("MAC_ADDRESS", request.getParameter("MAC_ADDRESS"));
										String newHref = "/ibase/jsp/Welcome.jsp";
										//String responseStr  = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>alert('Session is already exist for "+request.getParameter("USER")+"');window.location.href = '"+newHref+"'</SCRIPT></HEAD></HTML>"; //window.location.href = '"+newHref+"'
										String responseStr  = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>if(confirm('There is another session is running with this User ID. Terminate the running session?')){window.location.href = '"+newHref+"'}else{window.location.href = '"+newHref+"?removeCurrentSession=true'} </SCRIPT></HEAD></HTML>"; //window.location.href = '"+newHref+"'
										BaseLogger.log("3",null,null,"writeReponse    responseString    " + responseStr);
										response.setBufferSize(responseString.length());
								        response.setContentType( "text/html; charset=UTF8,"+CommonConstants.ENCODING );
										OutputStream outputStream = response.getOutputStream();
										outputStream.write(responseStr.getBytes());
										outputStream.flush();
										outputStream.close();
									}
									//Changed by Sandeep S. on 19-JAN-17 [To check session exist or not for same user on same or on another machine] End
								}
								writeResponse = false;
							}
						}//loginMode.equalsIgnoreCase("MOBILE")
					}
				}
				//Changes made by Gulzar on 30/01/15 :START
				else
				{
					HttpSession sessObj = request.getSession(false);
					if(sessObj != null)
					{
						BaseLogger.log("3",null,null,"AuthenticateServlet >>  generateResponse >> Invalidating the session and updating the logintrace............::"+userCode);
						sessObj.invalidate();
						getCommonDBAccess().updateLoginTrace(userCode, sessObj.getId());
					}
				}
				//Changes made by Gulzar on 30/01/15 :END

				if (writeResponse)
				{
					BaseLogger.log("3",null,null,"writeReponse    responseString    " + responseString); //$NON-NLS-1$
					responseString = "<HTML><HEAD><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><SCRIPT language=JAVASCRIPT>"+responseString+"</SCRIPT></HEAD></HTML>"; //$NON-NLS-1$ //$NON-NLS-2$
					response.setBufferSize(responseString.length());

					//Added by Dnyaneshwar Chavan on 24-OCT-13 [CO3ASUN005] [ Resolved the issue of when response in Russian language or etc.  ] START
					//response.setContentType("text/html");
			        response.setContentType( "text/html; charset=UTF8,"+CommonConstants.ENCODING );
			        //Added by Dnyaneshwar Chavan on 24-OCT-13 [CO3ASUN005] [ Resolved the issue of when response in Russian language or etc.  ] END

					OutputStream outputStream = response.getOutputStream();
					outputStream.write(responseString.getBytes());
					outputStream.flush();
					outputStream.close();
				}
			}
		}
		catch( BaseException be )
		{
			BaseLogger.log("0",null,null,"Exception: generateResponse:==>\n"+be); //$NON-NLS-1$
			throw be;
		}
		catch( Exception e )
		{
			BaseLogger.log("0",null,null,"Exception: generateResponse:==>\n"+e); //$NON-NLS-1$
			throw new BaseException( e );
		}
		return isUserAuthentic;
	}

	//Changed by Manish on 07/11/2006 to update login trace on logout.
	public void logout( String user ,String sessionId) throws BaseException
	{
		//Added By Mahesh Patidar on 08/MAR/13[WI2LSUN001 || to remove user Session info entry]
		HashMap applLevUserInfo =null;
		if(this.servletContext != null)
		{
			if ( servletContext.getAttribute("applLevUserInfo") != null) //$NON-NLS-1$
			{
				applLevUserInfo = (HashMap)servletContext.getAttribute("applLevUserInfo");	 //$NON-NLS-1$
				//Changed By Pankaj T. on 24-07-19 for session not remove from map when user login using USER_ID,EMAIL_ID or MOBILE_NO instead of code  
				applLevUserInfo.remove(user.trim()+":"+sessionId); //$NON-NLS-1$
				// Added by Raju K on02-05-14 for Event log and Transaction lock as per danish sir start--
				//changed By Mahesh Patidar on 01/AUG/13[WI3DSUN001|to remove locked transaction from session and remove user session activity from activity log]
//				Set<String> lockedEditorSet = (Set<String>) this.servletContext.getAttribute("TRANLOCK_"+sessionId);
				try {
					EventLogInfoBean eventInfoBean = new EventLogInfoBean(user);
					eventInfoBean.removeSessionActivity(sessionId);
					// Commented by Raju K on 10-Sep-14 for Memory Leak Issue in Transaction Lock as per Dnyaneshwar
					/*TranScopeBean tranScopeBean = new TranScopeBean();
					tranScopeBean.removeLockTransInfo(lockedEditorSet);*/
				} catch (Exception e) {
					e.printStackTrace();
				}
//				this.servletContext.removeAttribute("TRANLOCK_"+sessionId);
				//Ended By Mahesh Patidar on 01/AUG/13[WI3DSUN001|to remove locked transaction from session and remove user session activity from activity log]
				// Ended by Raju K on02-05-14 for Event log and Transaction lock as per danish sir End--
			}
		}
		//Ended By Mahesh Patidar
		try
		{
			getCommonDBAccess().updateSessionTrace(user,sessionId);
		}
		catch (BaseException base)
		{
			BaseLogger.log("0",null,null,"BaseException :AuthenticateServlet :logout() :==>\n"+base.getMessage()); //$NON-NLS-1$
			throw base;
		}
		catch (Exception e)
		{
			BaseLogger.log("0",null,null,"Exception :AuthenticateServlet :logout() :==>\n"+e.getMessage()); //$NON-NLS-1$
			throw new BaseException(e);
		}

	}

	protected boolean getAuthenticationStatus( String xmlInfo ) throws BaseException
	{
		boolean flag = false;
		try
		{
			Document document = new E12GenericUtility().parseString(xmlInfo);
			if (document.getElementsByTagName( "STATUS" ).item(0) != null) //$NON-NLS-1$
			{
				flag = (Boolean.valueOf(document.getElementsByTagName("STATUS").item(0).getFirstChild().getNodeValue())).booleanValue(); //$NON-NLS-1$
			}
		}
		catch( BaseException be )
		{
			BaseLogger.log("0",null,null,"Exception: getAuthenticationStatus:==>\n"+be); //$NON-NLS-1$
			throw be;
		}
		catch( Exception e )
		{
			BaseLogger.log("0",null,null,"Exception: getAuthenticationStatus:==>\n"+e); //$NON-NLS-1$
			throw new BaseException( e );
		}
		BaseLogger.log("2",null,null, "Returning parsed final authentication status :[" + flag + "]" ); //$NON-NLS-1$ //$NON-NLS-2$
		return flag;
	}

	private ibase.utility.UserInfoBean createUserInfo( String user, String passwd, Document document ) throws BaseException
	{
		ibase.utility.UserInfoBean userInfo = null;
		try
		{
			userInfo = new ibase.utility.UserInfoBean();
			// Commented by Abhishek on 11.03.2016 [Authentication changes] START
			  // userInfo.setLoginCode( user );
			// Commented by Abhishek on 11.03.2016 [Authentication changes] END
			userInfo.setLoginPwd( passwd );

			// Added by Abhishek on 11.03.2016 [Req Id : S15LBAS004 Authentication changes] START
			String temp = null;
			if (document.getElementsByTagName("USER_CODE").item(0) != null) { //$NON-NLS-1$
				userInfo.setLoginCode(temp = document.getElementsByTagName("USER_CODE").item(0).getFirstChild().getNodeValue());  //$NON-NLS-1$
			}
			if (document.getElementsByTagName("ENTRY_ID").item(0) != null) { //$NON-NLS-1$
				userInfo.setEntryId(temp = document.getElementsByTagName("ENTRY_ID").item(0).getFirstChild().getNodeValue());  //$NON-NLS-1$
			}
			if (document.getElementsByTagName("ENTRY_TYPE").item(0) != null) { //$NON-NLS-1$
				userInfo.setEntryType(temp = document.getElementsByTagName("ENTRY_TYPE").item(0).getFirstChild().getNodeValue());  //$NON-NLS-1$
			}
			// Added by Abhishek on 11.03.2016 [Req Id : S15LBAS004 Authentication changes] END

			if (document.getElementsByTagName("PROFILE_ID").item(0) != null) //$NON-NLS-1$
			{
				userInfo.setProfileId(document.getElementsByTagName("PROFILE_ID").item(0).getFirstChild().getNodeValue()); //$NON-NLS-1$
			}
			if (document.getElementsByTagName("EMP_CODE").item(0) != null) //$NON-NLS-1$
			{
				userInfo.setEmpCode(document.getElementsByTagName("EMP_CODE").item(0).getFirstChild().getNodeValue()); //$NON-NLS-1$
			}
			if (document.getElementsByTagName("EMP_FNAME").item(0) != null) //$NON-NLS-1$
			{
				userInfo.setEmpFName(document.getElementsByTagName("EMP_FNAME").item(0).getFirstChild().getNodeValue()); //$NON-NLS-1$
			}
			if (document.getElementsByTagName("EMP_MNAME").item(0) != null) //$NON-NLS-1$
			{
				userInfo.setEmpMName(document.getElementsByTagName("EMP_MNAME").item(0).getFirstChild().getNodeValue()); //$NON-NLS-1$
			}
			if (document.getElementsByTagName("EMP_LNAME").item(0) != null) //$NON-NLS-1$
			{
				userInfo.setEmpLName(document.getElementsByTagName("EMP_LNAME").item(0).getFirstChild().getNodeValue()); //$NON-NLS-1$
			}
			if (document.getElementsByTagName("SITE_CODE").item(0) != null) //$NON-NLS-1$
			{
				userInfo.setSiteCode(document.getElementsByTagName("SITE_CODE").item(0).getFirstChild().getNodeValue()); //$NON-NLS-1$
			}
			if (document.getElementsByTagName("IS_BI_USER").item(0) != null) //$NON-NLS-1$
			{
				userInfo.setIsBIUser(document.getElementsByTagName("IS_BI_USER").item(0).getFirstChild().getNodeValue()); //$NON-NLS-1$
			}
			//Changed by Pragyan on 11/08/07 to contain respource profile id.Start
			if ( document.getElementsByTagName( "PROFILE_ID__RES" ).item(0) != null && document.getElementsByTagName( "PROFILE_ID__RES" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setProfileIdRes(document.getElementsByTagName( "PROFILE_ID__RES" ).item(0).getFirstChild().getNodeValue() ); //$NON-NLS-1$
			}
//			Changed by Pragyan on 11/08/07 to contain respource profile id.End
			//Changed by Rupali Hande on 26-08-2008 [to add the logger_status in userInfo]Request ID:-[BI89SUN007].Start
			if ( document.getElementsByTagName( "LOGGER_TYPE" ).item(0) != null && document.getElementsByTagName( "LOGGER_TYPE" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setLoggerType(document.getElementsByTagName( "LOGGER_TYPE" ).item(0).getFirstChild().getNodeValue() ); //$NON-NLS-1$
			}
			//Changed by Rupali Hande on 26-08-2008 [to add the logger_status in userInfo]Request ID:-[BI89SUN007].End
			//Changed by Swapnil Shirke on 01-Jul-2010 [to add stan_code__hq, designation, dateOfJoining, division in userInfo][WS90SUN043] starts
			if ( document.getElementsByTagName( "STAN_CD__HQ_DESCR" ).item(0) != null && document.getElementsByTagName( "STAN_CD__HQ_DESCR" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setStanCode(document.getElementsByTagName( "STAN_CD__HQ_DESCR" ).item(0).getFirstChild().getNodeValue() ); //$NON-NLS-1$
			}
			//Commented and changes below by Gulzar as below code is wrong and proper method is not called
			/*if ( document.getElementsByTagName( "DESIGNATION" ).item(0) != null && document.getElementsByTagName( "STAN_CD__HQ_DESCR" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setStanCode(document.getElementsByTagName( "DESIGNATION" ).item(0).getFirstChild().getNodeValue() ); //$NON-NLS-1$
			}
			if ( document.getElementsByTagName( "DATE_JOIN" ).item(0) != null && document.getElementsByTagName( "STAN_CD__HQ_DESCR" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setStanCode(document.getElementsByTagName( "DATE_JOIN" ).item(0).getFirstChild().getNodeValue() ); //$NON-NLS-1$
			}*/

			if ( document.getElementsByTagName( "DESIGNATION" ).item(0) != null && document.getElementsByTagName( "DESIGNATION" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setDesignation(document.getElementsByTagName( "DESIGNATION" ).item(0).getFirstChild().getNodeValue() ); //$NON-NLS-1$
			}
			if ( document.getElementsByTagName( "DATE_JOIN" ).item(0) != null && document.getElementsByTagName( "DATE_JOIN" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setDateJoin(document.getElementsByTagName( "DATE_JOIN" ).item(0).getFirstChild().getNodeValue() ); //$NON-NLS-1$
			}
			//Commented and changes below by Gulzar as below code is wrong

			//Changed by Swapnil Shirke on 01-Jul-2010 [to add stan_code__hq, designation, dateOfJoining, division in userInfo][WS90SUN043] ends
			//Added By Shahu Mali on 08-10-13.[WS3GBAS001].START
			if ( document.getElementsByTagName( "TRANS_DB" ).item(0) != null && document.getElementsByTagName( "TRANS_DB" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
                userInfo.setTransDB(document.getElementsByTagName( "TRANS_DB" ).item(0).getFirstChild().getNodeValue() ); //$NON-NLS-1$
                //Added By Vikas Lagad on 17-11-20[set IN_MEMORY credential in userInfo] Start
                if( document.getElementsByTagName( "TRANS_DB" ).item(0).getFirstChild().getNodeValue().length() > 0)
                {
                    CommonDBAccessEJB commonAccessDB = new CommonDBAccessEJB();
                    commonAccessDB.setUserInfoInMem(userInfo.getTransDB(),userInfo); 
                }
                 //Added By Vikas Lagad on 17-11-20[set IN_MEMORY credential in userInfo] End
			}
			//Added By Shahu Mali on 08-10-13.[WS3GBAS001].END

			//Added by Prajyot 18MAR2014[Theme Implementation.]Start
			if ( document.getElementsByTagName( "USER_THEME" ).item(0) != null && document.getElementsByTagName( "USER_THEME" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setUserTheme( document.getElementsByTagName( "USER_THEME" ).item(0).getFirstChild().getNodeValue() ); //$NON-NLS-1$
			}
			//Added by Vishal Pathare on 4-AUG-2016 [getting <ux_interface> for applying themes]
			if ( document.getElementsByTagName( "UX_INTERFACE" ).item(0) != null && document.getElementsByTagName( "UX_INTERFACE" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setUxInterface( document.getElementsByTagName( "UX_INTERFACE" ).item(0).getFirstChild().getNodeValue() ); //$NON-NLS-1$
			}
			//Added by Prajyot 18MAR2014[Theme Implementation.]End
			//Added by Dnyaneshwar Chavan on 30-Jul-15 [ Implement Geo fencing functionality  ] Start
			if ( document.getElementsByTagName( "USER_GEO_FENCE_ENABLED" ).item(0) != null && document.getElementsByTagName( "USER_GEO_FENCE_ENABLED" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setUserGeoFence( document.getElementsByTagName( "USER_GEO_FENCE_ENABLED" ).item(0).getFirstChild().getNodeValue() ); //$NON-NLS-1$
			}
			//Added by Dnyaneshwar Chavan on 30-Jul-15 [ Implement Geo fencing functionality  ] End
			// Added by Sandeshs 09-Feb-2016 [Req:S15JBAS002 Social Post] START
			if ( document.getElementsByTagName( "USER_NAME" ).item(0) != null && document.getElementsByTagName( "USER_NAME" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setUserName(document.getElementsByTagName( "USER_NAME" ).item(0).getFirstChild().getNodeValue() ); //$NON-NLS-1$
			}
			// Added by Sandeshs 09-Feb-2016 [Req:S15JBAS002 Social Post] END

			// Added by Sandeshs 23-Feb-2016 [Req:S15KBAS001 Social Post] START
			if ( document.getElementsByTagName( "IS_PASSWORD_STORE" ).item(0) != null && document.getElementsByTagName( "IS_PASSWORD_STORE" ).item(0).getFirstChild() != null )
			{
				userInfo.setIsPasswordStore(document.getElementsByTagName( "IS_PASSWORD_STORE" ).item(0).getFirstChild().getNodeValue() );
			}
			// Added by Sandeshs 23-Feb-2016 [Req:S15KBAS001 Social Post] END

			// Added by Sandeshs 21-Jun-2016 [Req:W15BSUN011] START
			if ( document.getElementsByTagName( "DEFAULT_MENU" ).item(0) != null && document.getElementsByTagName( "DEFAULT_MENU" ).item(0).getFirstChild() != null )
			{
				userInfo.setDefaultMenu(document.getElementsByTagName( "DEFAULT_MENU" ).item(0).getFirstChild().getNodeValue() );
			}
			// Added by Sandeshs 21-Jun-2016 [Req:W15BSUN011] END
			//Added By Suraj on 20-March-2017 [To configure slide menu footer options ]Start
			if ( document.getElementsByTagName( "FEATURES" ).item(0) != null && document.getElementsByTagName( "FEATURES" ).item(0).getFirstChild() != null )
			{
				userInfo.setFeatures( document.getElementsByTagName( "FEATURES" ).item(0).getFirstChild().getNodeValue() );
			}
			//Added By Suraj on 20-March-2017 [To configure slide menu footer options ]End
			//Added by Pankaj R on 26-Oct-17 to add a enterprise image in this column [STARt]
			if ( document.getElementsByTagName( "ENTERPRISE" ).item(0) != null && document.getElementsByTagName( "ENTERPRISE" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setEnterprise( document.getElementsByTagName( "ENTERPRISE" ).item(0).getFirstChild().getNodeValue() ); //$NON-NLS-1$
			}
			//Added by Pankaj R on 26-Oct-17 to add a enterprise image in this column [END]
			
			//Added by jay - to set the social_opt [Start]
			if ( document.getElementsByTagName( "SOCIAL_OPT" ).item(0) != null && document.getElementsByTagName( "SOCIAL_OPT" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setSocialOpt( document.getElementsByTagName( "SOCIAL_OPT" ).item(0).getFirstChild().getNodeValue() ); //$NON-NLS-1$
			}
			//Added by jay - to set the social_opt [End]

			//Added by Sagar B. to track GPS configuration on user level on [11-JAN-18]START
			if ( document.getElementsByTagName( "USER_GEO_POS_OPTION" ).item(0) != null && document.getElementsByTagName( "USER_GEO_POS_OPTION" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setGeoPosOption(( document.getElementsByTagName( "USER_GEO_POS_OPTION" ).item(0).getFirstChild().getNodeValue()) ); //$NON-NLS-1$
			}
			//Added by Sagar B. to track GPS configuration on user level on [11-JAN-18]END
			//Added by Sagar B. to show descr in slide menu panel[18-Sep-18]START
			if ( document.getElementsByTagName( "ENTERPRISE_DESCR" ).item(0) != null && document.getElementsByTagName( "ENTERPRISE_DESCR" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setEnterpriseDescr( document.getElementsByTagName( "ENTERPRISE_DESCR" ).item(0).getFirstChild().getNodeValue() ); //$NON-NLS-1$
			}
			//Added by Sagar B. to show descr in slide menu panel[18-Sep-18]END
			//Added by Sagar B. to track GPS configuration on user level on [11-JAN-18]START
			if ( document.getElementsByTagName( "NETWORK_OPTION" ).item(0) != null && document.getElementsByTagName( "NETWORK_OPTION" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setUserNetworkOption(( document.getElementsByTagName( "NETWORK_OPTION" ).item(0).getFirstChild().getNodeValue()) ); //$NON-NLS-1$
			}
			//Added by Sagar B. to track GPS configuration on user level on [11-JAN-18]END
			//Added by Sagar B. to set offline edit/delete configuration enterprise-wise[13-Mar-19]START
			if ( document.getElementsByTagName( "IS_ALLOW_OFFLINE_EDIT" ).item(0) != null && document.getElementsByTagName( "IS_ALLOW_OFFLINE_EDIT" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setIsAllowOfflineEdit(( document.getElementsByTagName( "IS_ALLOW_OFFLINE_EDIT" ).item(0).getFirstChild().getNodeValue()) ); //$NON-NLS-1$
			}
			if ( document.getElementsByTagName( "IS_ALLOW_OFFLINE_DELETE" ).item(0) != null && document.getElementsByTagName( "IS_ALLOW_OFFLINE_DELETE" ).item(0).getFirstChild() != null ) //$NON-NLS-1$ //$NON-NLS-2$
			{
				userInfo.setIsAllowOfflineDelete(( document.getElementsByTagName( "IS_ALLOW_OFFLINE_DELETE" ).item(0).getFirstChild().getNodeValue()) ); //$NON-NLS-1$
			}
			//Added by Sagar B. to set offline edit/delete configuration enterprise-wise[13-Mar-19]END
			//Changed By Pankaj T. on 21-10-19 set USER_CODE, MOBILE_NO, EMAIL_ID of user in userInfo - start
			if ( document.getElementsByTagName( "USER_ID" ).item(0) != null && document.getElementsByTagName( "USER_ID" ).item(0).getFirstChild() != null )
			{
				userInfo.setLoginUserId(( document.getElementsByTagName( "USER_ID" ).item(0).getFirstChild().getNodeValue()) );
			}
			if ( document.getElementsByTagName( "MOBILE_NO" ).item(0) != null && document.getElementsByTagName( "MOBILE_NO" ).item(0).getFirstChild() != null )
			{
				userInfo.setLoginMobileNo(( document.getElementsByTagName( "MOBILE_NO" ).item(0).getFirstChild().getNodeValue()) );
			}
			if ( document.getElementsByTagName( "EMAIL_ID" ).item(0) != null && document.getElementsByTagName( "EMAIL_ID" ).item(0).getFirstChild() != null )
			{
				userInfo.setLoginEmailId(( document.getElementsByTagName( "EMAIL_ID" ).item(0).getFirstChild().getNodeValue()) );
			}
			//Changed By Pankaj T. on 21-10-19 set USER_CODE, MOBILE_NO, EMAIL_ID of user in userInfo - end
			
			//Added by pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - start
			if ( document.getElementsByTagName( "SMTP_HOST" ).item(0) != null && document.getElementsByTagName( "SMTP_HOST" ).item(0).getFirstChild() != null )
			{
				userInfo.setSmtpHost(( document.getElementsByTagName( "SMTP_HOST" ).item(0).getFirstChild().getNodeValue()) );
			}
			if ( document.getElementsByTagName( "SMTP_PORT" ).item(0) != null && document.getElementsByTagName( "SMTP_PORT" ).item(0).getFirstChild() != null )
			{
				userInfo.setSmtpPort(( document.getElementsByTagName( "SMTP_PORT" ).item(0).getFirstChild().getNodeValue()) );
			}
			if ( document.getElementsByTagName( "SMTP_USER" ).item(0) != null && document.getElementsByTagName( "SMTP_USER" ).item(0).getFirstChild() != null )
			{
				userInfo.setSmtpUser(( document.getElementsByTagName( "SMTP_USER" ).item(0).getFirstChild().getNodeValue()) );
			}
			if ( document.getElementsByTagName( "SMTP_PASS_WD" ).item(0) != null && document.getElementsByTagName( "SMTP_PASS_WD" ).item(0).getFirstChild() != null )
			{
				userInfo.setSmtpPassWD(( document.getElementsByTagName( "SMTP_PASS_WD" ).item(0).getFirstChild().getNodeValue()) );
			}
			if ( document.getElementsByTagName( "SMTP_PROTOCOL_TYPE" ).item(0) != null && document.getElementsByTagName( "SMTP_PROTOCOL_TYPE" ).item(0).getFirstChild() != null )
			{
				userInfo.setSmtpProtocolType(( document.getElementsByTagName( "SMTP_PROTOCOL_TYPE" ).item(0).getFirstChild().getNodeValue()) );
			}
			if ( document.getElementsByTagName( "SMTP_MAILFROM" ).item(0) != null && document.getElementsByTagName( "SMTP_MAILFROM" ).item(0).getFirstChild() != null )
			{
				userInfo.setSmtpMailFrom(( document.getElementsByTagName( "SMTP_MAILFROM" ).item(0).getFirstChild().getNodeValue()) );
			}
			if ( document.getElementsByTagName( "ADMIN_EMAIL_ID" ).item(0) != null && document.getElementsByTagName( "ADMIN_EMAIL_ID" ).item(0).getFirstChild() != null )
			{
				userInfo.setAdminEmailId(( document.getElementsByTagName( "ADMIN_EMAIL_ID" ).item(0).getFirstChild().getNodeValue()) );
			}
            //Added by pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE - end
             //Added by Pankajt T on 14-09-2020 for The user icon which shows detail information about user should also show Login using User id/Mobile/email and user_id/mobile/email value
            if ( document.getElementsByTagName( "AUTHENTICATED_USING" ).item(0) != null && document.getElementsByTagName( "AUTHENTICATED_USING" ).item(0).getFirstChild() != null )
			{
				userInfo.setAuthenticatedUsing(( document.getElementsByTagName( "AUTHENTICATED_USING" ).item(0).getFirstChild().getNodeValue()) );
            }
             //Added by Pankajt T on 14-09-2020 for The user icon which shows detail information about user should also show Login using User id/Mobile/email and user_id/mobile/email value
            //Added by Jatin M on 24-Jun-2022 [To set prior session timeout in UserInfoBean] - START
            if ( document.getElementsByTagName( "SESS_TIMEOUT_SEC" ).item(0) != null && document.getElementsByTagName( "SESS_TIMEOUT_SEC" ).item(0).getFirstChild() != null )
			{
				userInfo.setSessTimeoutInSec(( document.getElementsByTagName( "SESS_TIMEOUT_SEC" ).item(0).getFirstChild().getNodeValue()) );
            }
          //Added by Jatin M on 24-Jun-2022 [To set prior session timeout in UserInfoBean] - END
			BaseLogger.log("0", userInfo, null, "Userinfo inAuthenticateServlet createUsrInfo():["+userInfo+"]");
		}
		catch( Exception e )
		{
			BaseLogger.log("0",null,null,"Exception: createUserInfo:==>\n"+e); //$NON-NLS-1$
			throw new BaseException( e );
		}
		BaseLogger.log("2",null,null, "UserInfoBean Created....." ); //$NON-NLS-1$
		return userInfo;
	}
	//Two new arguement added by sadique 25-6-2019 for change password
	protected void secureAccount(String user, String resType,String clientIP,String deviceUuId) throws BaseException
	{
		try
		{
			//Below code comment and Two new arguement added by sadique 25-6-2019 for change password
			//getCommonDBAccess().secureAccount( user, resType, getCommonDBAccess().createUserInfo(user));
			//Changed by Pooja S on 6-NOV-2020 [passord should sent from common definition, not from enterprise]
			getCommonDBAccess().secureAccount( user, resType, getCommonDBAccess().createUserInfo(user, "code", false),clientIP, deviceUuId);
		}
		catch( BaseException be )
		{
			BaseLogger.log("0",null,null,"Exception: secureAccount:==>\n"+be); //$NON-NLS-1$
			throw be;
		}
		catch( Exception e )
		{
			BaseLogger.log("0",null,null,"Exception: secureAccount:==>\n"+e); //$NON-NLS-1$
			throw new BaseException( e );
		}
	}

	public void updateGraceCount(String user) throws BaseException
	{
		try
		{
			getCommonDBAccess().updateGraceCount( user );
		}
		catch( BaseException be )
		{
			BaseLogger.log("0",null,null,"Exception: updateGraceCount:==>\n"+be); //$NON-NLS-1$
			throw be;
		}
		catch( Exception e )
		{
			BaseLogger.log("0",null,null,"Exception: updateGraceCount:==>\n"+e); //$NON-NLS-1$
			throw new BaseException( e );
		}
	}

	//private CommonDBAccessRemote getCommonDBAccess() throws BaseException
	private CommonDBAccessEJB getCommonDBAccess() throws BaseException
	{
		// Commented and Added by Pankaj R on 20-JUL-18 to change calling of EJB to JB [START]
		// CommonDBAccessRemote ejbObj = null;
		CommonDBAccessEJB ejbObj = null;
		// Commented and Added by Pankaj R on 20-JUL-18 to change calling of EJB to JB [END]
		try
		{
			AppConnectParm appConnect = new AppConnectParm();
			Properties p = appConnect.getProperty();
			InitialContext ctx = new InitialContext(p);
			BaseLogger.log("3",null,null,"Looking Up for CommonDBAccess EJB with Properties==>\n"+p); //$NON-NLS-1$
			/*CommonDBAccessHome home = (CommonDBAccessHome)ctx.lookup("CommonDBAccess");
			ejbObj = home.create();*/
			// Commented and Added by Pankaj R on 20-JUL-18 to change calling of EJB to JB [START]
			// ejbObj = (CommonDBAccessRemote)ctx.lookup("ibase/CommonDBAccessEJB/remote"); //$NON-NLS-1$
			ejbObj = new CommonDBAccessEJB();
			// Commented and Added by Pankaj R on 20-JUL-18 to change calling of EJB to JB [END]
		}
		catch( BaseException be )
		{
			BaseLogger.log("0",null,null,"Exception: getCommonDBAccess:==>\n"+be); //$NON-NLS-1$
			throw be;
		}
		catch( Exception e )
		{
			BaseLogger.log("0",null,null,"Exception: getCommonDBAccess:==>\n"+e); //$NON-NLS-1$
			throw new BaseException( e );
		}
		return ejbObj;
	}
	private void setLogger() throws BaseException
	{
		try
		{
			//BaseLogger.log("9",null,null,"this.servletContext.getRealPath(/)["+this.servletContext.getRealPath("/")+"]");
			CommonConstants.setAPPLICATION_CONTEXT(this.servletContext.getRealPath("/")); //$NON-NLS-1$

			//Changes done by Gaurav Singh on 13-JUL-2016 [ setIBASEHOME only when TOMCAT_HOME is null | Start ]
			//CommonConstants.setIBASEHOME();
			//CommonConstants.setBIHOME();
			CommonConstants.getInterfaceDetails();
			if(CommonConstants.TOMCAT_HOME == null || CommonConstants.TOMCAT_HOME.trim().length() == 0)
			{
				CommonConstants.setIBASEHOME();
				CommonConstants.setBIHOME();
			}
			//Changes done by Gaurav Singh on 13-JUL-2016 [ setIBASEHOME only when TOMCAT_HOME is null | End ]

			PrintStream outVal = System.out;
			/*if( CommonConstants.LOGGER_TYPE.equalsIgnoreCase("F") || ( CommonConstants.LOGGER_TYPE.equalsIgnoreCase("C") && CommonConstants.DEBUG_LEVEL.equals("0")) ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
			{
				String fileName = CommonConstants.LOG_PATH + File.separator + "temp.txt"; //$NON-NLS-1$
				File file = new File(fileName);
				PrintStream printStream = new BasePrintStream(new FileOutputStream(file));
				System.setOut(printStream);
			}*/
		}
		catch (BaseException e)
		{
			System.err.println("BaseException :AuthenticateServlet :writeMessage() :==>\n"+e.getMessage()); //$NON-NLS-1$
			throw e;
		}
		catch (Exception e)
		{
			System.err.println("Exception :AuthenticateServlet :writeMessage() :==>\n"+e.getMessage()); //$NON-NLS-1$
			throw new BaseException(e);
		}
	}

	//changed by Rajesh 12/27/2007[New method to set application level info  ].start
	private void setApplLevelUserInfo( HttpServletRequest request, String hostName, String hostIP, String deviceType ) throws Exception
	{
		InternalLogger.log("0",null,null,"AuthenticateServlet.setApplLevelUserInfo()");
		HashMap applLevUserInfo = new HashMap();
		HashMap userDet = new HashMap();
		//Commented By Mahesh Patidar on 7/MAR/13[WI2LSUN001 || to remove userSession map dependency]
//		HashMap usersSession = new HashMap();
		HttpSession session = request.getSession();
		String userCode = request.getParameter( "USER" ); //$NON-NLS-1$
		BaseLogger.log("3",null,null," \n\n\n\n " ); //$NON-NLS-1$
		BaseLogger.log("3",null,null,"Get requested Session Id"+request.getRequestedSessionId()); //$NON-NLS-1$
//		BaseLogger.log("9",null,null,"isRequestedSessionIdValid"+request.isRequestedSessionIdValid());
//		BaseLogger.log("9",null,null, "session.isNew()"+session.isNew() );
//		BaseLogger.log("9",null,null, "session.getId()"+session.getId() );
		BaseLogger.log("3",null,null," \n\n\n\n " ); //$NON-NLS-1$
		UserSessionInfoBean sib = new UserSessionInfoBean();
		//Commented global userinfo object by Pankaj T on 18-01-18 for resolving issue of display data of another user
		ibase.utility.UserInfoBean userInfo = ( ibase.utility.UserInfoBean )request.getSession().getAttribute( "USER_INFO" ); //$NON-NLS-1$
		//userInfo = ( ibase.utility.UserInfoBean )request.getSession().getAttribute( "USER_INFO" ); //$NON-NLS-1$
		//BaseLogger.log("9",null,null," \n\n\n\n [[userInfo]] ["+userInfo+"]"+"[[request.getRemoteHost()]] ["+request.getRemoteHost()+"]" );
		if(servletContext != null)
		{
			if ( servletContext.getAttribute("applLevUserInfo") != null ) //$NON-NLS-1$
			{
				applLevUserInfo = (HashMap)servletContext.getAttribute("applLevUserInfo");				 //$NON-NLS-1$
				//BaseLogger.log("9",null,null,"Application level info Map Second user["+applLevUserInfo+"]");
			}
			//Changed By Mahesh Patidar on 07/MAR/13[WI2LSUN001 || to remove userSession map dependency]
//			if ( servletContext.getAttribute("usersSession") != null ) //$NON-NLS-1$
//			{
//				usersSession = (HashMap)servletContext.getAttribute("usersSession"); //$NON-NLS-1$
//				//BaseLogger.log("9",null,null,"USERSESSION AT LINE NO626 ["+usersSession+"]");
//			}
			//Ended By Mahesh Patidar
			if( request.getRemoteHost()!=null && userInfo != null )
			{
				sib.setRemoteHost( request.getRemoteHost() );
				sib.setUserLevel( userInfo.getUserLevel() );
				sib.setUserName( userInfo.getEmpName() );
				sib.setSession(session);
				sib.setSessionDestroy( "N" );
				sib.setHostName( hostName );
				sib.setHostIP( hostIP );
				sib.setDeviceType( ( deviceType == null ? "" : deviceType )  );
				sib.setEnterprise(userInfo.getEnterprise());
				sib.setSessionValid(true);
				//Changed made by mukesh  on  22-05-09 [ SY89BAS026-to create a unique key conisiting of usrcode and sessn id].Start
				//applLevUserInfo.put( userCode,sib );
				//Changed By Mahesh Patidar on 07/MAR/13[WI2LSUN001 || to remove userSession map dependency]
				//usersSession.put( session.getId(),userCode );
				//Changed By Pankaj T. on 24-07-19 for session not remove from map when user login using USER_ID,EMAIL_ID or MOBILE_NO instead of code
				//String uniqueKey = userCode+":"+session.getId(); //$NON-NLS-1$
				String uniqueKey = E12GenericUtility.checkNull(userInfo.getLoginCode())+":"+session.getId();
				InternalLogger.log("0",null,null,"AuthenticateServlet.setApplLevelUserInfo() uniqueKey:["+uniqueKey+"]");
				applLevUserInfo.put( uniqueKey,sib);
//				usersSession.put( session.getId(),uniqueKey);
				//Changed made by mukesh  on  22-05-09 [ SY89BAS026-to create a unique key conisiting of usrcode and sessn id].End
				//BaseLogger.log("9",null,null,"Application level info Map first user["+applLevUserInfo+"]"+"USERSESSION["+usersSession+"]");
				servletContext.setAttribute("applLevUserInfo",applLevUserInfo); //$NON-NLS-1$
//				servletContext.setAttribute("usersSession",usersSession);	 //$NON-NLS-1$
				//Ended By Mahesh Patidar
				session.setAttribute( "userIdAndSesId", uniqueKey );
			}
		}
		else
		{
			BaseLogger.log("3",null,null,"$$$$$$$$$$ SERVLET CONTEXT IS NULL  $$$$$$$$"); //$NON-NLS-1$
		}


	}
	//Changed by Rupali on 21/08/2008 to generate the menu tree for RIA.Request ID[BI89BAS010].Start
	public boolean getMenuTree(String userCode, String profileID,String riaCacheStatus)throws BaseException//(SHWETA)
	{
		//BaseLogger.log("9",null,null,"AuthenticateServlet :: getMenuTree()  :: userCode  ["+userCode+"]  profileID   ["+profileID+"] riaCacheStatus   ["+riaCacheStatus+"]");
		BufferedWriter buffWtr = null;
		boolean togenerate = false;
		try{
			String fileStr = CommonConstants.APPLICATION_CONTEXT + CommonConstants.RESOURCE + File.separator  + "Profilemenu" + File.separator + profileID.trim() + File.separator + "sfa_tree.xml"; //$NON-NLS-1$ //$NON-NLS-2$
			File file = new File(fileStr);
			if (file.exists()){
				if(riaCacheStatus != null && (riaCacheStatus.trim()).equalsIgnoreCase("1")){ //$NON-NLS-1$
					BaseLogger.log("3",null,null,fileStr + "file deleted.........."); //$NON-NLS-1$
					file.delete();
					togenerate = true;
				}
				else{
					BaseLogger.log("3",null,null,"File is Alrealy Exist.......... And RIA_CAHCE_STATUS =0"); //$NON-NLS-1$
					return false;
				}
			}
			else{
				togenerate = true;
			}
			if(togenerate==true)
			{
				BaseLogger.log("3",null,null,"schema Tree 'DOES NOT EXIST'"); //$NON-NLS-1$
				String generatedXml =getCommonDBAccess().getUserXMLTree(userCode, profileID);
				String profileDirStr = CommonConstants.APPLICATION_CONTEXT + CommonConstants.RESOURCE + File.separator  + "Profilemenu"; //$NON-NLS-1$
				String dirStr = CommonConstants.APPLICATION_CONTEXT + CommonConstants.RESOURCE + File.separator  + "Profilemenu" + File.separator + profileID.trim(); //$NON-NLS-1$
				File profileDir = new File(profileDirStr);
				BaseLogger.log("3",null,null,"ProfileMenu Tree dir.exists  :"+ profileDir.exists()); //$NON-NLS-1$
				if(!profileDir.exists()){
					profileDir.mkdirs();
				}
				File dir = new File(dirStr);
				BaseLogger.log("3",null,null,"Tree dir.exists  :"+ dir.exists()); //$NON-NLS-1$
				if (!dir.exists()){
					dir.mkdirs();
				}
				File treeFile = new File(fileStr);
				if(!treeFile.exists()){
					treeFile.createNewFile();
				}
				buffWtr = new BufferedWriter(new FileWriter(treeFile));
				buffWtr.write(generatedXml.toString());
				buffWtr.flush();
				buffWtr.close();
				return true;
			}
			else{
				return false;
			}
			}
			catch (Exception e){
				BaseLogger.log("0",null,null,"Exception: AuthenticateServlet : getMenuTree==>\n"+e); //$NON-NLS-1$
				e.printStackTrace();
				return false;
			}
			finally{

				try{
					if(buffWtr != null)
					{
						buffWtr.close();
					}
				}
				catch(Exception ex){
					BaseLogger.log("0",null,null,"Expection in AuthenticateServlet : getMenuTree method : -> "); //$NON-NLS-1$
					 ex.printStackTrace();
					 return false;
				}
			}
	}
	//Changed by Rupali on 21/08/2008 to generate the menu tree for RIA.Request ID[BI89BAS010].End
	//Changed by Dayanand on 16/08/10[To generate menu application wise || MF01SUN001]start
	//Changed by Harshada on 26th Oct 2012 [Creating user connections on login]
	//Add by Dnyaneshwar on 6-Feb-2013 [ Add isMobile param for Clubbing of Menus on the scanner ] Start
	//private boolean getMenuTree(String userCode, String profileID,String riaCacheStatus,String applName )throws BaseException//(SHWETA)

	//Commented and chnaged by Gulzar on 10/10/13 to pass userInfo for multidb connection: START
	//private boolean getMenuTree(String userCode, String profileID,String riaCacheStatus,String applName, boolean isMobile )throws BaseException//(SHWETA)
	private boolean getMenuTree(String userCode, String profileID,String riaCacheStatus,String applName, boolean isMobile, UserInfoBean userInfo )throws BaseException//(SHWETA)
	{
		//Changes By Prajyot[Issue of menu Tree Generation ] On 20MAR13 Start
		/*
		BaseLogger.log("9",null,null,"applName is:"+ applName +": AuthenticateServlet :: getMenuTree()  :: userCode  ["+userCode+"]  profileID   ["+profileID+"] riaCacheStatus   ["+riaCacheStatus+"] isMobile [" + isMobile + "]");
		BufferedWriter buffWtr = null;
		boolean togenerate = false;
		String fileStr=null;
		try{

				fileStr = CommonConstants.APPLICATION_CONTEXT + CommonConstants.RESOURCE + File.separator  + "Profilemenu" + File.separator + profileID.trim() + File.separator + applName.toLowerCase() + "_tree.xml"; //$NON-NLS-1$ //$NON-NLS-2$
				File file = new File(fileStr);
				if (file.exists()){
					if(riaCacheStatus != null && (riaCacheStatus.trim()).equalsIgnoreCase("1")){ //$NON-NLS-1$
						BaseLogger.log("9",null,null,fileStr + " file deleted.........."); //$NON-NLS-1$
						file.delete();
						togenerate = true;
					}
					else{
						BaseLogger.log("9",null,null,"File Already Exist..........And RIA_CAHCE_STATUS =0"); //$NON-NLS-1$
						return false;
					}
				}
				else{
					togenerate = true;
				}

			if(togenerate==true)
			{
				//BaseLogger.log("9",null,null,"schema Tree 'DOES NOT EXIST'");				 //$NON-NLS-1$
				//String generatedXml = getCommonDBAccess().getUserXMLTree(userCode, profileID,applName);
				String generatedXml = getCommonDBAccess().getUserXMLTree( userCode, profileID, applName, isMobile );
				String profileDirStr = CommonConstants.APPLICATION_CONTEXT + CommonConstants.RESOURCE + File.separator  + "Profilemenu"; //$NON-NLS-1$
				String dirStr = CommonConstants.APPLICATION_CONTEXT + CommonConstants.RESOURCE + File.separator  + "Profilemenu" + File.separator + profileID.trim(); //$NON-NLS-1$
				File profileDir = new File(profileDirStr);
				BaseLogger.log("9",null,null,"ProfileMenu Tree dir.exists  :"+ profileDir.exists()); //$NON-NLS-1$
				if(!profileDir.exists()){
					profileDir.mkdirs();
				}
				File dir = new File(dirStr);
				BaseLogger.log("9",null,null,"Tree dir.exists  :"+ dir.exists()); //$NON-NLS-1$
				if (!dir.exists()){
					dir.mkdirs();
				}
				File treeFile = new File(fileStr);
				if(!treeFile.exists()){
					treeFile.createNewFile();
				}
				buffWtr = new BufferedWriter(new FileWriter(treeFile));
				buffWtr.write(generatedXml.toString());
				buffWtr.flush();
				buffWtr.close();
				return true;
			}
			else{
				return false;
			}
			}
			catch (Exception e){
				BaseLogger.log("9",null,null,"Exception: AuthenticateServlet : getMenuTree==>\n"+e); //$NON-NLS-1$
				e.printStackTrace();
				return false;
			}
			finally{

				try{
					if(buffWtr != null)
					{
						buffWtr.close();
					}
				}
				catch(Exception ex){
					BaseLogger.log("9",null,null,"Expection in AuthenticateServlet : getMenuTree method : -> "); //$NON-NLS-1$
					 ex.printStackTrace();
					 return false;
				}
			}
		 */

		BaseLogger.log("3",null,null,"applName is:"+ applName +": AuthenticateServlet :: getMenuTree()  :: userCode  ["+userCode+"]  profileID   ["+profileID+"] riaCacheStatus   ["+riaCacheStatus+"] isMobile [" + isMobile + "]");
		BufferedWriter buffWtr = null;
		boolean togenerate = false;
		String fileStr = null;
		File extMenuTreeFile = null;
		StringBuffer menuTreeXML = new StringBuffer();
		try
		{

			fileStr = CommonConstants.APPLICATION_CONTEXT + CommonConstants.RESOURCE + File.separator  + "Profilemenu" + File.separator + profileID.trim() + File.separator + applName.toLowerCase() + "_tree.xml"; //$NON-NLS-1$ //$NON-NLS-2$
			extMenuTreeFile = new File(fileStr);
			if( extMenuTreeFile != null && extMenuTreeFile.exists())
			{
				String extMenuTreeFileContents = FileUtils.readFileToString(extMenuTreeFile);
				if(riaCacheStatus != null && (riaCacheStatus.trim()).equalsIgnoreCase("1"))
				{ //$NON-NLS-1$
					BaseLogger.log("3",null,null,fileStr + " file to be deleted.........."); //$NON-NLS-1$
					//extMenuTreeFile.delete();
					togenerate = true;
				}
				else if( extMenuTreeFileContents != null && ( extMenuTreeFileContents.trim().length() == "<APPLICATION></APPLICATION>".length() ) )
				{
					BaseLogger.log("3",null,null,"extMenuTreeFileContents [" + extMenuTreeFileContents + "]"); //$NON-NLS-1$
					//extMenuTreeFile.delete();
					togenerate = true;
				}
				else
				{
					BaseLogger.log("3",null,null,"File Already Exist..........And RIA_CAHCE_STATUS =0"); //$NON-NLS-1$
					return false;
				}
			}
			else
			{
				togenerate = true;
			}

			if(togenerate==true)
			{
				//BaseLogger.log("9",null,null,"schema Tree 'DOES NOT EXIST'");				 //$NON-NLS-1$
				//String generatedXml = getCommonDBAccess().getUserXMLTree(userCode, profileID,applName);
				String generatedXml = "";
				//Commented and chnaged by Gulzar on 10/10/13 for multidb connection : START
				//generatedXml = getCommonDBAccess().getUserXMLTree( userCode, profileID, applName, isMobile );
				String transDB = userInfo.getTransDB();
				//if(transDB != null && !"null".equalsIgnoreCase(transDB.trim()) && transDB.trim().length() > 0)
				{
					generatedXml = getCommonDBAccess().getUserXMLTree( userCode, profileID, applName, isMobile, userInfo );
				}
				/*else
				{
					generatedXml = getCommonDBAccess().getUserXMLTree( userCode, profileID, applName, isMobile );
				}*/
				//Commented and chnaged by Gulzar on 10/10/13 for multidb connection : END

				if( generatedXml != null && generatedXml.trim().length() != 0 )
				{
					menuTreeXML.append("<APPLICATION>");
					menuTreeXML.append(generatedXml);
					menuTreeXML.append("</APPLICATION>");
					BaseLogger.log("3",null,null,fileStr + " file has been deleted.........."); //$NON-NLS-1$
					extMenuTreeFile.delete();
				}
				else
				{
					BaseLogger.log("3",null,null," RIA_CAHCE_STATUS = 1, File Already Exist... generatedXml also blank !!!"); //$NON-NLS-1$
					return false;
				}

				String profileMenuDirStr = CommonConstants.APPLICATION_CONTEXT + CommonConstants.RESOURCE + File.separator  + "Profilemenu"; //$NON-NLS-1$
				String profileIdDirStr = CommonConstants.APPLICATION_CONTEXT + CommonConstants.RESOURCE + File.separator  + "Profilemenu" + File.separator + profileID.trim(); //$NON-NLS-1$
				File profileMenuDir = new File(profileMenuDirStr);
				BaseLogger.log("3",null,null,"ProfileMenu Tree dir.exists  :"+ profileMenuDir.exists()); //$NON-NLS-1$
				if(!profileMenuDir.exists())
				{
					profileMenuDir.mkdirs();
				}
				File profileIdDir = new File(profileIdDirStr);
				BaseLogger.log("3",null,null,"Tree dir.exists  :"+ profileIdDir.exists()); //$NON-NLS-1$
				if (!profileIdDir.exists())
				{
					profileIdDir.mkdirs();
				}
				File newMenuTreeFile = new File(fileStr);
				if(!newMenuTreeFile.exists())
				{
					newMenuTreeFile.createNewFile();
				}
				buffWtr = new BufferedWriter(new FileWriter(newMenuTreeFile));
				buffWtr.write( menuTreeXML.toString() );
				buffWtr.flush();
				buffWtr.close();
				return true;
			}
			else
			{
				return false;
			}
		}
		catch (Exception e)
		{
			BaseLogger.log("0",null,null,"Exception: AuthenticateServlet : getMenuTree==>\n"+e); //$NON-NLS-1$
			e.printStackTrace();
			return false;
		}
		finally
		{
			try
			{
				if(buffWtr != null)
				{
					buffWtr.close();
				}
			}
			catch(Exception ex)
			{
				BaseLogger.log("0",null,null,"Expection in AuthenticateServlet : getMenuTree method : -> "); //$NON-NLS-1$
			    ex.printStackTrace();
				return false;
			}
		}
		//Changes By Prajyot[Issue of menu Tree Generation ] On 20MAR13 Ends
	}
	//Changed by Dayanand on 16/08/10[To generate menu application wise || MF01SUN001]end

	private String getDecodedStr(String inputStr)
	{
		String decodedStr = "";
		try
		{
			if( inputStr != null && inputStr.length() > 0 )
			{
				decodedStr = URLDecoder.decode( inputStr, CommonConstants.ENCODING);//(new String( inputStr.getBytes( CommonConstants.ENCODING ) ) ) ;
			}
		}
		catch(Exception e)
		{

		}
		return decodedStr;
	}

	// Added by Raju K on 05-03-14 <CO3ASUN005> for ResourceBundle to display messages from *.properties file, while login
	/**
	 * This method will get the user language and user country
	 * from User table depend upon user code
	 *
	 * @param userCode the user id from login page
	 * @return the list of user lang and user country
	 * @throws Exception
	 */
	//Changed by Sandeep S. on 30-JUL-18 [If any exception occurs on login show on client side]
	public ArrayList<String> getUserLangAndCountry( String userCode ) throws Exception
	{
		ArrayList<String> langAndCountryList = new ArrayList<String>();
		try
		{
			String userLanguage = getCommonDBAccess().getDBColumnValue( "USERS", "USER_LANG","WHERE CODE = "+"'" +userCode+"'" );
			String userCountry = getCommonDBAccess().getDBColumnValue( "USERS", "USER_COUNTRY", "WHERE CODE = "+"'" +userCode+"'" );
			if( userLanguage != null && userCountry != null )
			{
				langAndCountryList.add( userLanguage );
				langAndCountryList.add( userCountry );
			}
			BaseLogger.log("0",null,null,"User Language["+userLanguage+"]"+" User Country["+userCountry+"]" +" List["+langAndCountryList.toString()+"]");
		} catch (Exception e)
		{
			BaseLogger.log("0",null,null,"Exception :: while accessing user country and user language from database. ");
			e.printStackTrace();
			//Changed by Sandeep S. on 30-JUL-18 [If any exception occurs on login show on client side]
			throw e;
		}

		return langAndCountryList ;
	}  // Ended by Raju K on 05-03-14

	/**
	 * This method is used to check if the maximum allowed session for user is exceeded or not
	 * @param userCode
	 * @return isAllowExceeded
	 * @author Gulzar
	 * @since 29/01/15
	 */
	//Changed by Sandeep S. on 30-JUL-18 [If any exception occurs on login show on client side]
	protected boolean isAllowSessionsExceeded( String userCode ) throws Exception
	{
		BaseLogger.log("2",null,null,"isAllowSessionsExceeded method is called .......");
		boolean isAllowExceeded = false;
		String maxAllowSess = "";
		int noOfActSess = 0;
		try
		{
			userCode = userCode.trim();
			if(servletContext.getAttribute("applLevUserInfo") != null)
			{
				HashMap applLevUserInfo = (HashMap)servletContext.getAttribute("applLevUserInfo");
				BaseLogger.log("3",null,null,"isAllowSessionsExceeded >> applLevUserInfo ::"+applLevUserInfo);
				if( applLevUserInfo != null && applLevUserInfo.size() > 0 )
				{
					Set userKeySet = applLevUserInfo.keySet();
					Iterator itApplLevUser = userKeySet.iterator();
					while(itApplLevUser.hasNext())
					{
						String keyValPairs = (String)itApplLevUser.next();
						String userIDSess = keyValPairs.split(":")[0];
						userIDSess = (userIDSess == null) ?"":userIDSess.trim();
						if(userIDSess.equals(userCode))
						{
							noOfActSess++;
						}
					}
				}
			}
			maxAllowSess = getCommonDBAccess().getDBColumnValue("users", "no_session_allow", " where code ='"+userCode+"'");

			// Change by Abhishek on 10.03.2016 [Req Id:S15LBAS004 Authentication changes] START
			String user_code = getCommonDBAccess().getBasicUserInfo(userCode).getLoginCode();
			BaseLogger.log("3",null,null,"AuthenticateServlet :: isAllowSessionsExceeded() : user_code[" + user_code + "]");
			maxAllowSess = getCommonDBAccess().getDBColumnValue("users", "no_session_allow", " where code ='"+user_code+"'");
			// Change by Abhishek on 10.03.2016 [Req Id:S15LBAS004 Authentication changes] END

			if(maxAllowSess != null && maxAllowSess.equals(""+noOfActSess))
			{
				isAllowExceeded = true;
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			//Changed by Sandeep S. on 30-JUL-18 [If any exception occurs on login show on client side]
			throw e;
		}
		BaseLogger.log("2",null,null,"AuthenticateServlet >> isAllowSessionsExceeded >> noOfActSess=["+noOfActSess+"], maxAllowSess =["+maxAllowSess+"], isAllowExceeded =["+isAllowExceeded+"]");
		return isAllowExceeded ;
	}
	//Changed by rahul on 25-apr-2016 [Request ID : W15LSUN010 for updatind date as well as time in LAST_PWD_CHGDATE column in users table] START
		public boolean isResetPassword(int wrongLoginCount,String userId,String chgIP)
		{
			BaseLogger.log("2",null,null,"in isResetPassword().......");
			boolean resetValue = false;
			try
			{
				AppConnectParm appConnect = new AppConnectParm();
				InitialContext ctx = new InitialContext(appConnect.getProperty());
				// Commented and Added by Pankaj R on 20-JUL-18 to change calling of EJB to JB [START]
				//CommonDBAccessRemote dbAccess = (CommonDBAccessRemote)ctx.lookup("ibase/CommonDBAccessEJB/remote");
				CommonDBAccessEJB dbAccess = new CommonDBAccessEJB();
				// Commented and Added by Pankaj R on 20-JUL-18 to change calling of EJB to JB [END]
				int wrongCount = dbAccess.getWrongLoginCount(userId,chgIP);
				BaseLogger.log("3",null,null,"wrongCount....."+wrongCount+".......CommonConstants.WRONG_LOGIN_COUNT"+CommonConstants.WRONG_LOGIN_COUNT);
				if(wrongCount >= CommonConstants.WRONG_LOGIN_COUNT)
				{
					resetValue = true;
				}
				BaseLogger.log("3",null,null,"resetValue...."+resetValue);
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			return resetValue;

		}
		//Changed by rahul on 25-apr-2016 [Request ID : W15LSUN010 for updatind date as well as time in LAST_PWD_CHGDATE column in users table] END

		//Added by Sandeep S. on 24/11/16 [[S16HBAS012]  Check for latest apk version ] start
		public boolean checkVersionComaptibility(String currentApkVersion)
		{
			boolean versionFlag = true;
			String compatibleVersion = CommonConstants.APK_REQUIRED_VERSION;
			BaseLogger.log("2",null,null," compatibleVersion ["+compatibleVersion+"]");
			if( compatibleVersion != null && !"".equalsIgnoreCase(compatibleVersion) )
			{
				String compatibleVerArr [] = compatibleVersion.split("-");
				String currentApkVerArr [] = currentApkVersion.split("-");
				BaseLogger.log("3",null,null,"Length of compatibleVerArr & currentApkVerArr ["+compatibleVerArr.length+"] ["+currentApkVerArr.length+"]");
				if( compatibleVerArr.length == 4 && currentApkVerArr.length == 4 )
				{
					for( int i = 0 ; i < compatibleVerArr.length ; i++ )
					{
						int j = Integer.parseInt( compatibleVerArr[i] );
						int k = Integer.parseInt( currentApkVerArr[i] );
						if( k < j )
						{
							versionFlag = false;
							break;
						}
						else
						{
							versionFlag = true;
							if( k > j )
							{
								if( i == 0 || i == 1 || i == 2 )
								{
									break;
								}
							}
						}
					}
				}
			}
			BaseLogger.log("2",null,null,"versionFlag ["+versionFlag+"]");
			return versionFlag;
		}

		public boolean checkRecommendedVersionComaptibility(String currentApkVersion)
		{
			boolean versionFlag = true;
			String compatibleVersion = CommonConstants.APK_RECOMMENDED_VERSION;
			BaseLogger.log("2",null,null," compatibleVersion ["+compatibleVersion+"]");
			if( compatibleVersion != null && !"".equalsIgnoreCase(compatibleVersion) )
			{
				String compatibleVerArr [] = compatibleVersion.split("-");
				String currentApkVerArr [] = currentApkVersion.split("-");
				BaseLogger.log("3",null,null,"Length of compatibleVerArr & currentApkVerArr ["+compatibleVerArr.length+"] ["+currentApkVerArr.length+"]");
				if( compatibleVerArr.length == 4 && currentApkVerArr.length == 4 )
				{
					for( int i = 0 ; i < compatibleVerArr.length ; i++ )
					{
						int j = Integer.parseInt( compatibleVerArr[i] );
						int k = Integer.parseInt( currentApkVerArr[i] );
						if( k < j )
						{
							versionFlag = false;
							break;
						}
						else
						{
							versionFlag = true;
							//Change by Sandeep S. on 05/12/16
							if( k > j )
							{
								if( i == 0 || i == 1 || i == 2 )
								{
									break;
								}
							}
						}
					}
				}
			}
			BaseLogger.log("2",null,null,"versionFlag ["+versionFlag+"]");
			return versionFlag;
		}
		//Added by Sandeep S. on 24/11/16 [[S16HBAS012]  Check for latest apk version ] end

		//Changed by Sandesh on 18/11/2016 [For Authentication API] Start
		/**
		 * Check allowed login attempts for user.
		 *
		 * @param userCode
		 * @return
		 */
		//Changed by Sandeep S. on 30-JUL-18 [If any exception occurs on login show on client side]
		protected boolean isAllowLoginAttempts( String userCode )throws BaseException, Exception
		{
			boolean isAllowed = true;
			try
			{
				isAllowed = getCommonDBAccess().checkLoginAttempts(userCode);
			}
			catch(BaseException e)
			{
				BaseLogger.log("0",null,null,"BaseException in AthenticateServlet :: isAllowLoginAttempts() : "+ e.getMessage());
				throw e;

			}
			catch(Exception e)
			{
				BaseLogger.log("0",null,null,"Exception in AthenticateServlet :: isAllowLoginAttempts() : "+ e.getMessage());
				throw e;
				//Changed by Sandeep S. on 30-JUL-18 [If any exception occurs on login show on client side]
			}
			return isAllowed;
		}

		/**
		 *
		 * Create and get base64 encoded JWT token based on user and application information.
		 *
		 * @param userCode
		 * @param applicationBean
		 * @return
		 * @throws BaseException
		 * @throws Exception
		 */
		protected String getJWTToken(String userCode, ExtAuthApplicationBean applicationBean, String sessionId) throws BaseException, Exception
		{
			BaseLogger.log("2",null,null,"AuthenticateServlet :: getJWTToken");
			// Get user details
			ExtAuthRespBean userBean = getCommonDBAccess().getExtAuthRespBean(userCode);

			//Create Base64 Encoded JWT token
			String jwtToken = CryptographyUtil.createBase64EncodedJWT(applicationBean, userBean, sessionId);

			BaseLogger.log("2",null,null,"AuthenticateServlet :: getJWTToken: jwtToken : ["+ jwtToken +"]");

			return jwtToken;
		}

		/**
		 *
		 * Redirect to application url.
		 *
		 * @param userCode
		 * @param response
		 * @param request
		 * @throws BaseException
		 * @throws Exception
		 */
		protected void redirectToURL(String userCode, HttpServletResponse response, HttpServletRequest request) throws BaseException, Exception
		{
			BaseLogger.log("2",null,null,"AuthenticateServlet :: Creating JWT token");

			String jwt = getJWTToken(userCode, applicationBean, request.getSession().getId());

			if (!(E12GenericUtility.checkNull(jwt).length() <= 0)) {
				String decodeURL = URLDecoder.decode(applicationBean.getAppRedirectURL(), "UTF-8");
				decodeURL = decodeURL.contains("?") ? decodeURL + "&jwtToken=" + jwt : decodeURL + "?jwtToken=" + jwt;
				BaseLogger.log("3",null,null,"AuthenticateServlet :: Sending JWT token : Redirect URL  [" + decodeURL + "]");
				response.sendRedirect(response.encodeURL("/ibase/login/ExtAuth.jsp?redirectUrl="+decodeURL+"&jwt="+jwt));
				CommonConstants.isRedirect = true;
				BaseLogger.log("2",null,null,"AuthenticateServlet :: Sent JWT token");
			}
		}
		//Changed by Sandesh on 18/11/2016 [For Authentication API] End
		//Added by Sagar B. for forgot password impl in APK[16/11/17]START
		/**
		 * Validates the verification otp with otp stored in session
		 * @param request
		 * @param vfCode
		 * @return
		 */
		private boolean validateVFCode( HttpServletRequest request, String vfCode )
		{
			boolean isValidCode = false;
			try
			{
				//String userCode = tokenId.split(":")[0];
				//String sessionTokenId = request.getSession().getAttribute( userCode+ "_TOKEN_ID" ) != null ? ""+request.getSession().getAttribute( userCode+ "_TOKEN_ID" ) : "";
				String sessionVFCode = request.getSession().getAttribute( "VF_CODE" ) != null ? ""+request.getSession().getAttribute( "VF_CODE" ) : "";
				BaseLogger.log("3",null,null, "sessionVFCode - ["+ sessionVFCode +"], vfcode - ["+ vfCode +"]");
				BaseLogger.log("3",null,null,"sessionID in validateUserSession method : "+request.getSession().getId());
				if ( sessionVFCode.equals( vfCode ) )
				{
					isValidCode = true;
				}
			}
			catch (Exception e)
			{
				isValidCode = false;
				e.printStackTrace();
			}
			return isValidCode;
		}
		//Added by Sagar B. for forgot password impl in APK[16/11/17]END

		//Changed by Sandeep S. on 19-JAN-17 [To check session exist or not for same user on same or on another machine] Start
		private boolean isSessionExist(HttpServletRequest request, String userCode) throws BaseException
		{
			boolean sessionFlag = false;
			//String sessionIdToRemove = "";
			try
			{
				Set<String> sessionIds = new HashSet<String>();
				//sessionIds = SessionListener.getSessionIds();
				sessionIds.addAll(SessionListener.getSessionIds());
				for( String s : sessionIds )
				{
					s = E12GenericUtility.checkNull(s);
					BaseLogger.log("3",null,null,"session id : ["+s +"]");
					HashMap<String, HttpSessionEvent> sessionIdMap = SessionListener.getSessionIdMap();
					if( !s.equalsIgnoreCase(request.getSession().getId()) )
					{
						if( sessionIdMap != null && sessionIdMap.size() > 0 )
						{
							if( sessionIdMap.get(s).getSession() != null )
							{
								UserInfoBean currentUserInfo = null;
								if( sessionIdMap.get(s).getSession().getAttribute("USER_INFO") != null )
								{
									currentUserInfo = (UserInfoBean) sessionIdMap.get(s).getSession().getAttribute("USER_INFO");
								}
								if( currentUserInfo != null && currentUserInfo.getLoginCode() != null )
								{
									if( userCode == null || userCode.length() == 0 )
									{
										UserInfoBean newUserInfo = null;
										if( request.getSession().getAttribute("USER_INFO") != null )
										{
											newUserInfo = (UserInfoBean) request.getSession().getAttribute("USER_INFO");
										}
										if( newUserInfo != null )
										{
											userCode = newUserInfo.getLoginCode();
										}
									}
									if( userCode != null && userCode.length() > 0 )
									{
										//Changed by Sandeep S. on 24-JAN-17 [To check session exist or not for same user on same or on another machine]
										boolean flag = true;;
										String logInInterface = E12GenericUtility.checkNull(currentUserInfo.getLogInInterface());
										BaseLogger.log("3",null,null,"inside isSessionExist login userCode : ["+ userCode +"]");
										//Changed By Pankaj T. on 24-07-19 for session not remove from map when user login using USER_ID,EMAIL_ID or MOBILE_NO instead of code
										CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
										userCode = E12GenericUtility.checkNull(commonDBAccessEJB.getUserCode(userCode));
										BaseLogger.log("3",null,null,"inside isSessionExist actual userCode : ["+ userCode +"]");
										BaseLogger.log("3",null,null,"inside isSessionExist session userCode : ["+ currentUserInfo.getLoginCode() +"]");
										BaseLogger.log("3",null,null,"inside isSessionExist logInInterface : ["+ logInInterface +"]");
										if( "Mobile".equalsIgnoreCase(logInInterface) )
										{
											flag = false;
										}
										//Changed by Sandeep S. on 24-JAN-17 [To check session exist or not for same user on same or on another machine] End
										//Changed By Pankaj T. on 24-07-19 for session not remove from map when user login using USER_ID,EMAIL_ID or MOBILE_NO instead of code
										if( userCode.equalsIgnoreCase( currentUserInfo.getLoginCode().trim()) && flag )
										{
											BaseLogger.log("3",null,null,"is user already present : ["+ userCode.equalsIgnoreCase( currentUserInfo.getLoginCode() ) +"]");
											sessionFlag = true;
											//getCommonDBAccess().updateLoginTrace(currentUserInfo.getLoginCode(), sessionIdMap.get(s).getSession().getId());
											//sessionIdMap.get(s).getSession().invalidate();
											//sessionIdToRemove = s;
											request.getSession().setAttribute("sessionIdToRemove", s);
											//sessionIdMap.get(s).getSession().removeAttribute("USER_INFO");
											break;
										}
									}
								}
							}
						}
					}
				}
				/*if( !"".equalsIgnoreCase(sessionIdToRemove) )
				{
					SessionListener.getSessionIds().remove(sessionIdToRemove);
					SessionListener.getSessionIdMap().remove(sessionIdToRemove);
				}*/
			} catch (Exception e)
			{
				BaseLogger.log("0",null,null,"Exception inside isSessionExist ===> "+e.getMessage());
				e.printStackTrace();
			}

			return sessionFlag;
		}
		//Changed by Sandeep S. on 19-JAN-17 [To check session exist or not for same user on same or on another machine] End

		// Changed and Added by Pankaj R on 20-JAN-18
		private static HashMap<String, String> getDeviceDetail(String userAgentString, String appName, String appVersion)
		{
			String osName = "",osVersion = "", clientApp = "",clientAppVersion = "", deviceMake = "",versionStr ="";
			HashMap<String, String > hashMap = new HashMap<String, String>();
			try
			{
				try
				{
					versionStr = userAgentString.substring(userAgentString.indexOf("Mozilla/5.0") + 13, userAgentString.indexOf("AppleWebKit") - 2);
				}
				catch(StringIndexOutOfBoundsException e)
				{
					versionStr = userAgentString.substring(userAgentString.indexOf("(")+1, userAgentString.indexOf(")"));
				}
				String[] arr = versionStr.split(";");
				if(arr.length == 2)
				{
					try
					{
						if(userAgentString.contains("iPad") || userAgentString.contains("iPhone"))
						{
							osVersion = arr[1].substring(arr[1].indexOf("OS") + 2, arr[1].indexOf("like"));
							osName = arr[1].substring(arr[1].indexOf("like") + 4);
							osVersion = osVersion.replace('_', '.');
							deviceMake = "Apple "+arr[0];
						}

						if (userAgentString.contains("iPad") || userAgentString.contains("iPhone"))
						{
							if(userAgentString.contains("CriOS") && userAgentString.contains(Browser.MOB.toDesc()) && userAgentString.contains(Browser.SAF.toDesc()))
							{
								clientApp = Browser.CH.toDesc();
								clientAppVersion = userAgentString.substring(userAgentString.indexOf("OS/") + 3, userAgentString.indexOf(Browser.MOB.toDesc()));
							}
							else if(userAgentString.contains("Version") && userAgentString.contains(Browser.MOB.toDesc()) && userAgentString.contains(Browser.SAF.toDesc()))
							{
								clientApp = Browser.SAF.toDesc();
								clientAppVersion = userAgentString.substring(userAgentString.indexOf(Browser.SAF.toDesc()+"/") + 7);
							}
							else if (userAgentString.contains(Browser.MOB.toDesc()))
							{
								clientApp = appName;
								clientAppVersion = appVersion;
							}
						}
						else if(arr[0].contains("X11"))
						{
							String r[] = arr[1].trim().split("\\s");
							osName = r[0];
							if(userAgentString.contains(Browser.CH.toDesc()))
							{
								clientApp = Browser.CH.toDesc();
								clientAppVersion = getChromeVersion(userAgentString, Browser.SAF.toDesc());
							}
							deviceMake = Browser.INTEL.toDesc();
						}
						else if(arr[0].contains(Browser.WIN.toDesc()))
						{
							String r[] = arr[0].split("\\s");
							osName = r[0]+" "+r[1];
							osVersion = r[2];
							if(userAgentString.contains(Browser.FFO.toDesc()))
							{
								clientApp = Browser.FFO.toDesc();
								clientAppVersion = userAgentString.substring(userAgentString.indexOf(Browser.FFO.toDesc()+"/") + 8);
							}
							deviceMake = Browser.INTEL.toDesc();
						}
						else if(arr[0].contains("Macintosh"))
						{
							osVersion = arr[1].substring(arr[1].indexOf("OS X") + 4);
							osName = arr[1].substring(arr[1].indexOf("Intel") + 6, arr[1].indexOf("OS X") + 4);
							osVersion = osVersion.replace('_', '.');
							if(userAgentString.contains(Browser.CH.toDesc()))
							{
								clientApp = Browser.CH.toDesc();
								clientAppVersion = userAgentString.substring(userAgentString.indexOf(Browser.CH.toDesc()+"/") + 7,  userAgentString.indexOf(Browser.SAF.toDesc()));
							}
							else if(userAgentString.contains(Browser.FFO.toDesc()))
							{
								clientApp = Browser.FFO.toDesc();
								clientAppVersion = userAgentString.substring(userAgentString.indexOf(Browser.FFO.toDesc()+"/") + 8);
							}
							else if(userAgentString.contains(Browser.SAF.toDesc()))
							{
								clientApp = Browser.SAF.toDesc();
								clientAppVersion = userAgentString.substring(userAgentString.indexOf(Browser.SAF.toDesc()+"/") + 7);
							}
							deviceMake = "Apple PC";
						}
					}
					catch (Exception e)
					{
						BaseLogger.log("0",null,null,"AuthenticateServlet.getDeviceDetail() in arr[2] :: "+e);
					}
				}
				else if(arr.length == 3)
				{

					if (userAgentString.contains("Android"))
					{
						String deviceMakeName = (arr[2].substring(0, arr[2].indexOf("Build")));
						osVersion = (arr[1].substring(9));
						osName = "Android";
						if(userAgentString.contains(Browser.CH.toDesc()))
						{
							clientApp = Browser.CH.toDesc();
							clientAppVersion = getChromeVersion(userAgentString, Browser.MOB.toDesc());
						}
						deviceMake = deviceMakeName.trim();
					}
					else if (userAgentString.contains(Browser.WIN.toDesc()))
					{
						String r[] = arr[0].split("\\s");
						osName = r[0]+" "+r[1];
						osVersion = r[2];
						if(userAgentString.contains(Browser.CH.toDesc()))
						{
							clientApp = Browser.CH.toDesc();
							clientAppVersion = getChromeVersion(userAgentString, Browser.SAF.toDesc());
						}
						deviceMake = Browser.INTEL.toDesc();
					}
					else if(arr[0].contains("X11"))
					{
						String r[] = arr[1].trim().split("\\s");
						osName = r[0];
						osVersion = r[1];
						if(userAgentString.contains(Browser.FFO.toDesc()))
						{
							clientApp = Browser.FFO.toDesc();
							clientAppVersion = getFireFoxVersion(userAgentString);
						}
						deviceMake = Browser.INTEL.toDesc();
					}
				}
				else if(arr.length == 4)
				{
					String deviceMakeName = (arr[2].substring(0, arr[2].indexOf("Build")));
					osVersion = (arr[1].substring(9));
					osName = "Android";
					if (userAgentString.contains("Android"))
					{
						clientApp = appName;
						clientAppVersion = appVersion;
				    }
					deviceMake = deviceMakeName.trim();
				}
				else if(arr.length == 5)
				{
					if (versionStr.contains("Android"))
					{
						if(arr[1].trim().equals("U"))
						{
							String str = userAgentString.replace(versionStr, "");
							String str2[] = str.split("\\s");
							for(int i = 0 ; i < str2.length; i++)
							{
							}
						}
				    }
				}
				hashMap.put("OS_NAME", osName.trim());
				hashMap.put("OS_VERSION", osVersion.trim());
				hashMap.put("DEVICE_MAKE", deviceMake.trim());
				hashMap.put("CLIENT_APP", clientApp.trim());
				hashMap.put("CLIENT_APP_VER", clientAppVersion.trim());

				BaseLogger.log("3",null,null,hashMap);
			}
			catch (Exception e) {
				BaseLogger.log("0",null,null,"AuthenticateServlet.getDeviceDetail() : "+e);
			}
			return hashMap;
		}

		public static String getChromeVersion(String userAgentString, String defaultBrow )
		{
			String clientAppVersion = "";
			clientAppVersion = userAgentString.substring(userAgentString.indexOf(Browser.CH.toDesc()+"/") + 7, userAgentString.indexOf(defaultBrow));
			return clientAppVersion;
		}
		public static String getFireFoxVersion(String userAgentString)
		{
			String clientAppVersion = "";
			clientAppVersion = userAgentString.substring(userAgentString.indexOf(Browser.FFO.toDesc()+"/") + 8);
			return clientAppVersion;
		}
		public enum Browser
		{
			CH("Chrome"),
			SAF("Safari"),
			FFO("Firefox"),
			MOB("Mobile"),
			WIN("Windows"),
			INTEL("Intel PC");

			private String value = null;

			Browser(String value)
			{
				this.value = value;
			}

			public String toDesc()
			{
				 return this.value;
			}
		}

		class BrowserDetail
		{
			private String osName, osVersion, clientApp, clientAppVersion, deviceMake;

			public BrowserDetail() {
			}

			public BrowserDetail(HashMap<String, String> browDetail)
			{
				this.osName = browDetail.get("OS_NAME");
				this.osVersion = browDetail.get("OS_VERSION");
				this.clientApp = browDetail.get("CLIENT_APP");
				this.clientAppVersion = browDetail.get("CLIENT_APP_VER");
				this.deviceMake = browDetail.get("DEVICE_MAKE");
				BaseLogger.log("2",null,null,"Constructor : "+browDetail);
			}

			public String getOsName() {
				return osName;
			}

			public void setOsName(String osName) {
				this.osName = osName;
			}

			public String getOsVersion() {
				return osVersion;
			}

			public void setOsVersion(String osVersion) {
				this.osVersion = osVersion;
			}

			public String getClientApp() {
				return clientApp;
			}

			public void setClientApp(String clientApp) {
				this.clientApp = clientApp;
			}

			public String getClientAppVersion() {
				return clientAppVersion;
			}

			public void setClientAppVersion(String clientAppVersion) {
				this.clientAppVersion = clientAppVersion;
			}

			public String getDeviceMake() {
				return deviceMake;
			}

			public void setDeviceMake(String deviceMaker) {
				this.deviceMake = deviceMaker;
			}
		}
		// Changed and Added by Pankaj R on 20-JAN-18

		//Added by Sandeep S. on 01-Feb-18 [To check session exist or not for same user in Mobile apk] Start
		private boolean isSessionExistInMobile(HttpServletRequest request, String userCode) throws BaseException
		{
			boolean sessionFlag = false;
			//String sessionIdToRemove = "";
			try
			{
				//added by sunny soni for getting isAllowMultipleSession [Start]
				boolean isAllowMultipleSession = new Boolean(request.getParameter("isAllowMultipleSession"));
				BaseLogger.log("2",null,null,"isAllowMultipleSession::[ "+isAllowMultipleSession+" ]");
				//added by sunny soni for getting isAllowMultipleSession [End]
				Set<String> sessionIds = new HashSet<String>();
				sessionIds.addAll(SessionListener.getSessionIds());
				for( String s : sessionIds )
				{
					s = E12GenericUtility.checkNull(s);
					BaseLogger.log("3",null,null,"session id "+s);
					HashMap<String, HttpSessionEvent> sessionIdMap = SessionListener.getSessionIdMap();
					if( !s.equalsIgnoreCase(request.getSession().getId()) )
					{
						if( sessionIdMap != null && sessionIdMap.size() > 0 )
						{
							if( sessionIdMap.get(s).getSession() != null )
							{
								UserInfoBean currentUserInfo = null;
								if( sessionIdMap.get(s).getSession().getAttribute("USER_INFO") != null )
								{
									currentUserInfo = (UserInfoBean) sessionIdMap.get(s).getSession().getAttribute("USER_INFO");
								}
								if( currentUserInfo != null && currentUserInfo.getLoginCode() != null )
								{
									if( userCode == null || userCode.length() == 0 )
									{
										UserInfoBean newUserInfo = null;
										if( request.getSession().getAttribute("USER_INFO") != null )
										{
											newUserInfo = (UserInfoBean) request.getSession().getAttribute("USER_INFO");
										}
										if( newUserInfo != null )
										{
											userCode = newUserInfo.getLoginCode();
										}
									}
									if( userCode != null && userCode.length() > 0 )
									{
										//Changed by Sandeep S. on 24-JAN-17 [To check session exist or not for same user on same or on another machine]
										boolean flag = false;;
										String logInInterface = E12GenericUtility.checkNull(currentUserInfo.getLogInInterface());
										BaseLogger.log("3",null,null,"inside isSessionExist login userCode : ["+ userCode +"]");
										//Changed By Pankaj T. on 24-07-19 for session not remove from map when user login using USER_ID,EMAIL_ID or MOBILE_NO instead of code
										CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
										userCode = E12GenericUtility.checkNull(commonDBAccessEJB.getUserCode(userCode));
										BaseLogger.log("3",null,null,"inside isSessionExist actual userCode : ["+ userCode +"]");
										BaseLogger.log("3",null,null,"inside isSessionExist session userCode : ["+ currentUserInfo.getLoginCode() +"]");
										BaseLogger.log("3",null,null,"inside isSessionExist logInInterface : ["+ logInInterface +"]");
										if( "Mobile".equalsIgnoreCase(logInInterface) )
										{
											//flag = true;
											//Added by sunny soni for allowing multiple session of same user[Start]
											if(!isAllowMultipleSession)
											{
												flag = true;
											}
											//Added by sunny soni for allowing multiple session of same user[End]
										}
										//Changed by Sandeep S. on 24-JAN-17 [To check session exist or not for same user on same or on another machine] End
										if( userCode.equalsIgnoreCase( currentUserInfo.getLoginCode().trim()) && flag )
										{
											BaseLogger.log("3",null,null,"is user already present :["+ userCode.equalsIgnoreCase( currentUserInfo.getLoginCode() )+"]");
											sessionFlag = getCommonDBAccess().checkLogInTraceEntry(userCode, s) ;
											BaseLogger.log("3",null,null,"line no 3817 sessionFlag "+ sessionFlag );
											request.getSession().setAttribute("mobileSessionIdToRemove", s);
											if( sessionFlag )
											{
												break;
											}
										}
									}
								}
							}
						}
					}
				}
			} catch (Exception e)
			{
				BaseLogger.log("0",null,null,"Exception inside isSessionExist ===> "+e.getMessage());
				e.printStackTrace();
			}
			BaseLogger.log("2",null,null,"final sessionFlag "+ sessionFlag );
			return sessionFlag;
		}
		//Added by Sandeep S. on 01-Feb-18 [To check session exist or not for same user in Mobile apk] End

	// Added by Abhishek T on 20-MAR-18 [For OTP based authentication] START
	private static char[] generateOTP(int ofLength) {
		char[] validChars = "123456789".toCharArray();
		char[] otp = new char[ofLength];

		for (int i = 0; i < ofLength; i++) {
			char c = validChars[(int)(Math.random() * validChars.length)];
			otp[i] = c;
		}

		return otp;
	}

	private void verifyOTP(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, BaseException, Exception {

		String otp = request.getParameter("OTP");
		String responseData = "0:Invalid OTP";

		HttpSession session = request.getSession(false);
		boolean matched = matchOTP(session, otp);

		if (matched) {
			if (isOTPExpired(otp, request)) {
				responseData = "0:Entered OTP has beed expired";
			} else {
				String mobileNumber = (String)session.getAttribute("MN");

				CommonDBAccessRemote dbAccessRemote = getCommonDBAccess();
				UserInfoBean basicUserInfo = dbAccessRemote.getBasicUserInfo(mobileNumber);

				String authenticateUrl = buildAuthenticateUrl(basicUserInfo);
				authenticateAndIncludeResponse(request, response, authenticateUrl);

				responseData = "~SEP~" + basicUserInfo.getLoginCode() + "~SEPE~" + basicUserInfo.getLoginPwd();
			}

			try
			{
				session.removeAttribute("OTP_CHARS");
				session.removeAttribute("OGT_" + otp);
				session.removeAttribute("MN");
			}
			catch (Exception ex)
			{
				BaseLogger.log("0",null,null,"Exception in AuthenticateServlet :: verifyOTP() due to invalid session");
			}
		}

		OutputStream responseWriter = response.getOutputStream();
		responseWriter.write(responseData.getBytes());
		responseWriter.flush();
		responseWriter.close();
	}

	private boolean matchOTP(HttpSession session, String otp) {
		if (session != null && otp != null) {
			char[] chars = (char[])session.getAttribute("OTP_CHARS");
			if (chars != null) {
				String otpInSession = String.valueOf(chars);

				return otp.equals(otpInSession);
			}
		}

		return false;
	}

	private boolean isOTPExpired(String otp, HttpServletRequest request) {
		long expirationDuration = 1000 * 60 * 5; // 5 minutes
		long currentTime = System.currentTimeMillis();

		HttpSession session = request.getSession(false);
		if (session != null) {
			String attributeKey = "OGT_" + otp;
			Object attributeValue = session.getAttribute(attributeKey);

			if (attributeValue != null) {
				long otpGeneratedTime = (long)attributeValue;

				return (currentTime - otpGeneratedTime) >= expirationDuration;
			}
		}

		return false;
	}

	private void authenticateAndIncludeResponse (
		HttpServletRequest request, HttpServletResponse response,
		String servletUrl
	) throws ServletException, IOException {

		RequestDispatcher requestDispatcher = request.getRequestDispatcher(servletUrl);
		requestDispatcher.include(request, response);

	}

	private String buildAuthenticateUrl(UserInfoBean basicUserInfo) {
		String user = basicUserInfo.getLoginCode();
		String password = basicUserInfo.getLoginPwd();
		boolean isSHA256 = "Y".equals(basicUserInfo.getIsPasswordStore());

		BaseLogger.log("0",null,null,String.format("Username : %s, Password : %s, SHA256 : %s", user, password, isSHA256));

		String servletName = String.format(
			"/AuthenticateServlet?action=MELOGIN&USER=%s&PASSWORD=%s&isSHA256Appld=%s",
			user, password, isSHA256
		);

		return servletName;
	}
	// Added by Abhishek T on 20-MAR-18 [For OTP based authentication] END

	//Added By Pankaj T. on 18-06-18 for device security based on enterprise level [0-disabled, 1-strictly enforced, 2-OTP, 3-workflow invoked] - Start
	/**
	 * Validates the verification otp with otp stored in session
	 * @param request
	 * @param vfCode
	 * @return
	 */
	private boolean validateDeviceVFCode( HttpServletRequest request, String vfCode )
	{
		boolean isValidCode = false;
		try
		{
			String sessionVFCode = request.getSession().getAttribute( "DEVICE_VER_CODE" ) != null ? ""+request.getSession().getAttribute( "DEVICE_VER_CODE" ) : "";
			BaseLogger.log("3",null,null, "sessionVFCode - ["+ sessionVFCode +"], vfcode - ["+ vfCode +"]");
			BaseLogger.log("3",null,null,"sessionID in validateUserSession method : "+request.getSession().getId());
			if ( sessionVFCode.equals( vfCode ) )
			{
				isValidCode = true;
			}
		}
		catch (Exception e)
		{
			isValidCode = false;
			e.printStackTrace();
		}
		return isValidCode;
	}

	public void invalidateSession( HttpServletRequest request )
	{
        InternalLogger.log("0",null,null,"In invalidateSession");
		HttpSession sessObj = request.getSession( false );
		if ( sessObj != null )
		{
			sessObj.invalidate();
			BaseLogger.log("3",null,null, "Invalidate session." );
			sessObj = request.getSession( true );
		}
	}
	//Added By Pankaj T. on 18-06-18 for device security based on enterprise level [0-disabled, 1-strictly enforced, 2-OTP, 3-workflow invoked] - End

	private boolean checkIsHost(String hostname) {
	    Pattern p = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
	    Matcher m = p.matcher(hostname);
	    return !m.find();
	}
	
	//Added by Sadique S [To hide/encrypt the OTP at client side] on 26-06-19 START
	public String encrypt(String value)
	{
		try 
		{
			IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
			SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

			byte[] encrypted = cipher.doFinal(value.getBytes());
			return Base64.encodeBase64String(encrypted);
		} 
		catch (Exception ex) 
		{
			ex.printStackTrace();
		}
		return null;
	}

	public String decrypt(String encrypted) 
	{
		try 
		{
			IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
			SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));

			return new String(original);
		} 
		catch (Exception ex) 
		{
			ex.printStackTrace();
		}

		return null;
	}
	//Added by Sadique S [To hide/encrypt the OTP at client side] on 26-06-19 START
}