/********************************************************
	Title : PhysicalInvFreezeConf
	Date  : 15/10/2011
	Developer: Dipak Chattar

********************************************************/

package ibase.webitm.ejb.wms;
import javax.xml.rpc.ParameterMode;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import java.rmi.RemoteException;
import java.util.*;
import javax.naming.InitialContext;
import ibase.system.config.AppConnectParm;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import java.util.Random;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.SQLException;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import ibase.webitm.ejb.fin.FinCommon;
import ibase.webitm.ejb.sys.UtilMethods;
import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.system.config.*;
import java.text.SimpleDateFormat;
import javax.ejb.Stateless; // added for ejb3
import java.io.*;
import java.math.*;
import ibase.utility.CommonConstants;
import ibase.webitm.utility.TransIDGenerator;

@Stateless // added for ejb3
public class PhysicalInvFreezeConf extends ActionHandlerEJB implements PhysicalInvFreezeConfLocal, PhysicalInvFreezeConfRemote
{
GenericUtility genericUtility = GenericUtility.getInstance();
UtilMethods utilMethods = UtilMethods.getInstance();
Random rnd = new Random();
public String actionHandler() throws RemoteException,ITMException
{
	System.out.println("actionHandler()return blank called >>>>>>>>>");
	return "";
}

public String actionHandler(String actionType, String xmlString, String objContext, String xtraParams) throws RemoteException,ITMException
{
	Document dom = null;
	String  resString = null;
	try
	{
		if (actionType.equalsIgnoreCase("IMP_FRM_DB"))
		{
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				dom = genericUtility.parseString(xmlString); 
			}
			System.out.println("inside IMP_FRM_DB");
			resString = importFromDatabase(dom,objContext,xtraParams);
		}
		if (actionType.equalsIgnoreCase("EXP_TO_EXCEL"))
		{
			if (xmlString != null && xmlString.trim().length()!=0)
			{
				dom = genericUtility.parseString(xmlString);
			}
			System.out.println("inside EXP_TO_EXCEL");
			resString = exportToExcel(dom,objContext,xtraParams);
		}
		if (actionType.equalsIgnoreCase("IMP_FRM_EXCEL"))
		{
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				dom = genericUtility.parseString(xmlString); 
			}
			System.out.println("inside IMP_FRM_EXCEL");
			resString = importFromExcel(dom,objContext,xtraParams);
		}
	}
   	catch(Exception e)
	{
		System.out.println("Exception :Physical Inc Count :actionHandler(String xmlString):" + e.getMessage() + ":");
		e.printStackTrace();
		throw new ITMException(e);
	}
	System.out.println("returning from actionHandler"+resString);
	return resString;
}

public String confirm(String tranId, String xtraParams, String forcedFlag) throws RemoteException,ITMException
{
	String retString = "Confirmed Success";
	String sql = "";
	Connection conn = null;
	PreparedStatement pStmt = null;
	ITMDBAccessEJB itmDBAccessEJB = null;
	String tranIds = tranId;
	String xtraParam = xtraParams;
	String forcedF = forcedFlag;
	String errString = null;
	ResultSet rs = null;
	System.out.println("Confirm Action Called:::");
	String confirmed = "";
	try
	{	
		itmDBAccessEJB = new ITMDBAccessEJB();
		ConnDriver connDriver = null;
		connDriver = new ConnDriver();
		conn = connDriver.getConnectDB("DriverITM");
		connDriver = null;
		if( errString == null || errString.trim().length() == 0 )
		{
			sql = "Select confirmed from inv_freeze where tran_id = ?";
			pStmt = conn.prepareStatement(sql);
			pStmt.setString(1,tranIds);
			rs = pStmt.executeQuery();
			while(rs.next())
			{
				confirmed = rs.getString(1)==null?"":rs.getString(1);
				if(confirmed.equals("Y"))
				{
					errString = itmDBAccessEJB.getErrorString("","VTDIST26","","",conn);
				}
			}
			pStmt.close();
			pStmt = null;
			rs.close();
			rs = null;
		}
		if( errString == null || errString.trim().length() == 0 )
		{
			errString = issueAdjReceiptAndIssue(tranIds, xtraParam, forcedF, conn);
			if(errString.equals(""))
			{
				sql =  "update inv_freeze set CONFIRMED = 'Y' where tran_id = ?";
				pStmt = conn.prepareStatement(sql);
				pStmt.setString(1,tranIds);
				int rowcnt = pStmt.executeUpdate();
				pStmt.close();
				pStmt = null;
				if(rowcnt > 0) 
				{
					conn.commit();	
				}
//ADDED rollback 
				else
				{
					System.out.println("shamim rollbacking >>>>>>>>>>");						
					conn.rollback();
				}
				errString = itmDBAccessEJB.getErrorString("","VTSUCC1","","",conn);
			}
            conn.close();
			conn = null;
		}
		else
		{
			conn.close();
			conn = null;
			return errString;
		}
	}
	catch( Exception e)
	{
		e.printStackTrace();
	}
//added finally 
	finally
	{
		
		try{
			if(conn != null)
			{
				if(rs != null )
				{
					rs.close();
				}
				rs = null;
				if(pStmt != null )
				{
					pStmt.close();
				}
				pStmt = null;
				System.out.println("InSide finally..  rollbacking >>>>>>>>>>>>>>>>> ");
				conn.rollback();
				conn.close();
				System.out.println("InSide finally.. Connection has been closed >>>>>>>>>>>>>>>>>>>>>>>>> ");
			}
				conn = null;
		}catch(SQLException se)
		{
			System.out.println("SQL Exception in finaly >>>> " + se.getMessage());
			throw new ITMException( se );
		}catch(Exception d)
		{
			d.printStackTrace();
			throw new ITMException( d );
		}  
	} 
	
	retString = errString.toString();
	return retString;
}

