package ibase.utility.training;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import ibase.bean.ExtAuthApplicationBean;
import ibase.bean.ExtAuthRespBean;
import ibase.utility.BaseException;
import ibase.utility.BaseLogger;
import ibase.utility.CryptographyUtil;
import ibase.utility.E12GenericUtility;
import ibase.utility.GenericUtility;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.RestAPIServiceUtility;

@Stateless
public class Harshal extends ValidatorEJB {

	GenericUtility genericUtility = GenericUtility.getInstance();
	String userId = "";

	public String wfValData() throws RemoteException, ITMException {
		return "";
	}

	public String wfValData(String xmlString, String xmlString1, String xmlString2, String objContext, String editFlag,
			String xtraParams) throws RemoteException, ITMException {

		BaseLogger.log("3", null, null, "Edit Flag value=" + editFlag);
		// System.out.println("Edit Flag value=" + editFlag);
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;

		String errString = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try {
			BaseLogger.log("3", null, null, "wfValData value of xmlString [" + xmlString + "]");
			BaseLogger.log("3", null, null, "wfValData value of xmlString [" + xmlString1 + "]");
			BaseLogger.log("3", null, null, "wfValData value of xmlString [" + xmlString2 + "]");
			if (xmlString != null && xmlString.trim().length() != 0) {
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0) {
				dom1 = genericUtility.parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() != 0) {
				dom2 = genericUtility.parseString(xmlString2);
			}
			errString = wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams);
			BaseLogger.log("3", null, null, "ErrString: " + errString);
		} catch (Exception e) {
			BaseLogger.log("3", null, null, "Exception: wfValData(String xmlString): " + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
		}
		BaseLogger.log("3", null, null, "Returning from  wfValData errString=[" + errString + "]");
		return (errString);
	}

