/********************************************************
	Title : QcOrderAprv
	Date  : 26/05/11
	Author: Janardhan.B
 ********************************************************/

package ibase.webitm.ejb.mfg;

import ibase.system.config.AppConnectParm;
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.webitm.ejb.ProcessEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import ibase.webitm.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.rpc.ParameterMode;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

@Stateless // added for ejb3 


public class QcOrderAprv extends ProcessEJB  implements QcOrderAprvLocal ,QcOrderAprvRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance();

	//getData() : To get the data by taking the values from process window/xls file
	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println(":: In getData() of QcOrderAprv EJB");

		String rtrStr = "";
		Document headerDom = null;
		Document detailDom = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			if(xmlString != null && xmlString.trim().length()!=0 )
			{
				headerDom = genericUtility.parseString(xmlString);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2);
			}
			rtrStr = getData(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println("Exception @ QcOrderAprv-getData(xmlString, xmlString2, windowName, xtraParams)::" + e.getMessage());
			throw new ITMException(e);
		}
		return rtrStr;
	}


	public String getData(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		// retrieve the data from filter
		String qcOrderNoFrom = "";
		String qcOrderNoTo = "";
		String lotNoFrom = "";
		String lotNoTo = "";
		String lotSlFrom = "";
		String lotSlTo = "";
		String xlsName = "";
		String xlsFilePath = "";
		String xlsFile = "";

		// to append the data on grid
		String qOrderNo = "";
		String status = "";
		String lotNo = "";
		String lotSl = "";
		String itemCode = "";
		String itemDescr = "";
		StringBuffer retTabSepStrBuff = new StringBuffer();
		String resultString = "";

		// to fetch the data from xsl file
		String batchSheetNo = "";
		String aprvReject = ""; // pass or fail value from xls file
		String fResult = "";

		String sql = "";
		String sql2 = "";
		String sql3 = "";
		Connection conn = null;
		ResultSet rs = null;
		ResultSet rs2 = null;
		ResultSet rs3 = null;
		PreparedStatement pstmt = null;
		PreparedStatement pstmt2 = null;
		PreparedStatement pstmt3 = null;
		ConnDriver connDriver = new ConnDriver();

		try
		{
			conn = connDriver.getConnectDB("DriverITM");

			xlsName = genericUtility.getColumnValue("xls_name",headerDom);
			System.out.println("xlsName is............................:"+xlsName);

			// To fetch the data from xls file if xls file name is entered
			if(xlsName != null && xlsName.trim().length() != 0)
			{
				System.out.println("!!You are importing the file!!");

				// code to retrieve the path and file name of xsl file
				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				Document dom1 = db.parse( "/IBASEHOME/ibase.xml" );
				xlsFilePath = dom1.getElementsByTagName( "XLS_PATH" ).item(0).getFirstChild().getNodeValue();
				xlsFile = xlsFilePath + File.separator + xlsName;
				System.out.println("!! xls File Name & it's Path ::"+xlsFile);

				File file = new File(xlsFile);
				POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
				HSSFWorkbook wb = new HSSFWorkbook(fs);
				HSSFSheet sheet = wb.getSheetAt(0);
				HSSFRow row;
				HSSFCell cell;

				int rows; 									// No of rows
				rows = sheet.getPhysicalNumberOfRows();

				int cols = 0; 								// No of columns
				int tmp = 0;

				// This trick ensures that we get the data properly even if it doesn't start from first few rows
				for(int i = 0; i < 10 || i < rows; i++)
				{
					row = sheet.getRow(i);
					if(row != null)
					{
						tmp = sheet.getRow(i).getPhysicalNumberOfCells();
						if(tmp > cols) cols = tmp;
					}
				}
				System.out.println("No of columns (Physical Number of Cells) "+cols);
				System.out.println("No of Rows (Physical Number of Rows) "+rows);

				for(int r = 1; r <= rows; r++)
				{
					row = sheet.getRow(r);
					if(row != null)
					{
						// lot_no & lot_sl(batch/sheetno)
						cell = row.getCell((short)3);
						if(cell != null)
						{
							batchSheetNo = cell.getStringCellValue();
							System.out.println("cell-batch/sheetno ::"+batchSheetNo);

							String[] res = batchSheetNo.split("-");
							System.out.println(res.length);
							lotNo = res[0];
							lotSl = res[1];
							System.out.println("lotNo"+lotNo);
							System.out.println("lotSl"+lotSl);

							// For qcorder number
							sql = "SELECT QORDER_NO, STATUS FROM QC_ORDER WHERE LOT_NO = ? AND LOT_SL = ? ";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1,lotNo);
							pstmt.setString(2,lotSl);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								qOrderNo = rs.getString("qorder_no");
								status = rs.getString("status");
								System.out.println("qOrderNo"+qOrderNo);
								System.out.println("Status is : "+status);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
						}

						// item code & item description
						cell = row.getCell((short)8);
						if(cell != null)
						{
							itemCode = cell.getStringCellValue();
							System.out.println("cell-prodcode(itemcode) ::"+itemCode);

							sql = "SELECT DESCR FROM ITEM WHERE ITEM_CODE = ? ";
							pstmt = conn.prepareStatement( sql );
							pstmt.setString(1, itemCode);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								itemDescr = rs.getString("descr");
								System.out.println("itemDescr"+itemDescr);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
						}

						// FleshResult
						cell = row.getCell((short)25);
						if(cell != null)
						{
							fResult = String.valueOf(cell.getNumericCellValue());
							System.out.println("cell-FleshResult ::"+fResult);
						}

						// Approved or Reject
						cell = row.getCell((short)34);
						if(cell != null)
						{
							aprvReject = cell.getStringCellValue();
							System.out.println("cell-Pass/Fail ::"+aprvReject);
							if(aprvReject != null && aprvReject.trim().length() > 0 && aprvReject.trim().equalsIgnoreCase("pass"))
							{
								aprvReject = "A";
							}
							else if(aprvReject != null && aprvReject.trim().length() > 0 && aprvReject.trim().equalsIgnoreCase("fail"))
							{
								aprvReject = "R";
							}
							System.out.println("aprvReject"+aprvReject);
						}

						// !! The data must be append in the below order !!
						//qorder_no
						//lot_no
						//lot_sl
						//item_code
						//item_descr
						//approve_reject
						//reason_code
						//flesh_result
						if(status.equals("U"))
						{
							retTabSepStrBuff.append(qOrderNo).append("\t");
							retTabSepStrBuff.append(lotNo).append("\t");
							retTabSepStrBuff.append(lotSl).append("\t");
							retTabSepStrBuff.append(itemCode).append("\t");
							retTabSepStrBuff.append(itemDescr).append("\t");
							retTabSepStrBuff.append(aprvReject).append("\t");
							retTabSepStrBuff.append("").append("\t"); //reason_code
							retTabSepStrBuff.append(fResult).append("\t");
							retTabSepStrBuff.append("\n"); // next line
						}
					} // if(row!=null)
					resultString = retTabSepStrBuff.toString();
				} // for
				System.out.println("@@ resultString is : " + resultString);
			} //if
			else
			{
				qcOrderNoFrom = genericUtility.getColumnValue("qc_order_no_from",headerDom);
				System.out.println("qcOrderNoFrom.................. :"+ qcOrderNoFrom);

				qcOrderNoTo = genericUtility.getColumnValue("qc_order_no_to",headerDom);
				System.out.println("qcOrderNoTo ................. :"+ qcOrderNoTo);

				lotNoFrom = genericUtility.getColumnValue("lot_no_from",headerDom);
				System.out.println("lotNoFrom is............................:"+lotNoFrom);

				lotNoTo = genericUtility.getColumnValue("lot_no_to",headerDom);
				System.out.println("lotNoTo is............................:"+lotNoTo);

				lotSlFrom = genericUtility.getColumnValue("lot_sl_from",headerDom);
				System.out.println("lotSlFrom is............................:"+lotSlFrom);

				lotSlTo = genericUtility.getColumnValue("lot_sl_to",headerDom);
				System.out.println("lotSlTo is............................:"+lotSlTo);

				// Query To get the Data from Process Window

				sql = "SELECT QORDER_NO, LOT_NO, LOT_SL FROM QC_ORDER WHERE QORDER_NO BETWEEN ? AND ? "+"AND LOT_NO BETWEEN ? AND ? "+
				"AND LOT_SL BETWEEN ? AND ? AND STATUS = 'U'";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, qcOrderNoFrom);
				pstmt.setString(2, qcOrderNoTo);
				pstmt.setString(3, lotNoFrom);
				pstmt.setString(4, lotNoTo);
				pstmt.setString(5, lotSlFrom);
				pstmt.setString(6, lotSlTo);
				rs = pstmt.executeQuery();
				while (rs.next())
				{
					qOrderNo = rs.getString("qorder_no");
					lotNo = rs.getString("lot_no");
					lotSl = rs.getString("lot_sl");

					System.out.println("qOrderNO"+qOrderNo);
					System.out.println("lotNO"+lotNo);
					System.out.println("lotNO"+lotSl);

					sql2 = "SELECT ITEM_CODE FROM QC_ORDER WHERE QORDER_NO = ? ";
					pstmt2 = conn.prepareStatement(sql2);
					pstmt2.setString(1, qOrderNo);
					rs2 = pstmt2.executeQuery();
					if(rs2.next())
					{
						itemCode = rs2.getString("item_code");
						System.out.println("itemCode:"+itemCode);

						sql3 = "SELECT DESCR FROM ITEM WHERE ITEM_CODE = ? ";
						pstmt3 = conn.prepareStatement(sql3);
						pstmt3.setString(1,itemCode);
						rs3 = pstmt3.executeQuery();
						if(rs3.next())
						{
							itemDescr = rs3.getString("descr");
							System.out.println("itemDescr:"+itemDescr);
						}
						rs3.close();
						rs3 = null;
						pstmt3.close();
						pstmt3 = null;
					}
					rs2.close();
					rs2 = null;
					pstmt2.close();
					pstmt2 = null;

					// !! The data must be append in the below order !!
					//qorder_no
					//lot_no
					//lot_sl
					//item_code
					//item_descr
					//approve_reject
					//reason_code
					//reasoncode_descr
					//flesh_result

					retTabSepStrBuff.append(qOrderNo).append("\t");
					retTabSepStrBuff.append(lotNo).append("\t");
					retTabSepStrBuff.append(lotSl).append("\t");				
					retTabSepStrBuff.append(itemCode).append("\t");
					retTabSepStrBuff.append(itemDescr).append("\t");
					retTabSepStrBuff.append("A").append("\t"); // default value = A
					retTabSepStrBuff.append("").append("\t");
					retTabSepStrBuff.append("").append("\t");
					retTabSepStrBuff.append("\n"); // next line
				} //while
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;

				resultString = retTabSepStrBuff.toString();
				System.out.println("@@ resultString is : " + resultString);
			}
		} //try
		catch(FileNotFoundException fne)
		{
			System.out.println("!!! File Not Found Exception : From QcOrderAprv.java " + fne.getMessage());
			throw new ITMException(fne);
		}
		catch (SQLException se)
		{
			System.out.println("!!! SQLException : From QcOrderAprv.java :" + se.getMessage() + ":");
			throw new ITMException(se);
		}
		catch (Exception e)
		{
			System.out.println("!!! Exception : From QcOrderAprv.java :" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println("!! connection closing at getData() !!");
				conn.close();
				conn = null;
			}
			catch(Exception e)
			{
				e.getMessage();
			}
		}
		return resultString;
	}


	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String retStr = "";
		Document detailDom = null;
		Document headerDom = null;

		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString);
				System.out.println("headerDom " + headerDom);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2);
				System.out.println("detailDom " + detailDom);
			}
			retStr = process(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println("Exception : QcOrderAprv.java :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return retStr;
	}

	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String qcOrderNo = "";
		String lotNo = "";
		String lotSl = "";
		String siteCode = "";
		String aprvReject = ""; 			// approved or rejected field
		String reasonCode = ""; 				// reason Code field
		String itemCode = "";
		String fResult = ""; 				// flesh result
		String expectedResult = "";
		boolean isExist = false; 		// To compare the flesh result region with expected Result

		String locCodeAprv = "";
		String locCodeRej ="";
		String updateSql = "";
		int updCnt = 0;
		final int VALUE_ONE = 1;
		final int VALUE_ZERO = 0;
		String specRef = "";
		String routeCode = "";

		String sql = "";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Date qorderDate = null;
		String qorderDate1 = "";

		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		String forcedFlag = "";
		String childNodeName = "";
		String retString = "";
		GenericUtility genutility=null;
		int childNodeListLength = 0;
		int ctr=0;
		int rowcnt = 0;
		SimpleDateFormat sdf=null;	
		String errString = "";

		ConnDriver connDriver = new ConnDriver();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();

		try
		{
			genutility = GenericUtility.getInstance();
			conn = connDriver.getConnectDB( "DriverITM" );
			connDriver = null;
			parentNodeList = detailDom.getElementsByTagName( "Detail2" );
			parentNode = parentNodeList.item(0);
			childNodeList = parentNode.getChildNodes();
			childNodeListLength = childNodeList.getLength();
			for( ctr = 0; ctr < childNodeListLength; ctr++ )
			{
				childNode = childNodeList.item( ctr );
				childNodeName = childNode.getNodeName();
				sdf=new SimpleDateFormat(genutility.getApplDateFormat());
				if( childNodeName.equals("qorder_no"))
				{
					qcOrderNo = genericUtility.getColumnValue( "qorder_no", detailDom );
					System.out.println("qcOrderNo"+qcOrderNo);
				}
				if( childNodeName.equals("lot_no"))
				{
					lotNo = genericUtility.getColumnValue( "lot_no", detailDom ); 
					System.out.println("lotNo "+lotNo);
				}
				if (childNodeName.equals("lot_sl"))
				{
					lotSl = genericUtility.getColumnValue( "lot_sl", detailDom );
					System.out.println("lotSl ..........."+ lotSl);

					// To retrieve site code from qc_order 
					sql = "SELECT SITE_CODE,SPEC_REF,ROUTE_CODE FROM  QC_ORDER WHERE  QORDER_NO = ? AND LOT_NO = ? AND LOT_SL = ? ";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, qcOrderNo);
					pstmt.setString(2, lotNo);
					pstmt.setString(3, lotSl);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						siteCode = rs.getString("SITE_CODE");
						specRef = rs.getString("SPEC_REF");
						routeCode = rs.getString("ROUTE_CODE");
						System.out.println("Site CODE is ......."+siteCode);
						System.out.println("+++++spec ref++++"+specRef);
						System.out.println("+++++r++++"+routeCode);
						
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					
				}
				if (childNodeName.equals("item_code"))
				{
					System.out.println("item_code");
					itemCode = genericUtility.getColumnValue("item_code", detailDom );
					System.out.println("itemCode ..........."+ itemCode);

					// To retrieve the loc_code__aprv, loc_code__rej from 'site item' master against site_code & item_code
					sql = "SELECT LOC_CODE__APRV, LOC_CODE__REJ FROM SITEITEM WHERE SITE_CODE = ? AND ITEM_CODE = ? ";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, siteCode);
					pstmt.setString(2, itemCode);
					rs = pstmt.executeQuery();
					while(rs.next())
					{
						locCodeAprv = rs.getString("loc_code__aprv");
						locCodeRej = rs.getString("loc_code__rej");
						System.out.println("locCodeAprv"+locCodeAprv);
						System.out.println("locCodeRej"+locCodeRej);
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					
					sql = "select qorder_date from qc_order where site_code = ?   and item_code = ?   and lot_no = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, siteCode);
					pstmt.setString(2, itemCode);
					pstmt.setString(3, lotNo);
					rs = pstmt.executeQuery();
					while(rs.next())
					{
						qorderDate = rs.getDate("qorder_date");
						 qorderDate1 = sdf.format(qorderDate);
						
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
				}
				if (childNodeName.equals("apprv_rej"))
				{
					System.out.println("apprv_rej");
					aprvReject = genericUtility.getColumnValue("apprv_rej", detailDom ); 
					System.out.println("aprvReject ..........."+ aprvReject);

					if(aprvReject == null || aprvReject == "" )
					{
						System.out.println("Approve/Rejected value coming as null");
						errString = itmDBAccessEJB.getErrorString("","VTARE","","",conn);
					}
					else if ( aprvReject != null && aprvReject.trim().length() != 0 && !aprvReject.equals("A") && !aprvReject.equals("R"))
					{
						System.out.println("Incorrect Approve/Rejected value(It must be 'A' or 'R')");
						errString = itmDBAccessEJB.getErrorString("","VTARIC","","",conn);
						conn.rollback();
					}
				}
				if(!aprvReject.equals("A"))
				{
				if (childNodeName.equals("reason_code"))
				{
					System.out.println("reason_code");
					reasonCode = genericUtility.getColumnValue("reason_code", detailDom ); 
					System.out.println("reason code ..........."+ reasonCode);

					// To check 'reason code' value & it shouldn't be null when approved/rejected value is 'R'
					if ( aprvReject != null && aprvReject.trim().length() != 0 && aprvReject.equals("R") )
					{
						if ( reasonCode == null || reasonCode == "")
						{
							System.out.println("*** reason Code should not be null when approved or Rejected value = R ***");
							errString = itmDBAccessEJB.getErrorString("","VTRCE","","",conn);
							return errString;
						}
					}
					if ( aprvReject != null && aprvReject.trim().length() != 0 && aprvReject.equals("R") )
					{
						if ( reasonCode != null )
						{
							sql = "SELECT COUNT(1) FROM gencodes WHERE fld_value = ?";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1,reasonCode);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								if(rs.getInt(1)==0)
								{
									errString = itmDBAccessEJB.getErrorString("","VTIRCE","","",conn);
									return errString;
								}
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
							System.out.println("^^^Reason code should be exist in gencodes valid from  ^^^^^^");
							
						}
					}
					
				}
				}
				if (childNodeName.equals("flesh_result"))
				{
					System.out.println("flesh_result");
					fResult = genericUtility.getColumnValue("flesh_result", detailDom );
					System.out.println("fResult ..........."+ fResult);

					//added by chitranjan pandey emp_code__qcaprv  to update when reason code, flesh result are empty and approve reject = 'A'
					if(aprvReject.equals("A"))
					{
						System.out.println("if apprv rej is A");
						updateSql = "UPDATE QC_ORDER SET LOC_CODE__APRV = ? ,QUANTITY = ? , QTY_REJECTED = ? , QTY_PASSED = ? ,EMP_CODE__QCAPRV = ? WHERE QORDER_NO = ? ";
						pstmt = conn.prepareStatement(updateSql);
						pstmt.setString(1, locCodeAprv);
						pstmt.setInt(2, VALUE_ONE);
						pstmt.setInt(3, VALUE_ZERO);
						pstmt.setInt(4, VALUE_ONE);
						pstmt.setString(5, genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode"));
						pstmt.setString(6, qcOrderNo);
						updCnt = pstmt.executeUpdate();
						System.out.println("!!! "+updCnt+"row updated in the case of flesh result & reason are empty & approve reject value is 'A'!!!");
						pstmt.close();
						pstmt = null;
						if(updCnt > 0)
						{
							conn.commit();
							System.out.println("!! IF  REASON CODE FRESULT IS NULL Updated SUCCESSFULLY");
						}
					}
					if(fResult != null && fResult.trim().length()!= 0)
					{
						// retrieves 'expected result' to compare with the flesh result
						sql = "SELECT EXPECTED_RESULT FROM QCITEM_SPEC_DET WHERE ITEM_CODE = ? AND SPEC_REF = ? AND ROUTE_CODE = ?";
						System.out.println("After Is Not Null Expected Result ");
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, itemCode);
						pstmt.setString(2, specRef);
						pstmt.setString(3, routeCode ); 
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							expectedResult = rs.getString(1);
							System.out.println("expectedResult ....."+expectedResult);
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						if(expectedResult != null && expectedResult.trim().length() > 0)
						{
							isExist = isBetween( fResult, expectedResult );
							if(isExist)
							{
								System.out.println("!!! Approved !!!");

								// updates 'Qc Order' as approved 'flesh result' exists between 'expected result'
								updateSql = "UPDATE QC_ORDER SET LOC_CODE__APRV = ? , QUANTITY = ? ,QTY_REJECTED = ? , QTY_PASSED = ? ,EMP_CODE__QCAPRV = ? WHERE QORDER_NO = ? ";
								System.out.println("qc order appproved if exist between flesh flesh result^^");
								pstmt = conn.prepareStatement(updateSql);
								pstmt.setString(1, locCodeAprv);
								pstmt.setInt(2, VALUE_ONE);
								pstmt.setInt(3, VALUE_ZERO);
								pstmt.setInt(4, VALUE_ONE);
								pstmt.setString(5, genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode"));
								pstmt.setString(6, qcOrderNo);
								updCnt = pstmt.executeUpdate();
								System.out.println("!!! "+updCnt+"row updated in the case of Approved after checking the boundary !!!");
							}
							else if( ! isExist )
							{
								System.out.println("!!! Rejected !!!");

								// reason code can't be empty if 'Qc Order' is rejected
//								if ( reasonCode == null || reasonCode == "")
//								{
//									System.out.println("*** Automatic rejection... so reasonCode should not be empty  ***");
//									errString = itmDBAccessEJB.getErrorString("","VTRFRCE","","",conn);
//									return errString;
//								}

								// updates 'Qc Order' as rejected if 'flesh result' not exists between 'expected result'
								updateSql = "UPDATE QC_ORDER SET REJECTION_CODE = ? , LOC_CODE__REJ = ? , QUANTITY = ? ,QTY_REJECTED = ? , QTY_PASSED = ? ,EMP_CODE__QCAPRV = ? WHERE QORDER_NO = ? ";
								System.out.println("^^^qc order update after rejection due to out of range flesh result^^");
								pstmt = conn.prepareStatement(updateSql);
								pstmt.setString(1, reasonCode);
								pstmt.setString(2,locCodeRej);
								pstmt.setInt(3, VALUE_ONE);
								pstmt.setInt(4, VALUE_ONE);
								pstmt.setInt(5, VALUE_ZERO);
								pstmt.setString(6, genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode"));
								pstmt.setString(7, qcOrderNo);
								
								updCnt = pstmt.executeUpdate();
								System.out.println("!!! "+updCnt+"row updated in the case of Rejected after checking the boundary !!!");
							}
							if(updCnt > 0)
							{
								conn.commit();
								System.out.println("!! Updated Successfully");
							}
							else
							{
								System.out.println("!! Rollback due to no updation !!");						
								conn.rollback();
							}
						}
						else if(expectedResult == null || expectedResult == "")
						{
							System.out.println("There Is No expected result against this value");
							errString = itmDBAccessEJB.getErrorString("","VTRFRCE","","",conn);
							return errString;
							
						}
					}
				}
			}
				if( qcOrderNo != null && qcOrderNo.trim().length() > 0)
			{
				errString = confirmQc("qcorder_new",qcOrderNo,xtraParams,forcedFlag, conn);
				System.out.println("retString-------"+errString);
			}


		} // try
		catch(Exception e)
		{
			System.out.println("Exception : QcOrderAprv@process():" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		finally
		{
			System.out.println("!! Closing Connection in process() !!");
			try
			{
				conn.close();
				conn = null;
			}
			catch(Exception se){
				System.out.println(se.getMessage());
			}
		}
		System.out.println("errString: "+errString);
		return errString;
	} //process
		//Method for confirm qcOrder and update stock.
	private String confirmQc(String businessObj, String qcOrderNo,String xtraParams,String forcedFlag, Connection conn) throws ITMException
	{
		String methodName = "gbf_post";
		String compName = "";
		String retString = "";
		String serviceCode = "";
		String serviceURI = "";
		String actionURI = "";
		String sql = "";
		//Connection conn = null;
		PreparedStatement pStmt = null;
		ResultSet rs = null;

		try
		{
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");

			//methodName = "";
			System.out.println("++++++++++++++++==process confirmQC for qc order=== +++++++++++  3  +");
			actionURI = "http://NvoServiceurl.org/" + methodName;
			System.out.println("Action url"+actionURI);
			System.out.println("in qc ");
			System.out.println(businessObj+"---"+qcOrderNo+"---"+xtraParams+"---");
			sql = "SELECT SERVICE_CODE,COMP_NAME FROM SYSTEM_EVENTS WHERE OBJ_NAME = ? AND EVENT_CODE = 'pre_confirm' ";
			pStmt = conn.prepareStatement(sql);
			pStmt.setString(1,businessObj);
			rs = pStmt.executeQuery();
			if ( rs.next() )
			{
				serviceCode = rs.getString("SERVICE_CODE");
				compName = rs.getString("COMP_NAME");
			}
			System.out.println("===========serviceCode========= = "+serviceCode+" compName "+compName);
			sql = "SELECT SERVICE_URI,METHOD_NAME FROM SYSTEM_EVENT_SERVICES WHERE SERVICE_CODE = ? ";
			pStmt = conn.prepareStatement(sql);
			pStmt.setString(1,serviceCode);
			rs = pStmt.executeQuery();
			if ( rs.next() )
			{
				serviceURI = rs.getString("SERVICE_URI");
				methodName=rs.getString("METHOD_NAME");
			}
			System.out.println("serviceURI = "+serviceURI+" compName = "+compName);
			Service service = new Service();
			Call call = (Call)service.createCall();
			call.setTargetEndpointAddress(new java.net.URL(serviceURI));
			call.setOperationName( new javax.xml.namespace.QName("http://NvoServiceurl.org", methodName ) );
			call.setUseSOAPAction(true);
			call.setSOAPActionURI(actionURI);
			System.out.println("call in confirmQC +++++=== 4==========++++++++++=");
			Object[] aobj = new Object[4];

			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "component_name"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "tran_id"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "xtra_params"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter( new javax.xml.namespace.QName("http://NvoServiceurl.org", "forced_flag"), XMLType.XSD_STRING, ParameterMode.IN);

			aobj[0] = new String(compName);
			aobj[1] = new String(qcOrderNo);
			aobj[2] = new String(xtraParams);
			aobj[3] = new String(forcedFlag);

			call.setReturnType(XMLType.XSD_STRING);
			retString = (String)call.invoke(aobj);
			System.out.println("Return string from NVO is:==>["+retString+"]");

		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (pStmt != null )
				{
					pStmt.close();
					pStmt = null;
				}
				if( conn != null ){
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{}
		}
		return retString;
	}

	// To check the flesh Result value whether it exists with in the expected result region
	boolean isBetween(String fResult, String eResult)
	{
		double fleshResult = 0.0, eResultStart = 0.0, eResultEnd = 0.0;
		String[] value = eResult.split("-");
		fleshResult = Double.parseDouble(fResult);
		System.out.println();
		eResultStart = Double.parseDouble(value[0]);
		eResultEnd = Double.parseDouble(value[1]);
		System.out.println("process in inbetween method+++++++++++====6====+++++++++++++++=");

		// compare the region
		if((fleshResult >= eResultStart)&&(fleshResult <= eResultEnd))
		{
			return true;
		}
		else
		{
			return false;
		}
	}


	@Override
	public void remove() {
		// TODO Auto-generated method stub

	}
}