private String issueAdjReceiptAndIssue(String tranId,String xtraParams,String forcedFlag, Connection conn) throws RemoteException, ITMException
{
	FinCommon finCommon = new FinCommon();
	String retSting = ""; 
	String sql = "";
	String sql1 = "";
	String sql2 = "";
	StringBuffer valueXmlforIssue = new StringBuffer();
	StringBuffer valueXmlforReceipt = new StringBuffer();
	PreparedStatement pStmt = null, pStmt1 = null, pStmt2 = null, pStmt3 = null;
	String tranIds = tranId;
	String xtraParam = xtraParams;
	String forcedF = forcedFlag;
	ResultSet rs = null, rs1 = null, rs2 = null, rs3=null;
	String siteCode = "";
	String locCode = "";
	String itemCode = "";
	boolean issueCondition = false;
	boolean receiptCondition = false;
	String unit = "";
	double differenceQty = 0.0;
	double physicalQty = 0.0;
	double stockQuantity = 0.0, amount = 0.0;
	int cntISS = 0;
	int cntRCP = 0;
	double temp =0;
	String tranIdForIssue = "";
	String tranIdForReciept = "", lotNumber = "";
	String packCode = "";
	String potencyPerc = "";
	double integralQty = 0;
	String noArt = "";
	String itemSer = "";
	String keyString = ""; 
	String keyColumn = "";
	String refSeries = "";
	String flagSaveString = "";
	double issueQuantity = 0;
	double rate = 0.0;
	double grossRate = 0.0;

	try
	{
		
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
		// To retrieve tranDate and 1st issu or receipt itemSeries
		sql = "select p.tran_date, (select item_ser from item where item_code = pd.item_code) as item_ser "
		      +" ,(p.phy_cnt_ref||' AND '||p.remarks) as remarks"
			  +" from inv_freeze p , inv_freeze_det pd"
			  +" where p.tran_id = pd.tran_id and rownum=1 and p.tran_id=? order by pd.line_no";
		pStmt3 = conn.prepareStatement(sql);
		pStmt3.setString(1,tranIds);
		rs3 = pStmt3.executeQuery();
		rs3.next();
		sql = "Select site_code,item_code,loc_code,quantity,"
		+"qty_physical,unit from inv_freeze_det where tran_id = ?";
		pStmt = conn.prepareStatement(sql);
		pStmt.setString(1,tranIds);
		rs = pStmt.executeQuery();
		
		
		while (rs.next())
		{
			siteCode = rs.getString(1);
			itemCode = rs.getString(2);
			locCode = rs.getString(3);
			stockQuantity = rs.getDouble(4);
			physicalQty = rs.getDouble(5);
			unit = rs.getString(6);
			if(physicalQty > stockQuantity)
			{
				differenceQty = physicalQty - stockQuantity;
			}
			else
			{
				differenceQty = stockQuantity - physicalQty;
			}
			if(!issueCondition && differenceQty > 0)
			{
				issueCondition = true;
				valueXmlforIssue.append("<?xml version='1.0' encoding='UTF-8'?>\n");
				valueXmlforIssue.append("<Root>\n");
				valueXmlforIssue.append("<DocumentRoot>");
				valueXmlforIssue.append("<description>").append("DatawindowRoot").append("</description>");
				valueXmlforIssue.append("<group0>");
				valueXmlforIssue.append("<description>").append("Group0description").append("</description>");
				valueXmlforIssue.append("<Header0>");
				valueXmlforIssue.append("<objName><![CDATA[").append("adj_iss").append("]]></objName>");
				valueXmlforIssue.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
				valueXmlforIssue.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
				valueXmlforIssue.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
				valueXmlforIssue.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
				valueXmlforIssue.append("<action><![CDATA[").append("SAVE").append("]]></action>");
				valueXmlforIssue.append("<elementName><![CDATA[").append("").append("]]></elementName>");
				valueXmlforIssue.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
				valueXmlforIssue.append("<pkValues><![CDATA[").append("").append("]]></pkValues>");
				valueXmlforIssue.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
				valueXmlforIssue.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
				valueXmlforIssue.append("<forcedSave><![CDATA[").append(false).append("]]></forcedSave>");
				valueXmlforIssue.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
				valueXmlforIssue.append("<Detail1 dbID=\"\" domID=\"1\" objContext=\"1\" objName=\"adj_iss\">");
				valueXmlforIssue.append("<attribute pkNames=\"\" selected=\"N\" status=\"O\" updateFlag=\"N\"/>");
				valueXmlforIssue.append("<tran_id/>");
				valueXmlforIssue.append("<tran_date><![CDATA[").append((rs3.getDate(1)==null)?"":simpleDateFormat.format(rs3.getDate(1))).append("]]></tran_date>");
				valueXmlforIssue.append("<eff_date><![CDATA[").append(simpleDateFormat.format(new Date())).append("]]></eff_date>");
				valueXmlforIssue.append("<ref_ser><![CDATA[").append("ADJISS").append("]]></ref_ser>");
				valueXmlforIssue.append("<order_id><![CDATA[").append(tranId).append("]]></order_id>");
				valueXmlforIssue.append("<site_code><![CDATA[").append(siteCode).append("]]></site_code>");
				valueXmlforIssue.append("<ref_date/>");
				valueXmlforIssue.append("<ref_ser__for/>");
				valueXmlforIssue.append("<ref_id__for/>");
				valueXmlforIssue.append("<item_ser><![CDATA[").append(rs3.getString(2)).append("]]></item_ser>");
				valueXmlforIssue.append("<remarks><![CDATA[").append(rs3.getString(3)).append("]]></remarks>");
				valueXmlforIssue.append("<confirmed><![CDATA[N]]></confirmed>");
				valueXmlforIssue.append("<conf_date/>");
				valueXmlforIssue.append("<chg_date><![CDATA[").append("").append("]]></chg_date>");
				valueXmlforIssue.append("<chg_user><![CDATA[").append("").append("]]></chg_user>");
				valueXmlforIssue.append("<chg_term><![CDATA[").append("").append("]]></chg_term>");
				valueXmlforIssue.append("<emp_code__aprv/>");
				valueXmlforIssue.append("<price_list/>");
				valueXmlforIssue.append("</Detail1>");
				System.out.println("ISSUE HEADER GENERATED");
			}
			if(!receiptCondition && differenceQty < 0)
			{
				receiptCondition = true;
				valueXmlforReceipt.append("<?xml version='1.0' encoding='UTF-8'?>\n");
				valueXmlforReceipt.append("<Root>\n");
				valueXmlforReceipt.append("<DocumentRoot>");
				valueXmlforReceipt.append("<description>").append("DatawindowRoot").append("</description>");
				valueXmlforReceipt.append("<group0>");
				valueXmlforReceipt.append("<description>").append("Group0description").append("</description>");
				valueXmlforReceipt.append("<Header0>");
				valueXmlforReceipt.append("<objName><![CDATA[").append("adj_rcp").append("]]></objName>");
				valueXmlforReceipt.append("<pageContext><![CDATA[").append("1").append("]]></pageContext>");
				valueXmlforReceipt.append("<objContext><![CDATA[").append("1").append("]]></objContext>");
				valueXmlforReceipt.append("<editFlag><![CDATA[").append("A").append("]]></editFlag>");
				valueXmlforReceipt.append("<focusedColumn><![CDATA[").append("").append("]]></focusedColumn>");
				valueXmlforReceipt.append("<action><![CDATA[").append("SAVE").append("]]></action>");
				valueXmlforReceipt.append("<elementName><![CDATA[").append("").append("]]></elementName>");
				valueXmlforReceipt.append("<keyValue><![CDATA[").append("1").append("]]></keyValue>");
				valueXmlforReceipt.append("<pkValues><![CDATA[").append("").append("]]></pkValues>");
				valueXmlforReceipt.append("<taxKeyValue><![CDATA[").append("").append("]]></taxKeyValue>");
				valueXmlforReceipt.append("<saveLevel><![CDATA[").append("1").append("]]></saveLevel>");
				valueXmlforReceipt.append("<forcedSave><![CDATA[").append(false).append("]]></forcedSave>");
				valueXmlforReceipt.append("<taxInFocus><![CDATA[").append(false).append("]]></taxInFocus>");
				valueXmlforReceipt.append("<Detail1 dbID=\"\" domID=\"1\" objContext=\"1\" objName=\"adj_rcp\">");
				valueXmlforReceipt.append("<attribute pkNames=\"\" selected=\"N\" status=\"O\" updateFlag=\"N\"/>");
				valueXmlforReceipt.append("<tran_id/>");
				valueXmlforReceipt.append("<tran_date><![CDATA[").append((rs3.getDate(1)==null)?"":simpleDateFormat.format(rs3.getDate(1))).append("]]></tran_date>");
				valueXmlforReceipt.append("<eff_date><![CDATA[").append(simpleDateFormat.format(new Date())).append("]]></eff_date>");
				valueXmlforReceipt.append("<ref_ser><![CDATA[ADJRCP]]></ref_ser>");
				valueXmlforReceipt.append("<order_id><![CDATA[").append(tranId).append("]]></order_id>");
				valueXmlforReceipt.append("<site_code><![CDATA[").append(siteCode).append("]]></site_code>");
				valueXmlforReceipt.append("<ref_date/>");
				valueXmlforReceipt.append("<ref_ser__for/>");
				valueXmlforReceipt.append("<ref_id__for/>");
				valueXmlforReceipt.append("<item_ser><![CDATA[").append(rs3.getString(2)).append("]]></item_ser>");
				valueXmlforReceipt.append("<remarks><![CDATA[").append(rs3.getString(3)).append("]]></remarks>");
				valueXmlforReceipt.append("<confirmed><![CDATA[N]]></confirmed>");
				valueXmlforReceipt.append("<conf_date/>");
				valueXmlforReceipt.append("<chg_date><![CDATA[24/06/09 15:04:47]]></chg_date>");
				valueXmlforReceipt.append("<chg_user><![CDATA[RCHANDRAN ]]></chg_user>");
				valueXmlforReceipt.append("<chg_term><![CDATA[192.168.1.52   ]]></chg_term>");
				valueXmlforReceipt.append("<emp_code__aprv/>");
				valueXmlforReceipt.append("<price_list/>");
				valueXmlforReceipt.append("</Detail1>");
				System.out.println("RECIEPT HEADER GENERATED");
 			}
			if(differenceQty > 0) 
			{	
				amount = 0.0;
				System.out.println("Adjustment Issue");
				sql1 = "SELECT item_code,loc_code,site_code,crea_date,exp_date,rate,quantity,"
					+"gross_rate,lot_no,lot_sl,grade,dimension,no_art,gross_weight,net_weight,tare_weight,acct_code__inv,potency_perc,"
					+"pack_code,mfg_date,site_code__mfg,conv__qty_stduom,unit__alt,cctr_code_inv,alloc_qty FROM STOCK where item_code = ? and loc_code = ? and site_code = ? "
					          + "ORDER BY last_rcp_date ";
				
				pStmt1 = conn.prepareStatement(sql1);		 
				pStmt1.setString(1,itemCode);
				pStmt1.setString(2,locCode);
				pStmt1.setString(3,siteCode);
				
				rs1 = pStmt1.executeQuery();
				while(rs1.next())
				{
					cntISS++;
					temp = ("".equals(rs1.getDouble("quantity"))? 0.0 : rs1.getDouble("quantity"))-("".equals(rs1.getDouble("alloc_qty"))? 0.0 : rs1.getDouble("alloc_qty"));
					if( temp >= differenceQty)
					{
						issueQuantity = differenceQty;
						differenceQty = 0;
					}
					else
					{
						issueQuantity = temp;
						differenceQty = differenceQty - temp;
					}
					amount = rs1.getDouble("rate") * issueQuantity;
					valueXmlforIssue.append("<Detail2 dbID=\"\" domID=\""+cntISS+"\" objContext=\"2\" objName=\"adj_iss\">");
					valueXmlforIssue.append("<attribute pkNames=\"\" selected=\"N\" status=\"O\" updateFlag=\"N\"/>");
					valueXmlforIssue.append("<tran_id/>");
					valueXmlforIssue.append("<line_no><![CDATA[").append(Integer.toString(cntISS)).append("]]></line_no>");
					valueXmlforIssue.append("<item_code><![CDATA[").append(itemCode).append("]]></item_code>");
					valueXmlforIssue.append("<unit><![CDATA[").append(unit).append("]]></unit>");
					valueXmlforIssue.append("<loc_code><![CDATA[").append(locCode).append("]]></loc_code>");
					valueXmlforIssue.append("<lot_no><![CDATA[").append(rs1.getString("lot_no")).append("]]></lot_no>");
					valueXmlforIssue.append("<lot_sl><![CDATA[").append(rs1.getString("lot_sl")).append("]]></lot_sl>");
					valueXmlforIssue.append("<quantity><![CDATA[").append(issueQuantity).append("]]></quantity>");
					valueXmlforIssue.append("<sundry_type/>");
					valueXmlforIssue.append("<sundry_code/>");
					valueXmlforIssue.append("<rate><![CDATA[").append(rs1.getString("rate")).append("]]></rate>");
					valueXmlforIssue.append("<gross_rate><![CDATA[").append(rs1.getString("gross_rate")==null?"":rs1.getString("gross_rate")).append("]]></gross_rate>");
					valueXmlforIssue.append("<grade><![CDATA[").append(rs1.getString("grade")==null?"":rs1.getString("grade")).append("]]></grade>");
					valueXmlforIssue.append("<dimension><![CDATA[").append(rs1.getString("dimension")==null?"":rs1.getString("dimension")).append("]]></dimension>");
					valueXmlforIssue.append("<no_art><![CDATA[").append(rs1.getString("no_art")==null?"":rs1.getString("no_art")).append("]]></no_art>");
					valueXmlforIssue.append("<amount><![CDATA[").append(String.valueOf(amount)).append("]]></amount>");
					valueXmlforIssue.append("<gross_weight><![CDATA[").append(rs1.getString("gross_weight")==null?"":rs1.getString("gross_weight")).append("]]></gross_weight>");
					valueXmlforIssue.append("<tare_weight><![CDATA[").append(rs1.getString("tare_weight")==null?"":rs1.getString("tare_weight")).append("]]></tare_weight>");
					valueXmlforIssue.append("<net_weight><![CDATA[").append(rs1.getString("net_weight")==null?"":rs1.getString("net_weight")).append("]]></net_weight>");
					valueXmlforIssue.append("<acct_code__dr><![CDATA[").append(finCommon.getFinparams("999999","ACCT_CODE_ISS_RCP",conn)).append("]]></acct_code__dr>");
					valueXmlforIssue.append("<cctr_code__dr><![CDATA[").append(finCommon.getFinparams("999999","COST_CEN_ISS_RCP",conn)).append("]]></cctr_code__dr>");
					valueXmlforIssue.append("<acct_code__cr><![CDATA[").append(rs1.getString("acct_code__inv")==null?"":rs1.getString("acct_code__inv")).append("]]></acct_code__cr>");
					valueXmlforIssue.append("<cctr_code__cr><![CDATA[").append(rs1.getString("cctr_code_inv")==null?"":rs1.getString("cctr_code_inv")).append("]]></cctr_code__cr>");
					valueXmlforIssue.append("<potency_perc><![CDATA[").append(rs1.getString("potency_perc")==null?"":rs1.getString("potency_perc")).append("]]></potency_perc>");
					valueXmlforIssue.append("<pack_code><![CDATA[").append(rs1.getString("pack_code")==null?"":rs1.getString("pack_code")).append("]]></pack_code>");
					valueXmlforIssue.append("<mfg_date><![CDATA[").append("").append("]]></mfg_date>");
					valueXmlforIssue.append("<exp_date><![CDATA[").append((rs1.getDate("exp_date")==null)?"":simpleDateFormat.format(rs1.getDate("exp_date"))).append("]]></exp_date>");
					valueXmlforIssue.append("<site_code__mfg><![CDATA[").append(rs1.getString("site_code__mfg")==null?"":rs1.getString("site_code__mfg")).append("]]></site_code__mfg>");
					valueXmlforIssue.append("<conv__qty_stduom><![CDATA[").append(rs1.getString("conv__qty_stduom")==null?"":rs1.getString("conv__qty_stduom")).append("]]></conv__qty_stduom>");
					valueXmlforIssue.append("<unit__alt><![CDATA[").append(rs1.getString("unit__alt")==null?"":rs1.getString("unit__alt")).append("]]></unit__alt>");
					valueXmlforIssue.append("</Detail2>");
					if (differenceQty == 0)
					{
						break;
					}
				}
				pStmt1.close();
				pStmt1 = null;
				rs1.close();
				rs1 = null;
				System.out.println("ISSUE DETAIL GENERATED");
			}
			else if(differenceQty < 0)
			{
				cntRCP++;
				System.out.println("Adjustment Receipt");
				sql1 = "select rate, gross_rate from invtrace where tran_id = ("
					+"select max(tran_id) from invtrace	where tran_date = ("
					+"select max(tran_date) from invtrace where item_code = ? and site_code = ? and ref_ser = ?)"
					+"and item_code = ? and site_code = ?)";

				pStmt1 = conn.prepareStatement(sql1);		 
				pStmt1.setString(1,itemCode);
				pStmt1.setString(2,siteCode);
				pStmt1.setString(3,"P-RCP");
				pStmt1.setString(4,itemCode);
				pStmt1.setString(5,siteCode);
				rs1 = pStmt1.executeQuery();
				if(rs1.next())
				{
					rate = rs1.getDouble("rate");
					grossRate =rs1.getDouble("gross_rate");						
				}
				else
				{
					rate = 0.0;
					grossRate = 0.0;
				}
				pStmt1.close();
				pStmt1 = null;
				rs1.close();
				rs1 = null;
				sql2 = "select item_ser, pack_code, potency_perc, integral_Qty from item where item_code = ? ";
				pStmt2 = conn.prepareStatement(sql2);
				pStmt2.setString(1,itemCode);
				rs2 = pStmt2.executeQuery();
				if(rs2.next())
				{
					packCode = rs2.getString("pack_code")==null?"":rs2.getString("pack_code");
					potencyPerc = rs2.getString("potency_perc")==null?"":rs2.getString("potency_perc");
					integralQty = rs2.getDouble("integral_Qty");
					itemSer = rs2.getString("item_ser")==null?"":rs2.getString("item_ser");
					
				}					
				pStmt2.close();
				pStmt2 = null;
				rs2.close();
				rs2 = null;
				
				noArt = "";
				if(integralQty != 0.0)
				{
					temp = Math.abs(differenceQty)/integralQty;
					BigDecimal bd = new BigDecimal(temp);
					bd = bd.setScale(0,BigDecimal.ROUND_UP);
					noArt = String.valueOf(bd);
				}
				else
				{
					noArt = String.valueOf(differenceQty);
				}
				
				sql2 = "select key_string, tran_id_col, ref_ser from transetup where tran_window = ?";
				pStmt2 = conn.prepareStatement(sql2);
				pStmt2.setString(1,"phyInvCnt_lotno");
				rs2 = pStmt2.executeQuery();
				if(rs2.next())
				{
					keyString = rs2.getString("key_String"); 
					keyColumn = rs2.getString("tran_id_col");
					refSeries = rs2.getString("ref_ser");
					
				}
				pStmt2.close();
				pStmt2 = null;
				rs2.close();
				rs2 = null;
				
				valueXmlforReceipt.append("<Detail2 dbID=\"\" domID=\""+cntRCP+"\" objContext=\"2\" objName=\"adj_rcp\">");
				valueXmlforReceipt.append("<attribute pkNames=\"\" selected=\"N\" status=\"O\" updateFlag=\"N\"/>");
				valueXmlforReceipt.append("<tran_id/>");
				valueXmlforReceipt.append("<line_no><![CDATA[").append(cntRCP).append("]]></line_no>");
				valueXmlforReceipt.append("<item_code><![CDATA[").append(itemCode).append("]]></item_code>");
				valueXmlforReceipt.append("<unit><![CDATA[").append(unit).append("]]></unit>");
				valueXmlforReceipt.append("<loc_code><![CDATA[").append(locCode).append("]]></loc_code>");
				valueXmlforReceipt.append("<lot_sl><![CDATA[1S]]></lot_sl>");
				valueXmlforReceipt.append("<quantity><![CDATA[").append(String.valueOf(Math.abs(differenceQty))).append("]]></quantity>");
				valueXmlforReceipt.append("<sundry_type/>");
				valueXmlforReceipt.append("<sundry_code/>");
				valueXmlforReceipt.append("<rate><![CDATA[").append(rate).append("]]></rate>");
				valueXmlforReceipt.append("<gross_rate><![CDATA[").append(grossRate).append("]]></gross_rate>");
				valueXmlforReceipt.append("<grade/>");
				valueXmlforReceipt.append("<dimension/>");
				valueXmlforReceipt.append("<no_art><![CDATA[").append(noArt).append("]]></no_art>");
				valueXmlforReceipt.append("<amount/>");
				valueXmlforReceipt.append("<gross_weight><![CDATA[").append("0").append("]]></gross_weight>");
				valueXmlforReceipt.append("<tare_weight><![CDATA[").append("0").append("]]></tare_weight>");
				valueXmlforReceipt.append("<net_weight><![CDATA[").append("0").append("]]></net_weight>");
				String[] acctCctrDetrValue = finCommon.getFromAcctDetr(itemCode,itemSer,"STKINV",conn).split(",");
				valueXmlforReceipt.append("<acct_code__dr><![CDATA[").append(acctCctrDetrValue[0]).append("]]></acct_code__dr>");
				valueXmlforReceipt.append("<cctr_code__dr><![CDATA[").append(acctCctrDetrValue[1]).append("]]></cctr_code__dr>");
				valueXmlforReceipt.append("<acct_code__cr><![CDATA[").append(finCommon.getFinparams("999999","ACCT_CODE_ISS_RCP",conn)).append("]]></acct_code__cr>");
				valueXmlforReceipt.append("<cctr_code__cr><![CDATA[").append(finCommon.getFinparams("999999","COST_CEN_ISS_RCP",conn)).append("]]></cctr_code__cr>");
				valueXmlforReceipt.append("<potency_perc><![CDATA[").append(potencyPerc).append("]]></potency_perc>");
				valueXmlforReceipt.append("<pack_code><![CDATA[").append(packCode).append("]]></pack_code>");
				valueXmlforReceipt.append("<mfg_date><![CDATA[]]></mfg_date>");
				valueXmlforReceipt.append("<exp_date><![CDATA[]]></exp_date>");
				valueXmlforReceipt.append("<site_code__mfg><![CDATA[").append("").append("]]></site_code__mfg>");
				valueXmlforReceipt.append("<conv__qty_stduom><![CDATA[").append("").append("]]></conv__qty_stduom>");
				valueXmlforReceipt.append("<unit__alt><![CDATA[").append(unit).append("]]></unit__alt>");
				String tempLotNumnberString =  valueXmlforReceipt.toString();
				StringBuffer tempLotNumber = new StringBuffer(tempLotNumnberString);
				tempLotNumber.append("</Detail2>");
				tempLotNumber.append("</Header0>");
				tempLotNumber.append("</group0>");
				tempLotNumber.append("</DocumentRoot>");
				tempLotNumber.append("</Root>");
				lotNumber = getUniqueKey(tempLotNumber.toString(),keyString,keyColumn,refSeries,xtraParam,conn);
				valueXmlforReceipt.append("<lot_no><![CDATA[").append(lotNumber).append("]]></lot_no>");
				valueXmlforReceipt.append("</Detail2>");
				System.out.println("RECEIPT DETAIL GENERATED");
			}
			
		}
		pStmt3.close();
		pStmt3 = null;
		rs3.close();
		rs3 = null;
		pStmt.close();
		pStmt = null;
		rs.close();
		rs = null;
		valueXmlforIssue.append("</Header0>");
		valueXmlforIssue.append("</group0>");
		valueXmlforIssue.append("</DocumentRoot>");
		valueXmlforIssue.append("</Root>");
		valueXmlforReceipt.append("</Header0>");
		valueXmlforReceipt.append("</group0>");
		valueXmlforReceipt.append("</DocumentRoot>");
		valueXmlforReceipt.append("</Root>");
		
		flagSaveString = "";

		if(issueCondition && flagSaveString.equals(""))
		{
			System.out.println("Saving Data for Issue");
			retSting = saveData(siteCode,valueXmlforIssue.toString(),conn);
			if(retSting.indexOf("Success") > -1)
			{
				String[] arrayForTranId = retSting.split("<TranID>");
				int endIndex = arrayForTranId[1].indexOf("</TranID>");
				tranIdForIssue = arrayForTranId[1].substring(0,endIndex);
				conn.commit();
				retSting = confirmIssueAndReceipt("adj_iss",tranIdForIssue,xtraParam,forcedF,conn);
				if(retSting.indexOf("VTSUCC1") > -1)
				{
					retSting = "";
				}
				else 
				{
					flagSaveString = retSting;
				}
			}
			else 
			{
				flagSaveString = retSting;
				System.out.println("shamim rollbacking >>>>>>>>>>");
				conn.rollback();
				
			}
			
			
			System.out.println("Issue "+tranIdForIssue);
			
		}
		if(receiptCondition && flagSaveString.equals(""))
		{
			System.out.println("Saving Data for Receipt");
			retSting = saveData(siteCode,valueXmlforReceipt.toString(),conn);
			if(retSting.indexOf("Success") > -1)
			{
				String[] arrayForTranId = retSting.split("<TranID>");
				int endIndex = arrayForTranId[1].indexOf("</TranID>");
				tranIdForReciept = arrayForTranId[1].substring(0,endIndex);
				conn.commit();
				retSting = confirmIssueAndReceipt("adj_rcp",tranIdForReciept,xtraParam,forcedF,conn);
				if(retSting.indexOf("VTSUCC1") > -1)
				{
					retSting = "";
				}
			}
			else 
			{

				flagSaveString = retSting;
				System.out.println("shamim rollbacking >>>>>>>>>>");
				conn.rollback();
				
			}
			
			
			System.out.println("Receipt "+tranIdForReciept);
			
		}
		
		
	}
	catch(Exception e)
	{
		System.out.println("Exception : PhysicalInvCnt : actionHandler :(Document dom)" +e.getMessage());
		throw new ITMException(e);
	}
	System.out.println("Dhawal result " +retSting);
	return retSting;
}