	public String wfValData(Document dom, Document dom1, Document dom2, String objContext, String editFlag,
			String xtraParams) throws RemoteException, ITMException {
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		UserInfoBean userInfo = super.getUserInfo();
		int ctr = 0, currentFormNo = 0, childNodeListLenght = 0;
		String childNodeName = null;
		// String childNodeValue = null;
		String errString = "";
		// String errCode = "";
		String userId = "";
//		String loginSite = "";
		try {
			userId = getValueFromXTRA_PARAMS(xtraParams, "loginCode");
//			loginSite = getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			if (objContext != null && objContext.trim().length() > 0) {
				currentFormNo = Integer.parseInt(objContext);
			}
			BaseLogger.log("3", null, userInfo.getLoginCode(),
					"*************Validation for empty inputs Formno=" + currentFormNo);
			switch (currentFormNo) {
			case 1:
				parentNodeList = dom.getElementsByTagName("Detail" + currentFormNo);

				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				childNodeListLenght = childNodeList.getLength();

				for (ctr = 0; ctr < childNodeListLenght; ctr++) {
					childNode = childNodeList.item(ctr);
					BaseLogger.log("3", null, null, "Child Node=>" + ctr + "=>" + childNode);
					childNodeName = childNode.getNodeName().trim();
					BaseLogger.log("3", null, null, "Child Node Name=>" + ctr + "=>" + childNodeName);
					BaseLogger.log("3", null, null,
							"Child Node Value=>" + ctr + "=>" + genericUtility.getColumnValue(childNodeName, dom));

					if (childNodeName.equalsIgnoreCase("app_id") && editFlag.equalsIgnoreCase("a")) {
						if (checkAppid(genericUtility.getColumnValue("app_id", dom2))) {
							errString = getErrorString("app_id", "EXISTAPPID", userId);
							break;

						}
					} else if (childNodeName.equalsIgnoreCase("eff_from")) {
						Date fromDate = sdf.parse(genericUtility.getColumnValue("eff_from", dom));
						Date toDate = sdf.parse(genericUtility.getColumnValue("valid_upto", dom));
						if (fromDate.compareTo(toDate) > 0) {
							// errString = getErrorString("valid_upto", "VALAPPDATE", userId);
							// break;
						}

					}

				}
				break;
			case 2:

				parentNodeList = dom.getElementsByTagName("Detail" + currentFormNo);
				BaseLogger.log("3", null, null, "Parent node list Size" + parentNodeList.getLength());
				BaseLogger.log("3", null, null, "Current form no" + currentFormNo);
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				childNodeListLenght = childNodeList.getLength();
				for (ctr = 0; ctr < childNodeListLenght; ctr++) {

					childNode = childNodeList.item(ctr);
					BaseLogger.log("3", null, null, "Child Node=>" + ctr + "=>" + childNode);
					childNodeName = childNode.getNodeName().trim();
					BaseLogger.log("3", null, null, "Child Node Name=>" + ctr + "=>" + childNodeName);
					BaseLogger.log("3", null, null,
							"Child Node Value=>" + ctr + "=>" + genericUtility.getColumnValue(childNodeName, dom2));

					if (childNodeName.equalsIgnoreCase("app_id") && editFlag.equalsIgnoreCase("a")) {
						if (checkAppid(genericUtility.getColumnValue("app_id", dom2))) {
							errString = getErrorString("app_id", "EXISTAPPID", userId);
							break;
						}
					}
					if (childNodeName.equalsIgnoreCase("user_id") && editFlag.equalsIgnoreCase("a")) {
//						String user = genericUtility.getColumnValue("user_id", dom2);
					}
					if (childNodeName.equalsIgnoreCase("user_id")) {
						userId = checkNull(genericUtility.getColumnValue("user_id", dom));
					}

				}
				BaseLogger.log("3", null, null, "User Id from auth_apps_api=" + userId);
				break;
			case 3:
				parentNodeList = dom.getElementsByTagName("Detail" + currentFormNo);
				BaseLogger.log("3", null, null, "Current form no" + currentFormNo);
				BaseLogger.log("3", null, null, "Paren node list Size" + parentNodeList.getLength());
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				childNodeListLenght = childNodeList.getLength();
				for (ctr = 0; ctr < childNodeListLenght; ctr++) {
					childNode = childNodeList.item(ctr);
					BaseLogger.log("3", null, null, "Child Node=>" + ctr + "=>" + childNode);
					childNodeName = childNode.getNodeName().trim();
					BaseLogger.log("3", null, null, "Child Node Name=>" + ctr + "=>" + childNodeName);
					BaseLogger.log("3", null, null,
							"Child Node Value=>" + ctr + "=>" + genericUtility.getColumnValue(childNodeName, dom2));
					if (childNodeName.equalsIgnoreCase("app_id") && editFlag.equalsIgnoreCase("a")) {
						if (childNode.getFirstChild() == null
								|| checkEmpty(genericUtility.getColumnValue("app_id", dom2))) {
							errString = getErrorString("app_id", "NULLAPPID", userId);
							break;
						}
					}

					else if (childNodeName.equalsIgnoreCase("enterprise")) {

						String enterprise = genericUtility.getColumnValue("enterprise", dom2);
						String userid = genericUtility.getColumnValue("user_id", dom2);
						if (!checkEnterpriseName(enterprise)) {
							errString = getErrorString("enterprise", "EXAPPENTER", userId);
							break;
						}
						if (checkEnterprise(enterprise, userid)) {
							// errString = getErrorString("user_id", "EXUSER", userId);
							// break;
						}
					} else if (childNodeName.equalsIgnoreCase("channel_id")) {

						String channelId = genericUtility.getColumnValue("channel_id", dom2);
						if (checkChannelID(channelId)) {
							errString = getErrorString("channel_id", "EXCHID", userId);

							break;
						}
					}

				} // end of for
				break;

			}
		} catch (Exception e) {
			e.getMessage();
			e.printStackTrace();
			BaseLogger.log("3", null, null, "Got Error in Validation=>" + e.getMessage());
		}
		BaseLogger.log("3", null, null, "Error String by Ankush==>" + errString + "<=");
		return errString;
		/**/}

	private boolean checkEmpty(String columnValue) {
		if (columnValue.length() <= 0) {
			return true;
		}
		if (columnValue.trim().equals("")) {
			return true;
		}
		return false;
	}

	private boolean checkAppid(String appid) {
		Connection connectionObject = null;
		Statement stmt = null;
		try {
			connectionObject = getConnection();
			String sql = "select app_id from auth_apps where app_id='" + appid + "'";
			stmt = connectionObject.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			if (rs.next())
				return true;
			else
				return false;
		} catch (Exception e) {
			return false;
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
					stmt = null;
				}
				if (connectionObject != null) {
					connectionObject.close();
					connectionObject = null;
				}
			} catch (Exception e) {
				BaseLogger.log("3", null, null, e.getMessage());
			}

		}

	}

	private boolean checkEnterpriseName(String enterprise) {
		Connection connectionObject = null;
		Statement stmt = null;
		try {
			connectionObject = getConnection();
			String sql = "select enterprise from enterprise where enterprise='" + enterprise + "'";
			stmt = connectionObject.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			if (rs.next())
				return true;
			else
				return false;
		} catch (Exception e) {
			return false;
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
					stmt = null;
				}
				if (connectionObject != null) {
					connectionObject.close();
					connectionObject = null;
				}
			} catch (Exception e) {

			}
		}

	}

	private String checkNull(String input) {
		if (input == null) {
			input = "";
		} else {
			input = input.trim();
		}
		return input;
	}

	private boolean checkEnterprise(String enterprise, String userId) {
		Connection connectionObject = null;
		Statement stmt = null;
		try {
			connectionObject = getConnection();
			String sql = "SELECT * FROM USER_ACC_CHANNEL WHERE ENTERPRISE='" + enterprise + "' AND USER_ID='" + userId
					+ "'";
			stmt = connectionObject.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			if (rs.next())
				return true;
			else
				return false;
		} catch (Exception e) {
			return false;
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
					stmt = null;
				}
				if (connectionObject != null) {
					connectionObject.close();
					connectionObject = null;
				}
			} catch (Exception e) {
				BaseLogger.log("3", null, null, e.getMessage());
			}

		}
	}

	private boolean checkChannelID(String channelId) {
		Connection connectionObject = null;
		Statement stmt = null;
		try {
			connectionObject = getConnection();
			String sql = "SELECT * FROM USER_ACC_CHANNEL WHERE CHANNEL_ID='" + channelId + "'";
			stmt = connectionObject.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			if (rs.next())
				return true;
			else
				return false;
		} catch (Exception e) {
			return false;
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
					stmt = null;
				}
				if (connectionObject != null) {
					connectionObject.close();
					connectionObject = null;
				}
			} catch (Exception e) {
				BaseLogger.log("3", null, null, e.getMessage());
			}

		}
	}

	public String itemChanged() throws RemoteException, ITMException {
		return "";
	}

	public String itemChanged(String xmlString, String xmlString1, String xmlString2, String objContext,
			String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException {

		Document dom1 = null;
		Document dom = null;
		Document dom2 = null;
		String valueXmlString = "";
		BaseLogger.log("3", null, null, "Current column in itemchange==>" + currentColumn);
		try {
			if (xmlString != null && xmlString.trim().length() != 0) {
				BaseLogger.log("3", null, null, "itemchange header xmlString>>>>" + xmlString);
				dom = genericUtility.parseString(xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() != 0) {
				BaseLogger.log("3", null, null, "xmlString1>>>>" + xmlString1);
				dom1 = genericUtility.parseString(xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() != 0) {
				BaseLogger.log("3", null, null, "xmlString2>>>>" + xmlString2);
				dom2 = genericUtility.parseString(xmlString2);
				BaseLogger.log("3", null, null, "dom2:::-" + genericUtility.serializeDom(dom2));
			}

			valueXmlString = itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);

		} catch (Exception e) {
			BaseLogger.log("3", null, null, "Exception itemChanged::::" + e.getMessage() + ":");
			e.printStackTrace();
		}
		BaseLogger.log("3", null, null, "returning from itemChanged method");

		return valueXmlString;
	}

	public String itemChanged(Document dom, Document dom1, Document dom2, String objContext, String currentColumn,
			String editFlag, String xtraParams) throws RemoteException, ITMException {
		BaseLogger.log("3", null, null, "itemChanged by Ankush");
		BaseLogger.log("3", null, null, "Itemchanged Called");

		StringBuffer valueXmlString = new StringBuffer();
		int currentFormNo = 0;
		try {
			BaseLogger.log("3", null, null, "dom: : " + genericUtility.serializeDom(dom));
			BaseLogger.log("3", null, null, "dom1: : " + genericUtility.serializeDom(dom1));
			BaseLogger.log("3", null, null, "dom2: : " + genericUtility.serializeDom(dom2));
			UserInfoBean userInfo = super.getUserInfo();
			if (objContext != null && objContext.trim().length() > 0)
				currentFormNo = Integer.parseInt(objContext);
			BaseLogger.log("3", null, null, "current form no: " + currentFormNo);
			currentColumn = currentColumn == null ? "" : currentColumn.trim();
			BaseLogger.log("3", null, null, "Application API currentColumn : " + currentColumn);
			BaseLogger.log("3", null, null, "Application API editFlag : " + editFlag);
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");

			switch (currentFormNo) {

			case 1:
				BaseLogger.log("3", null, null, "Application API editFlag  Case 1: " + editFlag);
				valueXmlString.append("<Detail1>");

				if ("api_name".equalsIgnoreCase(currentColumn.trim())) {

					String api_nameValue = genericUtility.getColumnValue("api_name", dom);
					valueXmlString.append("<api_name><![CDATA[").append(api_nameValue).append("]]></api_name>\r\n");
					// valueXmlString.append("<api_name><![CDATA[").append("Harshal").append("]]></api_name>\r\n");
					String apiType = getApiType(api_nameValue);
					BaseLogger.log("3", null, null, "Enterprise Field Value " + api_nameValue);

					valueXmlString.append("<api_type><![CDATA[").append(apiType).append("]]></api_type>\r\n");
					BaseLogger.log("3", null, null, "Valueof Api Type " + apiType);
				}
				valueXmlString.append("</Detail1>");
				BaseLogger.log("3", null, null, "value xml string for detail1" + valueXmlString);
				break;

			}
			valueXmlString.append("</Root>\r\n");

		} catch (Exception e) {
			BaseLogger.log("3", null, null, e.getMessage());
		}
		BaseLogger.log("3", null, null, "\n****ValueXmlString By Ankush :" + valueXmlString + ":********");

		return valueXmlString.toString();
	}

	private String getApiType(String api_Name) {
		
		BaseLogger.log("3", null, null, " Enter into this getApiType method  : "+ api_Name);

		
		String valueOfApiType = "";
		try {
			// String sql= "select API_TYPE from ent_ext_api_key where
			// api_name='"+api_Name+"'";
			
			String sql = "select  API_TYPE from (select  API_TYPE from ent_ext_api_key  where api_name=? ORDER BY API_TYPE) WHERE ROWNUM = 1";
			
			Connection conn = getConnection();
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, api_Name);
			ResultSet rs = pstmt.executeQuery();
			
			if (rs.next()) {
				valueOfApiType = rs.getString("API_TYPE");
				BaseLogger.log("3", null, null, "Value from the database got here is " + valueOfApiType);

			}
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return valueOfApiType;
	}

	private String getUserEnterprise(String userId) {
		try {
			String enterprise = "";
			String sql = "SELECT ENTERPRISE FROM USERS WHERE CODE='" + userId + "'";

			Connection conn = getConnection();
			Statement pstmt = conn.createStatement();
			ResultSet rs = pstmt.executeQuery(sql);
			if (rs.next()) {
				enterprise = rs.getString("ENTERPRISE");
			}
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
			conn.close();
			return enterprise;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	private String getFLD_VALUE(String serviceDescr) {
		String fldValue = "";
		try {

			String sql = "SELECT FLD_VALUE FROM GENCODES WHERE DESCR='" + serviceDescr + "'";
			Connection conn = getConnection();
			Statement pstmt = conn.createStatement();
			ResultSet rs = pstmt.executeQuery(sql);
			if (rs.next()) {
				fldValue = rs.getString("FLD_VALUE");
			}
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// if(fldValue.equalsIgnoreCase("writeFileSaveTrans")||fldValue.equalsIgnoreCase("writeFile"))
		// fldValue="fileWrite";
		return fldValue;
	}

	private String createEndpoint(String fldValue, String description, String objName, String enterprise,
			String appId) {
		String endpoint = "";
		String serviceConfig = "";
		try {
			if (!fldValue.equals("") && !objName.equals("") && !enterprise.equals("") && !appId.equals("")) {
				if (fldValue.equals("writeFile") || fldValue.equals("writeFileSaveTrans")) {
					fldValue = "setData";
				}
				System.out.println("description in create url:" + description);

				if (!description.equals("")
						&& description.equalsIgnoreCase("Accept Data (Write File And Save Transaction)")) {
					serviceConfig = "writeFileSaveTrans";
					endpoint = ("/ibase/rest/EDIService/" + "setData" + "/" + objName.toLowerCase() + "/" + enterprise
							+ "/" + appId + "/" + serviceConfig.toLowerCase());

				}

				else if (!description.equals("") && description.equalsIgnoreCase("Accept Data (Only Write File)")) {
					serviceConfig = "writeFile";
					serviceConfig = "";
					endpoint = ("/ibase/rest/EDIService/" + "setData" + "/" + objName.toLowerCase() + "/" + enterprise
							+ "/" + appId);

				} else if (!description.equals("") && description.equalsIgnoreCase("Set Data And Confirm")) {
					serviceConfig = "setDataAndConfirm";
					endpoint = ("/ibase/rest/EDIService/" + "setData" + "/" + objName.toLowerCase() + "/" + enterprise
							+ "/" + appId + "/" + serviceConfig);
				} else {
					endpoint = fldValue;
				}

				// for creating url for getData
				if (fldValue.equalsIgnoreCase("getData")) {
					endpoint = "/ibase/rest/E12ExtService/getData/" + objName + "/" + enterprise + "/" + appId;
				}

			}

		} catch (Exception e) {

		}
		return endpoint;
	}

	private boolean checkObject(String object) {
		Connection connectionObject = null;
		Statement stmt = null;
		try {
			connectionObject = getConnection();
			String sql = "SELECT DISTINCT OBJ_NAME FROM OBJ_ACTIONS WHERE OBJ_NAME='" + object + "'";
			stmt = connectionObject.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			if (rs.next())
				return true;
			else
				return false;
		} catch (Exception e) {
			return false;
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
					stmt = null;
				}
				if (connectionObject != null) {
					connectionObject.close();
					connectionObject = null;
				}
			} catch (Exception e) {
				BaseLogger.log("3", null, null, e.getMessage());
			}

		}
	}

	private List<String> getTableAndPrimaryKey(String objName) {
		List<String> dataList = new ArrayList<>();
		Connection conn = null;
		Statement pstmt = null;
		try {
			String sql = "SELECT TABLE_NAME,TRAN_ID_COL FROM TRANSETUP WHERE TRAN_WINDOW='w_" + objName + "'";
			conn = getConnection();
			pstmt = conn.createStatement();
			ResultSet rs = pstmt.executeQuery(sql);
			if (rs.next()) {
				System.out.println("Table Name=:" + rs.getString("TABLE_NAME"));
				if (!rs.getString("TABLE_NAME").equals(null) && !rs.getString("TABLE_NAME").equals("null")
						&& !rs.getString("TABLE_NAME").equals("")) {

					dataList.add(rs.getString("TABLE_NAME"));
					dataList.add(rs.getString("TRAN_ID_COL"));
				}
			}
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
			if (dataList.size() > 0) {
				BaseLogger.log("3", null, null, "primary key=" + dataList.get(1));
				if ("null".equals(dataList.get(1)) || null == dataList.get(1) || dataList.get(1).equals("")
						|| dataList.get(1).equals(null)) {

					String query = "SELECT cols.column_name " + "FROM all_constraints cons, all_cons_columns cols "
							+ "WHERE cols.table_name = '" + dataList.get(0).toUpperCase() + "' "
							+ "AND cons.constraint_type = 'P' " + "AND cons.constraint_name = cols.constraint_name "
							+ "AND cons.owner = cols.owner " + "AND POSITION='1' "
							+ "ORDER BY cols.table_name, cols.position";

					pstmt = conn.createStatement();
					rs = pstmt.executeQuery(query);
					if (rs.next()) {
						dataList.add(1, rs.getString("column_name"));
					}
					if (rs != null) {
						rs.close();
						rs = null;
					}
					if (pstmt != null) {
						pstmt.close();
						pstmt = null;
					}
				}
			}
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
				if (conn != null) {
					conn.close();
					conn = null;
				}
			} catch (Exception e) {

			}
		}
		return dataList;
	}

	private String getObjDescription(String objName) {
		String description = "";
		Connection conn = null;
		Statement pstmt = null;
		try {
			String sql = "SELECT DESCR FROM ITM2MENU WHERE WIN_NAME='w_" + objName + "'";
			conn = getConnection();
			pstmt = conn.createStatement();
			ResultSet rs = pstmt.executeQuery(sql);
			if (rs.next()) {
				description = rs.getString("DESCR");
			}
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			try {
				if (pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
				if (conn != null) {
					conn.close();
					conn = null;
				}
			} catch (Exception e) {

			}
		}
		return description;

	}

	private boolean checkUserCode(String userCode) {
		boolean result = false;
		Connection conn = null;
		Statement pstmt = null;
		try {
			String sql = "SELECT * FROM USERS WHERE CODE='" + userCode + "'";
			conn = getConnection();
			pstmt = conn.createStatement();
			ResultSet rs = pstmt.executeQuery(sql);
			if (rs.next()) {
				result = true;
			}
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			try {
				if (pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
				if (conn != null) {
					conn.close();
					conn = null;
				}
			} catch (Exception e) {

			}
		}
		return result;
	}

	private Object getUserType(String userId) {
		String userType = "";
		try {
			String sql = "SELECT USER_TYPE FROM USERS WHERE CODE='" + userId + "'";

			Connection conn = getConnection();
			Statement pstmt = conn.createStatement();
			ResultSet rs = pstmt.executeQuery(sql);
			if (rs.next()) {
				userType = rs.getString("USER_TYPE");
			}
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return userType;
	}

	/**
	 * 
	 * This method is for getting application information based on appId
	 * 
	 */
	public ExtAuthApplicationBean getExtAuthApplicationInfo(Document dom1) throws BaseException, Exception {

		// ConnDriver connDriver = null;
		// Connection connection = null;
		// PreparedStatement preparedStatement = null;
		// ResultSet resultSet = null;
		ExtAuthApplicationBean applicationBean = new ExtAuthApplicationBean();
		// applicationBean.setAppId(appId);
		try {
			BaseLogger.log("3", null, null, "ApplicationAPI :: getExtAuthApplicationInfo ");

			applicationBean.setAppId(E12GenericUtility.checkNull(genericUtility.getColumnValue("app_id", dom1)));
			BaseLogger.log("3", null, null, "getExtAuthApplicationInfo :: AppId"
					+ E12GenericUtility.checkNull(genericUtility.getColumnValue("app_id", dom1)));

			applicationBean.setAppName(E12GenericUtility.checkNull(genericUtility.getColumnValue("app_name", dom1)));
			BaseLogger.log("3", null, null, "getExtAuthApplicationInfo :: AppName"
					+ E12GenericUtility.checkNull(genericUtility.getColumnValue("app_name", dom1)));

			applicationBean.setAppRedirectURL(
					E12GenericUtility.checkNull(genericUtility.getColumnValue("redirect_url", dom1)));
			BaseLogger.log("3", null, null, "getExtAuthApplicationInfo :: redirect URL"
					+ E12GenericUtility.checkNull(genericUtility.getColumnValue("redirect_url", dom1)));

			applicationBean.setDescr(E12GenericUtility.checkNull(genericUtility.getColumnValue("descr", dom1)));
			BaseLogger.log("3", null, null, "getExtAuthApplicationInfo :: description"
					+ E12GenericUtility.checkNull(genericUtility.getColumnValue("descr", dom1)));

			applicationBean.setEffFrom(E12GenericUtility.checkNull(genericUtility.getColumnValue("eff_from", dom1)));
			BaseLogger.log("3", null, null, "getExtAuthApplicationInfo :: EFF_FROM"
					+ E12GenericUtility.checkNull(genericUtility.getColumnValue("eff_from", dom1)));

			applicationBean.setActive(E12GenericUtility.checkNull(genericUtility.getColumnValue("active", dom1)));
			BaseLogger.log("3", null, null, "getExtAuthApplicationInfo :: ACTIVE"
					+ E12GenericUtility.checkNull(genericUtility.getColumnValue("active", dom1)));

			applicationBean.setEnableSecurity(
					E12GenericUtility.checkNull(genericUtility.getColumnValue("enable_security", dom1)));
			BaseLogger.log("3", null, null, "getExtAuthApplicationInfo :: ENABLE_SECURITY"
					+ E12GenericUtility.checkNull(genericUtility.getColumnValue("enable_security", dom1)));

			applicationBean
					.setSharedKey(E12GenericUtility.checkNull(genericUtility.getColumnValue("shared_key", dom1)));
			BaseLogger.log("3", null, null, "getExtAuthApplicationInfo :: SHARED_KEY"
					+ E12GenericUtility.checkNull(genericUtility.getColumnValue("shared_key", dom1)));
			if (applicationBean.getSharedKey().equals("")) {
				applicationBean.setSharedKey("a3edd11a09ea4e0ccd09c6cd2828021b");
			}

			applicationBean.setTtl(Integer.parseInt(genericUtility.getColumnValue("ttl", dom1).trim()));
			BaseLogger.log("3", null, null, "getExtAuthApplicationInfo :: TTL"
					+ E12GenericUtility.checkNull(genericUtility.getColumnValue("ttl", dom1)));

			applicationBean
					.setWhiteListIp(E12GenericUtility.checkNull(genericUtility.getColumnValue("white_list_ip", dom1)));
			BaseLogger.log("3", null, null, "getExtAuthApplicationInfo :: WHITE_LIST_IP"
					+ E12GenericUtility.checkNull(genericUtility.getColumnValue("white_list_ip", dom1)));

			applicationBean
					.setEncryptMth(E12GenericUtility.checkNull(genericUtility.getColumnValue("encrypt_mth", dom1)));
			BaseLogger.log("3", null, null, "getExtAuthApplicationInfo :: ENCRYPT_MTH"
					+ E12GenericUtility.checkNull(genericUtility.getColumnValue("encrypt_mth", dom1)));

			applicationBean
					.setSecretKey(E12GenericUtility.checkNull(genericUtility.getColumnValue("secret_key", dom1)));
			BaseLogger.log("3", null, null, "getExtAuthApplicationInfo :: SECRET_KEY"
					+ E12GenericUtility.checkNull(genericUtility.getColumnValue("secret_key", dom1)));

		} catch (Exception e) {
			BaseLogger.log("0", null, null, "Exception in CommonDBAccessEJB getExtAuthApplicationInfo()........." + e);
		}
		return applicationBean;
	}

	/**
	 *
	 * 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)
			throws BaseException, Exception {
		BaseLogger.log("2", null, null, "ExtAuthAppService :: getJWTToken");
		// Get user details
		RestAPIServiceUtility restapiserviceutility = new RestAPIServiceUtility();
		ExtAuthRespBean userBean = restapiserviceutility.getCommonDBAccess().getExtAuthRespBean(userCode);

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

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

		return jwtToken;
	}
}