public String confirmIssueAndReceipt(String businessObj, String tranIdFr,String xtraParams, String forcedFlag, Connection conn) throws ITMException
{
	String methodName = "";
	String compName = "";
	String retString = "";
	String serviceCode = "";
	String serviceURI = "";
	String actionURI = "";
	String sql = "";
	PreparedStatement pStmt = null;
	ResultSet rs = null;
	System.out.println("confirmIssueAndReceipt(String businessObj, String tranIdFr,String xtraParams, String forcedFlag, Connection conn) called >>><!@#>");
			
	try
	{
		methodName = "gbf_post";
		actionURI = "http://NvoServiceurl.org/" + methodName;
		
		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 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");
		}
		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);
		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(tranIdFr);
		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;
			}
			 
		}
		catch(Exception e)
		{}
	}
	return retString;
}


private String importFromDatabase(Document dom, String objContext, String xtraParams) throws RemoteException , ITMException
{
	String siteCode = "", locCodeFrom = "", locCodeTo = "";
	String itemSerFrom = "", itemSerTo = "", itemCodeFrom = "", itemCodeTo = "";
	String sql = "";
	StringBuffer valueXmlString = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root>\r\n");
	Connection conn = null;
	PreparedStatement pStmt1 = null;
	PreparedStatement pStmt2 = null;
	ResultSet rs = null, rs1 = null;
	String returnValue1 = "";
	ConnDriver connDriver = new ConnDriver();
	GenericUtility genericUtility = GenericUtility.getInstance();
	try
	{
		conn = connDriver.getConnectDB("DriverITM");
		connDriver = null;
		siteCode= genericUtility.getColumnValue("site_code",dom);
		locCodeFrom = genericUtility.getColumnValue("loc_code__from",dom);
		locCodeTo = genericUtility.getColumnValue("loc_code__to",dom);
		itemSerFrom = genericUtility.getColumnValue("item_ser__from",dom);
		itemSerTo = genericUtility.getColumnValue("item_ser__to",dom);
		itemCodeFrom = genericUtility.getColumnValue("item_code__from",dom);
		itemCodeTo = genericUtility.getColumnValue("item_code__to",dom);
		sql = "SELECT ITEM_CODE,LOC_CODE,SUM(QUANTITY) as Quantity,UNIT,SUM(Quantity*RATE) as Amount,SITE_CODE"
			 +" FROM STOCK "
			 +" WHERE SITE_CODE = ? "
			 +" AND LOC_CODE >= ? "
			 +" AND LOC_CODE <= ? "
			 +" AND ITEM_SER >= ? "
			 +" AND ITEM_SER <= ? "
			 +" AND ITEM_CODE >= ? "
			 +" AND ITEM_CODE <= ? "
			 +" GROUP BY ITEM_CODE,LOC_CODE,SITE_CODE,UNIT";
			 
		System.out.println("sql "+sql);
		pStmt1 = conn.prepareStatement(sql);
		pStmt1.setString( 1, siteCode );
		pStmt1.setString( 2, locCodeFrom );
		pStmt1.setString( 3, locCodeTo );
		pStmt1.setString( 4, itemSerFrom );
		pStmt1.setString( 5, itemSerTo );
		pStmt1.setString( 6, itemCodeFrom );
		pStmt1.setString( 7, itemCodeTo );
		rs = pStmt1.executeQuery();
		while (rs.next())
		{
			String itemCode = rs.getString(1);
			
			valueXmlString.append("<Detail>\r\n");
			valueXmlString.append("<site_code>").append("<![CDATA[").append(siteCode).append("]]>").append("</site_code>\r\n");
			valueXmlString.append("<item_code>").append("<![CDATA[").append(itemCode).append("]]>").append("</item_code>\r\n");
			sql = "SELECT DESCR FROM ITEM WHERE ITEM_CODE = ?";
			pStmt2 = conn.prepareStatement(sql);
			pStmt2.setString( 1, itemCode );
			rs1 = pStmt2.executeQuery();
			if(rs1.next())
			{
				returnValue1 = rs1.getString(1);					
			}
			pStmt2.close();
			pStmt2 = null;
			rs1.close();
			rs1 = null;
			
			valueXmlString.append("<item_descr>").append(returnValue1).append("</item_descr>\r\n");
			valueXmlString.append("<loc_code>").append("<![CDATA[").append(rs.getString(2)).append("]]>").append("</loc_code>\r\n");
			valueXmlString.append("<stock_quantity>").append("<![CDATA[").append(rs.getString(3)).append("]]>").append("</stock_quantity>\r\n");
			valueXmlString.append("<amount>").append("<![CDATA[").append(rs.getString(5)).append("]]>").append("</amount>\r\n");
			valueXmlString.append("<physical_qty>").append("<![CDATA[").append(rs.getString(3)).append("]]>").append("</physical_qty>\r\n");
			valueXmlString.append("<unit>").append("<![CDATA[").append(rs.getString(4)).append("]]>").append("</unit>\r\n");
			valueXmlString.append("<difference_qty>").append("<![CDATA[").append("0").append("]]>").append("</difference_qty>\r\n");
			String locCode = rs.getString(2);
			String siteCode1 = rs.getString(6);
			sql = "SELECT DESCR FROM SITE WHERE SITE_CODE = ?";
			pStmt2 = conn.prepareStatement(sql);
			pStmt2.setString( 1, siteCode1 );
			rs1 = pStmt2.executeQuery();
			if(rs1.next())
			{
				returnValue1 = rs1.getString(1);					
			}
			pStmt2.close();
			pStmt2 = null;
			rs1.close();
			rs1 = null;
			valueXmlString.append("<site_descr>").append("<![CDATA[").append(returnValue1).append("]]>").append("</site_descr>\r\n");
			sql = "SELECT DESCR FROM LOCATION WHERE LOC_CODE = ?";
			pStmt2 = conn.prepareStatement(sql);
			pStmt2.setString( 1, locCode );
			rs1 = pStmt2.executeQuery();
			if(rs1.next())
			{
				returnValue1 = rs1.getString(1);					
			}
			pStmt2.close();
			pStmt2 = null;
			rs1.close();
			rs1 = null;
			valueXmlString.append("<location_descr>").append("<![CDATA[").append(returnValue1).append("]]>").append("</location_descr>\r\n");
			valueXmlString.append("</Detail>\r\n");
		}
		pStmt1.close();
		pStmt1 = null;	
		valueXmlString.append("</Root>\r\n");			
	}
	catch(SQLException e)
	{
		System.out.println("Exception : Physical Inv Fount : importFromDatabase " +e.getMessage());
		throw new ITMException(e);
	}
	catch(Exception e)
	{
		System.out.println("Exception : Physical Inv Fount : importFromDatabase" +e.getMessage());
		throw new ITMException(e);
	}
	finally
	{
		try
		{
			System.out.println("Closing Connection........");
			conn.close();
			conn = null;
		}catch(SQLException se){}
	}
	System.out.println("valueXmlString.toString() :"+valueXmlString.toString());
	return valueXmlString.toString();
}

@SuppressWarnings("deprecation")
private String exportToExcel(Document dom, String objContext, String xtraParams) throws RemoteException , ITMException
{
    NodeList parentNodeList=null;
    Node parentNode=null;
    String siteCode = "";
	String itemCode = "";
	String itemDescription = "";
	String locationCode = "";
	String unit = "";
	String stockQuantity = "";
	String value = "";
	String physicalQuantity = "";
	String siteDescription = "";
	String locationDescription = "";
	String resultString = "";
	HSSFRow row = null;
	String userId = "";
	String tranDate = "";
	java.util.Date date = new java.util.Date();			
	SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
	tranDate = sdf.format(date);
	userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");			
	
	final String[] titles = {
		"Site Code","Item Code", "Item Description", "Location Code", "Unit", 
		"Book Qty", "Amount", "Physical Qty","Site Description", "Location Description"
	};
		
	try
	{
	    HSSFWorkbook wb;
		wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("PhyInvCnt");
        sheet.autoSizeColumn((short) 1);
		
		HSSFRow headerRow = sheet.createRow(0);
		headerRow.setHeightInPoints(40);
		HSSFCell headerCell;
		
		for (int cellCtr = 0; cellCtr < titles.length; cellCtr++) 
		{
			headerCell = headerRow.createCell((short)cellCtr);
			headerCell.setCellValue(titles[cellCtr]);
		}
		
		int insertRow = 1;
		
		parentNodeList = dom.getElementsByTagName("Detail2");
        int childNodeListLength = parentNodeList.getLength();
		for(int ctr = 0; ctr < childNodeListLength; ctr++)
        {
            System.out.println("ctr ::"+ctr);
            parentNode = parentNodeList.item(ctr);
            
            siteCode = genericUtility.getColumnValueFromNode("site_code", parentNode);
            itemCode = genericUtility.getColumnValueFromNode("item_code", parentNode);
            itemDescription = genericUtility.getColumnValueFromNode("item_descr", parentNode);
            locationCode = genericUtility.getColumnValueFromNode("loc_code", parentNode);
            unit = genericUtility.getColumnValueFromNode("unit", parentNode);
            stockQuantity = genericUtility.getColumnValueFromNode("stock_quantity", parentNode);
            value = genericUtility.getColumnValueFromNode("amount", parentNode);
            physicalQuantity = genericUtility.getColumnValueFromNode("physical_qty", parentNode);
            siteDescription = genericUtility.getColumnValueFromNode("site_descr", parentNode);
            locationDescription = genericUtility.getColumnValueFromNode("location_descr", parentNode);
            insertRow++;
			row = sheet.createRow(insertRow);
			for (int j = 0; j < titles.length; j++) 
			{
			}
			row.getCell(0).setCellValue(siteCode);
			row.getCell(1).setCellValue(itemCode);
			row.getCell(2).setCellValue(itemDescription);
			row.getCell(3).setCellValue(locationCode);
			row.getCell(4).setCellValue(unit);
			row.getCell(5).setCellValue(Double.parseDouble(stockQuantity));
			row.getCell(6).setCellValue(Double.parseDouble(value));
			row.getCell(7).setCellValue(Double.parseDouble(physicalQuantity));
			row.getCell(8).setCellValue(siteDescription);
			row.getCell(9).setCellValue(locationDescription);
			System.out.println("New Row Created");
             
        } // end for

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document dom1 = db.parse( "/IBASEHOME/ibase.xml" );
		String phyInvPath = dom1.getElementsByTagName( "phy_inv_path" ).item(0).getFirstChild().getNodeValue();
		String file = phyInvPath+ File.separator + "PhyInv_"+ siteCode.trim() + "_" + userId.trim()+"_"+tranDate+".xls ";
		FileOutputStream out = new FileOutputStream(file);
		wb.write(out);
		out.close();
		StringBuffer valueXmlString = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root>\r\n");
		valueXmlString.append("<Detail>\r\n");
		valueXmlString.append("<site_code>").append("<![CDATA[]]>").append("</site_code>\r\n");
		valueXmlString.append("<item_code>").append("<![CDATA[]]>").append("</item_code>\r\n");
		valueXmlString.append("<item_descr>").append("<![CDATA[]]>").append("</item_descr>\r\n");
		valueXmlString.append("<loc_code>").append("<![CDATA[]]>").append("</loc_code>\r\n");
		valueXmlString.append("<stock_quantity>").append("<![CDATA[]]>").append("</stock_quantity>\r\n");
		valueXmlString.append("<amount>").append("<![CDATA[]]>").append("</amount>\r\n");
		valueXmlString.append("<physical_qty>").append("<![CDATA[]]>").append("</physical_qty>\r\n");
		valueXmlString.append("<unit>").append("<![CDATA[]]>").append("</unit>\r\n");
		valueXmlString.append("<difference_qty>").append("<![CDATA[]]>").append("</difference_qty>\r\n");
		valueXmlString.append("<site_descr>").append("<![CDATA[]]>").append("</site_descr>\r\n");
		valueXmlString.append("<location_descr>").append("<![CDATA[]]>").append("</location_descr>\r\n");
		valueXmlString.append("</Detail>\r\n");
		
		valueXmlString.append("</Root>\r\n");
		System.out.println("End of collected datas......");
		resultString = valueXmlString.toString();
	}
	catch (Exception e)
	{
		System.out.println("Exception :PhysicalInvCnt :exportToExcel():" + e.getMessage() + ":");
		e.printStackTrace();
		throw new ITMException(e);
	}
	
	
	return resultString;
}

@SuppressWarnings("deprecation")
private String importFromExcel(Document dom, String objContext, String xtraParams) throws RemoteException , ITMException
{	
	StringBuffer valueXmlString = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root>\r\n");
	double stockQty = 0.0;
	double phyQty = 0.0;
	double value = 0.0;
	
	try 
	{	File file = new File("PhysicalInventory.xls"); 
		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 = 2; r <= rows; r++) 
		{
			row = sheet.getRow(r);
			if(row != null) 
			{
					valueXmlString.append("<Detail>\r\n");
					cell = row.getCell((short)0);
					if(cell != null) 
					{
						valueXmlString.append("<site_code>").append("<![CDATA[").append(cell.getStringCellValue()).append("]]>").append("</site_code>\r\n");
					}
					cell = row.getCell((short)1);
					if(cell != null) 
					{
						valueXmlString.append("<item_code>").append("<![CDATA[").append(cell.getStringCellValue()).append("]]>").append("</item_code>\r\n");
					}
					cell = row.getCell((short)2);
					if(cell != null) 
					{
						valueXmlString.append("<item_descr>").append(cell.getStringCellValue()).append("</item_descr>\r\n");
					}
					cell = row.getCell((short)3);
					if(cell != null) 
					{
						valueXmlString.append("<loc_code>").append("<![CDATA[").append(cell.getStringCellValue()).append("]]>").append("</loc_code>\r\n");
					}
					cell = row.getCell((short)4);
					if(cell != null) 
					{
						valueXmlString.append("<unit>").append("<![CDATA[").append(cell.getStringCellValue()).append("]]>").append("</unit>\r\n");
					}
					cell = row.getCell((short)5);
					if(cell != null) 
					{
						stockQty = cell.getNumericCellValue();
						valueXmlString.append("<stock_quantity>").append("<![CDATA[").append(String.valueOf(stockQty)).append("]]>").append("</stock_quantity>\r\n");
					}
					cell = row.getCell((short)6);
					if(cell != null) 
					{
						value = cell.getNumericCellValue();
						valueXmlString.append("<amount>").append("<![CDATA[").append(String.valueOf(value)).append("]]>").append("</amount>\r\n");
					}
					cell = row.getCell((short)7);
					if(cell != null) 
					{
						phyQty = cell.getNumericCellValue();
						valueXmlString.append("<physical_qty>").append("<![CDATA[").append(String.valueOf(phyQty)).append("]]>").append("</physical_qty>\r\n");
					}
					
					valueXmlString.append("<difference_qty>").append("<![CDATA[").append(String.valueOf(stockQty-phyQty)).append("]]>").append("</difference_qty>\r\n");
					
					cell = row.getCell((short)8);
					if(cell != null) 
					{
						valueXmlString.append("<site_descr>").append("<![CDATA[").append(cell.getStringCellValue()).append("]]>").append("</site_descr>\r\n");
					}
					cell = row.getCell((short)9);
					if(cell != null) 
					{
						valueXmlString.append("<location_descr>").append("<![CDATA[").append(cell.getStringCellValue()).append("]]>").append("</location_descr>\r\n");
					}
					valueXmlString.append("</Detail>\r\n");
			}
		}
	
		System.out.println(valueXmlString.toString());
		valueXmlString.append("</Root>\r\n");
	}
	catch(Exception ioe) 
	{
		ioe.printStackTrace();
	}

	return valueXmlString.toString();
}

public String saveData(String siteCode,String xmlString, Connection conn) throws ITMException
{
    System.out.println("saving data...........");
    InitialContext ctx = null;
    String retString = null;
    MasterStatefulLocal masterStateful = null; // for ejb3
    try
    {
        AppConnectParm appConnect = new AppConnectParm();
        ctx = new InitialContext(appConnect.getProperty());
        masterStateful = (MasterStatefulLocal)ctx.lookup("ibase/MasterStatefulEJB/local");
        String [] authencate = new String[2];
        authencate[0] = "";
        authencate[1] = "";
        System.out.println("xmlString :::: " + xmlString+"END END END");
        retString = masterStateful.processRequest(authencate, siteCode, true, xmlString,true,conn);
		masterStateful = null;
        System.out.println("masterStateful.processRequest(authencate, siteCode, true, xmlString,true,conn) >>>>> " + retString+" shamim");
     }
     catch(ITMException itme)
     {
        System.out.println("ITMException :Physical Inv Fount : saveData :==>");
        throw itme;
     }
     catch(Exception e)
     {
        System.out.println("Exception :Physical Inv Fount : saveData :==>");
        throw new ITMException(e);
     }
       return retString;
}

    private String getUniqueKey(String xmlValues, String keyString, String keyCol, String tranSer, String xtraParams,Connection conn)throws ITMException
    {
        String uniqueKey = null;
        try
        {
			String userId = "BASE";
            System.out.println("Key String for " + tranSer + " - " + keyString);
            TransIDGenerator tg = new TransIDGenerator(xmlValues,userId, CommonConstants.DB_NAME);
            uniqueKey = tg.generateTranSeqID(tranSer, keyCol, keyString, conn);
        }
        catch(Exception e)
        {
            System.out.println("Exception :Physical Inv Fount : getUniqueKey :==>\n" + e.getMessage());
            e.printStackTrace();
            uniqueKey = null;
            throw new ITMException(e);
        }
        System.out.println("Generated Primary Key :" + uniqueKey);
        return uniqueKey;
    }

}