/*
    Window Name : w_wavegen
*/

package ibase.webitm.ejb.wms;

import ibase.system.config.ConnDriver;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.MasterStatefulLocal;
import ibase.webitm.ejb.ProcessEJB;
import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.ejb.dis.InvAllocTraceBean;
import ibase.webitm.reports.utility.XSDParser;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.TransIDGenerator;

import java.awt.print.PrinterJob;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.print.PrintService;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
//import net.sf.jasperreports.governors.GovernorException;

@javax.ejb.Stateless
public class WaveGenerationPrc extends ProcessEJB implements WaveGenerationPrcLocal,WaveGenerationPrcRemote //SessionBean
{
	String siteCode = null;
	String itemSerFr = null;
	String itemSerTo = null;
	String custCodeFr = null;
	String custCodeTo = null;
	//Added by Chandni 30-May-2012
	String custCodeDlvFr = null;
	String custCodeDlvTo = null;
	//Ended by chandni 30-May-2012
	String custCode = null;
	//Change by Sumit Sarkar on 09/03/12 create 2 variable start.
	String itemCodeFr = null;
	String itemCodeTo = null;
	//Change by Sumit Sarkar on 09/03/12 create 2 variable start.
	String DefaultQtyFlag= null;
	
	//Changed sumit on 25/08/12 declare waveId as globe variable 
	String waveId = "";
	
	String saleOrderFr = null;
	String saleOrderTo = null;
	String postOrderFg = null;
	String 	sql = null;
	String sDateTo = null;
	String sDateFr = null;
	//Changed by sumit on 18/09/12 create single_lot, master_pack_allow, active_pick_allow, stock_to_dock_allow start.
	String globalSingleLot = "";
	String globalMasterPackAllow = "";
	String globalActivePickAllow = "";
	String globalStockToDockAllow = "";
	//Changed by sumit on 18/09/12 create single_lot, master_pack_allow, active_pick_allow, stock_to_dock_allow end.
	
	//Changed by sumit on 11/12/12 adding variable start
	//String globalSaleOrder = "";	
	private HashMap pickSaleOrderDetail = new  HashMap();
	String globalParcelPackAllow = "";
	//Changed by sumit on 11/12/12 adding variable end
	
	double balStockQty = 0;

	java.sql.Timestamp dateTo =  null;
	java.sql.Timestamp dueDate =  null;
	java.sql.Timestamp dateFr =  null;
	Map itemCodeMap = new HashMap();
	ArrayList saleOrderArr = new ArrayList();
	ArrayList custCodeArr = new ArrayList();
	ArrayList dueDateArr = new ArrayList();
	MasterStatefulLocal masterStatefulLocal = null;
	
	InvAllocTraceBean invAllocTrace = new InvAllocTraceBean();
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	//ConnDriver connDriver = new ConnDriver();
	CommonConstants commonConstants = new CommonConstants();
	String chgUser = null;
	String chgTerm = null;
	//Changed by sumit on 03/08/12 To get the wave mod
	String waveMode = "";
	//Changed by sumit on 03/10/12 created printer variable
	String printer = "";	
	//Changedby sumit on 24/11/12 variable for print label
	String printLabel = "";
	//Changed By Pragyan on 19/09/11.start
	private HashMap  saleOrderWiseMap = new  HashMap();
	private ArrayList saleOrderWiseNotAllowList = new  ArrayList();
	private ArrayList  saleOrderWisePartialAllowList = new  ArrayList();
	private ArrayList  tempItemOrderList = new  ArrayList();
	DistCommon discommon = new DistCommon();	
	private HashMap itemInfoMapForRepl = new HashMap();
	ArrayList replanismentInfoList = new ArrayList();
	double qtyActual=0.0;
	//private Calendar mapWeightVolume;
	//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header.start
	String prevsLocCode = ""; 
	
	int replCnt = 0;
	boolean isReplHdr = false;
	String replOrdCpy = "";
	
	int rplCntDSO = 0;
	boolean isReplHdrDSO = false;
	String replOrdDSOCpy = "";
	
	int rplCntPND = 0;
	boolean isReplHdrPND = false;
	String replPNDCpy = "";
	
	int rplCntPSO = 0;
	boolean isReplHdrPSO = false;
	String replOrdPSOCpy = "";
	
	int rplCntRSV = 0;
	boolean isReplHdrRSV = false;
	String replOrdRSVCpy = "";
	
	//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header.end
	
	public String process() throws RemoteException,ITMException
	{
		return "";
	}
	
	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String rtrStr = "";
		Document headerDom = null;
		Document detailDom = null;
		System.out.println("getData(xmlString,xmlString2,windowName,xtraParams CALLED..."+ xmlString);
		try
		{
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				System.out.println("XML String :"+xmlString);
				headerDom = genericUtility.parseString(xmlString); 				
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				System.out.println("XML String :"+xmlString2);
				detailDom = genericUtility.parseString(xmlString2); 				
			}
			rtrStr = getData(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println("Exception :StockAllocationPrcEJB :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			rtrStr = e.getMessage();
		}
		return rtrStr; 
	}

	public String getData(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
  
		String errCode = "";
		String errString = "";
		String getDataSql= "" ;
		String sql= "" ;
		String resultString = "";
		
		Connection conn = null;
		ResultSet rs = null;
		ResultSet rs1 = null;
		PreparedStatement pstmt = null;
		Statement st = null;
		StringBuffer retTabSepStrBuff = new StringBuffer();
		double pendQty = 0;
		double allocQty = 0;	
		boolean bappend = false ;	
		HashMap tempMap = null;
		//Changed by Rohan on 29-12-11 as said by gulzar.start
		String sSQL  = "";
		String sSingleLotSql = "";
		String resrvLoc  = "";
		String casePickLoc  = "";
		String activePickLoc  = "";
		String deepStoreLoc = "";
		String partialResrvLoc = "";
		String packInstr ="";
		PreparedStatement pstmtStock = null;
		//PreparedStatement pstmtStock1 = null;
		//Changed by Rohan on 29-12-11 as said by gulzar.end
		double balStockQtyTemp = 0.0,sordItemQty=0.0,balStk=0.0; // added by Chandni 01-June-2012
		//Changed by sumit sarkar on 22/06/12 start.
		String partQtyValue = "", allocFlag = "";
		double holdQty = 0;
		String orderByStkStr = "";
		//Changed by sumit sarkar on 22/06/12 start.
		//Changed by sumit on 20/08/12 to show wave allow start.
		String masterPackAllow = "";
		String activePickAllow = "";
		String stockToDockAllow = "";
		String parcelPackAllow = "";
		String pickType = "";
		String directPickLoc = "";
		//Changed by sumit on 20/08/12 to show wave allow end.
		//Change by Rohan on 19/07/12 to get transporter Info.start
		HashMap getTranInfo = null;
		String saleOrderTran = "";
		String tranCod = "";
		String docLocation = "";
		String sqlTran = "";
		String tranName = "";
		PreparedStatement pstmtTran = null;
		ResultSet rsTran = null;
		//Changed By Pragyan 17/12/12 to get the standard UOM and order UOM.Start
		String unit,unitStd,mbaseUnit = "";
		String shipType = "";
		double meffQty = 0,convQtyStduom = 0 ,convFact = 0, quantity = 0.0;
		//Changed By Pragyan 17/12/12 to get the standard UOM and order UOM.End
		//Change by Rohan on 19/07/12 to get transporter Info.start
		//Changed by sumit 22/08/12 to retrieve alloc_flag start.
		PreparedStatement pstmt1 = null;
		ResultSet rs2 = null;
		//Changed by sumit 22/08/12 to retrieve alloc_flag end.
        //Changed by Sankara on 23/11/12 fir dispalying get data in propar format
		 retTabSepStrBuff = new StringBuffer( "<?xml version='1.0' encoding='UTF-8'?>\r\n<DocumentRoot>\r\n<description>Datawindow Root</description>\r\n<group0>\r\n" +
		 		                             "<description>Group0 description</description>\r\n<Header0>\r\n<description>Header0 members</description>\r\n");
		 
		try
		{
			ConnDriver connDriver = new ConnDriver();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getDBDateFormat());
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			//retTabSepStrBuff.append("</Header>\r\n" );
			
			/*//Changed by Rohan 29-12-11 to consider only RESERV, CASE PICK AND ACTIVE PICK LOCATIONS
                        //Changed by Rohan 0n 18/01/12 as said by gulzar sir
			//resrvLoc  = discommon.getDisparams("999999","RESERV_LOCATION",conn);
			resrvLoc  = discommon.getDisparams("999999","RESERV_LOCATION",conn);
                        
			casePickLoc  = discommon.getDisparams("999999","CASE_PICK_INVSTAT",conn);
			activePickLoc  = discommon.getDisparams("999999","ACTIVE_PICK_INVSTAT",conn);
			deepStoreLoc = discommon.getDisparams("999999","DEEP_STORE_INVSTAT",conn);
			partialResrvLoc = discommon.getDisparams("999999","PRSRV_INVSTAT",conn);
			
			System.out.println("CASE_PICK_INVSTAT"+casePickLoc+"ACTIVE_PICK_INVSTAT"+activePickLoc+"RESERV_LOCATION"+resrvLoc+"PARTIAL RESERVE LOC["+partialResrvLoc+"]");
			//Changed by Rohan 29-12-11 .end
			 */			
			siteCode = genericUtility.getColumnValue("site_code",headerDom);
			if ( siteCode == null || siteCode.trim().length() == 0 )
			{
				siteCode = "";
				System.out.println("Site Code From is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			} 
			System.out.println("SITE CODE ::"+ siteCode);
			postOrderFg = "N";
			/*
			postOrderFg = genericUtility.getColumnValue("post_order_flag",headerDom);
			if(postOrderFg == null || postOrderFg.trim().length() == 0)
			{
				postOrderFg = "";
				System.out.println("Site Code From is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}
			*/
			System.out.println("postOrderFg ::"+ postOrderFg);
			itemSerFr = genericUtility.getColumnValue("item_ser__from",headerDom);
			if ( itemSerFr == null || itemSerFr.trim().length() == 0 )
			{
				itemSerFr = "";
				System.out.println("Item Series From is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}
			System.out.println("Item Ser FR "+ itemSerFr);
			itemSerTo = genericUtility.getColumnValue("item_ser__to",headerDom);
			if ( itemSerTo == null || itemSerTo.trim().length() == 0 )
			{
				itemSerTo = "";
				System.out.println("Item Series To is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}
			System.out.println("Item Ser To"+itemSerTo);
	    	custCodeFr = genericUtility.getColumnValue("cust_code__from",headerDom);
	    	if ( custCodeFr == null || custCodeFr.trim().length() == 0 )
			{
				custCodeFr = "";
				System.out.println("Cust Code From is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}
			System.out.println("custCodeFr"+ custCodeFr);
			custCodeTo = genericUtility.getColumnValue("cust_code__to",headerDom); 
			if ( custCodeTo == null || custCodeTo.trim().length() == 0 )
			{
				custCodeTo = "";
				System.out.println("Cust Code To is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}  
			System.out.println("custCodeTo"+ custCodeTo);  
			//Added by Chandni 30-May-2012
			custCodeDlvFr = genericUtility.getColumnValue("cust_code__dlv__from",headerDom);
	    	if ( custCodeDlvFr == null || custCodeDlvFr.trim().length() == 0 )
			{
	    		custCodeDlvFr = "";
				System.out.println("Cust Code Dlv From is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}
			System.out.println("custCodeDlvFr"+ custCodeDlvFr);
			custCodeDlvTo = genericUtility.getColumnValue("cust_code__dlv__to",headerDom); 
			if ( custCodeDlvTo == null || custCodeDlvTo.trim().length() == 0 )
			{
				custCodeDlvTo = "";
				System.out.println("Cust Code Dlv To is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}  
			System.out.println("custCodeDlvTo"+ custCodeDlvTo);  
			//Ended by Chandni 30-May-2012
			saleOrderFr = genericUtility.getColumnValue("sale_order__from",headerDom);
            if ( saleOrderFr == null || saleOrderFr.trim().length() == 0 )
			{
				saleOrderFr = "";
				System.out.println("Sale Order From is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}
			
			saleOrderTo = genericUtility.getColumnValue("sale_order__to",headerDom);         
			if ( saleOrderTo == null || saleOrderTo.trim().length() == 0 )
			{
				saleOrderTo = "";
				System.out.println("Sale Order To is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}
         	sDateFr = genericUtility.getColumnValue("due_date__from",headerDom);
         	if ( sDateFr == null || sDateFr.trim().length() == 0 )
			{
				sDateFr = "";
				System.out.println("Date From is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}
			sDateFr = genericUtility.getValidDateString(sDateFr, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
			dateFr = java.sql.Timestamp.valueOf(sDateFr + " 00:00:00");
	
			sDateTo = genericUtility.getColumnValue("due_date__to",headerDom);            
			if ( sDateTo == null || sDateTo.trim().length() == 0 )
			{
				sDateTo = "";
				System.out.println("Date To is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}
			sDateTo = genericUtility.getValidDateString(sDateTo, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
			dateTo = java.sql.Timestamp.valueOf(sDateTo + " 00:00:00");
			
			DefaultQtyFlag = genericUtility.getColumnValue("default_qty_flag",headerDom);
			if(DefaultQtyFlag == null || DefaultQtyFlag.trim().length() == 0)
			{
				DefaultQtyFlag = "";
				System.out.println("Default Qty flag is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}
			
			//Change by sumit sarkar on 09/03/12 getting the value of itemCodeFr and itemCodeTo Start.
			itemCodeFr = genericUtility.getColumnValue("item_code__from",headerDom);         
			if ( itemCodeFr == null || itemCodeFr.trim().length() == 0 )
			{
				itemCodeFr = "";
				System.out.println("Item Code from is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}
			
			itemCodeTo = genericUtility.getColumnValue("item_code__to",headerDom);         
			if ( itemCodeTo == null || itemCodeTo.trim().length() == 0 )
			{
				itemCodeTo = "";
				System.out.println("Item Code to is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}			
			//Change by sumit sarkar on 09/03/12 getting the value of itemCodeFr and itemCodeTo End.
			//Change by sumit sarkar on 09/03/12 getting the value of SINGLE_LOT, MASTER_PACK_ALLOW, ACTIVE_PICK_ALLOW, STOCK_TO_DOCK_ALLOW START.
			globalSingleLot = checkNull(genericUtility.getColumnValue("single_lot",headerDom));
			globalMasterPackAllow = checkNull(genericUtility.getColumnValue("master_pack_allow",headerDom));
			globalActivePickAllow = checkNull(genericUtility.getColumnValue("active_pick_allow",headerDom));
			globalStockToDockAllow = checkNull(genericUtility.getColumnValue("stock_to_dock_allow",headerDom));
			//Change by sumit sarkar on 09/03/12 getting the value of SINGLE_LOT, MASTER_PACK_ALLOW, ACTIVE_PICK_ALLOW, STOCK_TO_DOCK_ALLOW END.
			//Changed by sumit on 20/12/12 getting parcelpacking_allow 
			globalParcelPackAllow = checkNull(genericUtility.getColumnValue("parcelpack_allow",headerDom));
			shipType = genericUtility.getColumnValue("ship_type",headerDom);
			directPickLoc = genericUtility.getColumnValue("direct_pick_loc",headerDom);
			//Changed by sumit on 03/10/12 getting value of printer start
			/*printer = "";
			printer = checkNull(genericUtility.getColumnValue("printer",headerDom));*/
			//Changed by sumit on 03/10/12 getting value of printer start
			printer = "";
			printer = checkNull(genericUtility.getColumnValue("printer_name",headerDom));
			//Changed by sumit on 03/10/12 getting value of printer end
			
			//Changed by sumit on 24/11/12 getting print label value
			printLabel = genericUtility.getColumnValue("print_label",headerDom);
			
			//Changed by sumit on 03/10/12 getting value of printer end
			
			//Changed by Sumit sarkar on 07/03/12 search on the basis of item_code too.
			/*getDataSql = "SELECT SORDER.CUST_CODE, CUSTOMER.CUST_NAME,SORDDET.LINE_NO, "
				       +"SORDER.SALE_ORDER,SORDER.DUE_DATE,SORDITEM.ITEM_CODE,"
					   +"ITEM.DESCR,SORDITEM.QUANTITY,"
					   +"SORDITEM.QUANTITY - SORDITEM.QTY_DESP - SORDITEM.QTY_ALLOC PENDING_QUANTITY,"
					   +"SORDITEM.QTY_ALLOC,SORDDET.PACK_INSTR,"
					   +"SORDER.SITE_CODE,SORDITEM.EXP_LEV "
					   +"FROM SORDDET,SORDER,SORDITEM,CUSTOMER,ITEM  "
					   +"WHERE ( SORDER.SALE_ORDER = SORDDET.SALE_ORDER ) AND "
					   +"( SORDITEM.SALE_ORDER = SORDER.SALE_ORDER ) AND "
					   +"( SORDDET.LINE_NO = SORDITEM.LINE_NO ) AND "
					   +"( SORDITEM.ITEM_CODE = ITEM.ITEM_CODE ) AND "
					   +"( SORDER.CUST_CODE = CUSTOMER.CUST_CODE ) AND  "
					   +"( SORDDET.SITE_CODE = SORDITEM.SITE_CODE ) AND  "
					   +" SORDER.SITE_CODE = ? AND "
					   +" ITEM.ITEM_SER >=? AND "
					   +" ITEM.ITEM_SER <=? AND "  
					   +" CUSTOMER.CUST_CODE >=? AND "
					   +" CUSTOMER.CUST_CODE <=? AND "  
					   +" SORDER.SALE_ORDER >= ? AND "
					   +" SORDER.SALE_ORDER <= ? AND " 
					   +" SORDER.DUE_DATE >=  ?  AND" 
					   +" SORDER.DUE_DATE <= ? " 
					   +"AND CASE WHEN SORDDET.STATUS IS NULL THEN 'P' ELSE SORDDET.STATUS end <> 'C' "
					   +"AND CASE WHEN SORDER.STATUS IS NULL THEN 'P' ELSE SORDER.STATUS end = 'P' " 
					   +"AND SORDITEM.QUANTITY - SORDITEM.QTY_DESP - SORDITEM.QTY_ALLOC > 0 "
					   +"AND SORDITEM.LINE_TYPE = 'I'"
					   +"ORDER BY SORDER.CUST_CODE,SORDER.SALE_ORDER,SORDITEM.ITEM_CODE__ORD"; */
			/*
			//Changed by Chandni on 30/May/12 for cust_cod__dlv__from and cust_cod__dlv__from
			getDataSql = "SELECT SORDER.CUST_CODE, CUSTOMER.CUST_NAME,SORDDET.LINE_NO, "
		       +"SORDER.SALE_ORDER,SORDER.DUE_DATE,SORDITEM.ITEM_CODE,"
			   +"ITEM.DESCR,SORDITEM.QUANTITY,"
			   +"(SORDITEM.QUANTITY - SORDITEM.QTY_DESP - SORDITEM.QTY_ALLOC) PENDING_QUANTITY,"
			   +"SORDITEM.QTY_ALLOC,SORDDET.PACK_INSTR,"
			   +"SORDER.SITE_CODE,SORDITEM.EXP_LEV, "
			   +"SORDER.PART_QTY AS PART_QTY, CUSTOMER.SINGLE_LOT AS SINGLE_LOT "//Gulzar 5/13/2012
			   +"FROM SORDDET,SORDER,SORDITEM,CUSTOMER,ITEM  "
			   +"WHERE ( SORDER.SALE_ORDER = SORDDET.SALE_ORDER ) AND "
			   +"( SORDITEM.SALE_ORDER = SORDER.SALE_ORDER ) AND "
			   +"( SORDDET.LINE_NO = SORDITEM.LINE_NO ) AND "
			   +"( SORDITEM.ITEM_CODE = ITEM.ITEM_CODE ) AND "
			   +"( SORDER.CUST_CODE = CUSTOMER.CUST_CODE ) AND  "
			   +"( SORDDET.SITE_CODE = SORDITEM.SITE_CODE ) AND  "
			   +" SORDER.SITE_CODE = ? AND "
			   +" ITEM.ITEM_SER >=? AND "
			   +" ITEM.ITEM_SER <=? AND "  
			   +" ITEM.ITEM_CODE >=? AND "
			   +" ITEM.ITEM_CODE <=? AND "
			   +" CUSTOMER.CUST_CODE >=? AND "
			   +" CUSTOMER.CUST_CODE <=? AND "  
			   +" SORDER.SALE_ORDER >= ? AND "
			   +" SORDER.SALE_ORDER <= ? AND " 
			   +" SORDER.DUE_DATE >=  ?  AND" 
			   +" SORDER.DUE_DATE <= ? " 
			   +"AND CASE WHEN SORDDET.STATUS IS NULL THEN 'P' ELSE SORDDET.STATUS end <> 'C' "
			   +"AND CASE WHEN SORDER.STATUS IS NULL THEN 'P' ELSE SORDER.STATUS end = 'P' " 
			   +"AND SORDITEM.QUANTITY - SORDITEM.QTY_DESP - SORDITEM.QTY_ALLOC > 0 "
			   +"AND SORDITEM.LINE_TYPE = 'I'"
			   +"ORDER BY SORDER.CUST_CODE,SORDER.SALE_ORDER,SORDITEM.ITEM_CODE__ORD"; 
			   */
			
			
			getDataSql =" SELECT SORDER.CUST_CODE, CUSTOMER.CUST_NAME,SORDDET.LINE_NO, "
			       +"SORDER.SALE_ORDER,SORDER.DUE_DATE,SORDITEM.ITEM_CODE,"
				   +"ITEM.DESCR,SORDITEM.QUANTITY,"
				   +"(SORDITEM.QUANTITY - SORDITEM.QTY_DESP - SORDITEM.QTY_ALLOC) PENDING_QUANTITY,"
				   +"SORDITEM.QTY_ALLOC,SORDDET.PACK_INSTR,"
				   +"SORDER.SITE_CODE,SORDITEM.EXP_LEV, "
				   +"SORDER.PART_QTY AS PART_QTY, CUSTOMER.SINGLE_LOT AS SINGLE_LOT, SORDITEM.MIN_SHELF_LIFE AS MIN_SHELF_LIFE "//Gulzar 5/13/2012
				   //Chnged by Rohan 0n 22/06/12
				   +",SORDER.ALLOC_FLAG AS ALLOC_FLAG "				   
				   +"FROM SORDDET,SORDER,SORDITEM,CUSTOMER,ITEM  "
				   +"WHERE ( SORDER.SALE_ORDER = SORDDET.SALE_ORDER ) AND "
				   +"( SORDITEM.SALE_ORDER = SORDER.SALE_ORDER ) AND "
				   +"( SORDDET.LINE_NO = SORDITEM.LINE_NO ) AND "
				   +"( SORDITEM.ITEM_CODE = ITEM.ITEM_CODE ) AND "
				   +"( SORDER.CUST_CODE = CUSTOMER.CUST_CODE ) AND  "
				   +"( SORDDET.SITE_CODE = SORDITEM.SITE_CODE ) AND  "
				   +" SORDER.SITE_CODE = ? AND "
				   +" ITEM.ITEM_SER >=? AND "
				   +" ITEM.ITEM_SER <=? AND "  
				   +" ITEM.ITEM_CODE >=? AND "
				   +" ITEM.ITEM_CODE <=? AND "
				   +" CUSTOMER.CUST_CODE >=? AND "
				   +" CUSTOMER.CUST_CODE <=? AND "  
				   +" SORDER.CUST_CODE__DLV >=? AND " 	//Added by Chandni 30-May-2012
				   +" SORDER.CUST_CODE__DLV <=? AND "  	//Added by Chandni 30-May-2012
				   +" SORDER.SALE_ORDER >= ? AND "
				   +" SORDER.SALE_ORDER <= ? AND " 
				   +" SORDER.DUE_DATE >=  ?  AND" 
				   +" SORDER.DUE_DATE <= ? " 
				   +"AND CASE WHEN SORDDET.STATUS IS NULL THEN 'P' ELSE SORDDET.STATUS end <> 'C' "
				   +"AND CASE WHEN SORDER.STATUS IS NULL THEN 'P' ELSE SORDER.STATUS end = 'P' "
				   //Changed by Rohan on 22/06/12
				   //+"AND SORDITEM.QUANTITY - SORDITEM.QTY_DESP - SORDITEM.QTY_ALLOC > 0 "
				   +"AND (SORDITEM.QUANTITY - SORDITEM.QTY_DESP - SORDITEM.QTY_ALLOC > 0 OR SORDER.ALLOC_FLAG='M' )"
				   +"AND SORDITEM.LINE_TYPE = 'I'"
				   //Changed By Rohan on 22/06/12.start
				   +" AND (SORDITEM.SALE_ORDER , SORDITEM.LINE_NO) NOT IN (SELECT SALE_ORDER,LINE_NO__SORD FROM PICK_ORD_DET " 
				   +" WHERE  PICK_ORD_DET.SALE_ORDER =SORDITEM.SALE_ORDER AND  PICK_ORD_DET.LINE_NO__SORD =   SORDITEM.LINE_NO)"
				   +" AND (SORDITEM.SALE_ORDER , SORDITEM.LINE_NO) NOT IN (SELECT SALE_ORDER,LINE_NO__SORD FROM REPL_ORD_DET " 
				   +" WHERE  REPL_ORD_DET.SALE_ORDER = SORDITEM.SALE_ORDER AND  REPL_ORD_DET.LINE_NO__SORD =   SORDITEM.LINE_NO)"
				   //Chnged by Rohan on 22/06/12.end
				   +" ORDER BY SORDER.CUST_CODE,SORDER.SALE_ORDER,SORDITEM.ITEM_CODE__ORD"; 
			
			getDataSql =" SELECT SORDER.CUST_CODE, CUSTOMER.CUST_NAME,SORDDET.LINE_NO, "
			       +"SORDER.SALE_ORDER,SORDER.DUE_DATE,SORDITEM.ITEM_CODE,"
				   +"ITEM.DESCR,SORDITEM.QUANTITY,"
				   +"(SORDITEM.QUANTITY - SORDITEM.QTY_DESP - SORDITEM.QTY_ALLOC) PENDING_QUANTITY,"
				   +"SORDITEM.QTY_ALLOC,SORDDET.PACK_INSTR,"
				   //Changed By Pragyan
				   //Changed By Pragyan sit code ship
				   //+"SORDER.SITE_CODE,SORDITEM.EXP_LEV, "
				   +"SORDER.SITE_CODE__SHIP,SORDITEM.EXP_LEV, "
				   +"SORDER.PART_QTY AS PART_QTY, CUSTOMER.SINGLE_LOT AS SINGLE_LOT, SORDITEM.MIN_SHELF_LIFE AS MIN_SHELF_LIFE "//Gulzar 5/13/2012
				   //Chnged by Rohan 0n 22/06/12
				   //Changed by sumit 20/08/12 getting column data start.
				   //+",SORDER.ALLOC_FLAG AS ALLOC_FLAG "		   
				   //+"FROM SORDDET,SORDER,SORDITEM,CUSTOMER,ITEM "
				   //Changed by sumit on 20/12/12 getting value of parcelpacking_allow
				   //+" ,SORDER.ALLOC_FLAG AS ALLOC_FLAG , WAVE_TYPE.MASTER_PACK_ALLOW , WAVE_TYPE.ACTIVE_PICK_ALLOW , WAVE_TYPE.STOCK_TO_DOCK_ALLOW "		   
				   +" ,SORDER.ALLOC_FLAG AS ALLOC_FLAG , WAVE_TYPE.MASTER_PACK_ALLOW , WAVE_TYPE.ACTIVE_PICK_ALLOW , WAVE_TYPE.STOCK_TO_DOCK_ALLOW, WAVE_TYPE.PARCELPACK_ALLOW  "
				   //Changed by sumit on 31/01/13 adding column 
				   +" ,ITEM.UNIT AS UNIT_STD ,SORDDET.UNIT ORDER_UNIT,SORDDET.UNIT__STD AS  UNIT__STD, SORDDET.CONV__QTY_STDUOM "
				   +"FROM SORDDET,SORDER,SORDITEM,CUSTOMER,ITEM , WAVE_TYPE "
				   //Changed by sumit 20/08/12 getting column data end.
				   +"WHERE ( SORDER.SALE_ORDER = SORDDET.SALE_ORDER ) AND "
				   +"( SORDITEM.SALE_ORDER = SORDER.SALE_ORDER ) AND "
				   +"( SORDDET.LINE_NO = SORDITEM.LINE_NO ) AND "
				   +"( SORDITEM.ITEM_CODE = ITEM.ITEM_CODE ) AND "
				   +"( SORDER.CUST_CODE = CUSTOMER.CUST_CODE ) AND  "
				   +"( SORDDET.SITE_CODE = SORDITEM.SITE_CODE ) AND  "
				   //Changed by sumit on 20/08/12 join customer with wave_type
				   +"( CUSTOMER.WAVE_TYPE = WAVE_TYPE.WAVE_TYPE(+)) AND "
				   //Changed By Rohan 
				   //+" SORDER.SITE_CODE = ? AND "
				   +" SORDER.SITE_CODE__SHIP = ? AND "
				   +" ITEM.ITEM_SER >=? AND "
				   +" ITEM.ITEM_SER <=? AND "  
				   +" ITEM.ITEM_CODE >=? AND "
				   +" ITEM.ITEM_CODE <=? AND "
				   +" CUSTOMER.CUST_CODE >=? AND "
				   +" CUSTOMER.CUST_CODE <=? AND "  
				   +" SORDER.CUST_CODE__DLV >=? AND " 	//Added by Chandni 30-May-2012
				   +" SORDER.CUST_CODE__DLV <=? AND "  	//Added by Chandni 30-May-2012
				   +" SORDER.SALE_ORDER >= ? AND "
				   +" SORDER.SALE_ORDER <= ? AND " 
				   +" SORDER.DUE_DATE >=  ?  AND" 
				   +" SORDER.DUE_DATE <= ? " 
				   +"AND CASE WHEN SORDDET.STATUS IS NULL THEN 'P' ELSE SORDDET.STATUS end <> 'C' "
				   +"AND CASE WHEN SORDER.STATUS IS NULL THEN 'P' ELSE SORDER.STATUS end = 'P' "
				   //Changed by sumit on 12/09/12 considering hold_flag from sorddet 
				   +" AND CASE WHEN SORDDET.HOLD_FLAG IS NULL THEN 'N' ELSE SORDDET.HOLD_FLAG end <> 'Y'"
				   //Chnaged by Rohan on 11/07/12 revert Changes of Manual Stock Allocation
				   //Changed by Rohan on 22/06/12
				   //+"AND SORDITEM.QUANTITY - SORDITEM.QTY_DESP - SORDITEM.QTY_ALLOC > 0 "
				   //+"AND (SORDITEM.QUANTITY - SORDITEM.QTY_DESP - SORDITEM.QTY_ALLOC > 0 OR SORDER.ALLOC_FLAG='M' )"
				   //Changed by sumit on 13/08/12 as per manual stock allocation start.
				 //+"AND SORDITEM.QUANTITY - SORDITEM.QTY_DESP - SORDITEM.QTY_ALLOC > 0 "
				   +" AND ((SORDITEM.QUANTITY - SORDITEM.QTY_DESP - SORDITEM.QTY_ALLOC > 0 ) "  
				   +" OR (FN_CHECK_MANUAL_STOCK_ALLOC(SORDER.SALE_ORDER, SORDDET.LINE_NO) = 0 ) )"				   
				   //Changed by sumit on 13/08/12 as per manual stock allocation end.
				   
				   
				   +"AND SORDITEM.LINE_TYPE = 'I'"
				  
				   //Changed by Rohan on 11/07/12 revert Changes of Manual Stock Allocation.start
				   /*
				   //Changed By Rohan on 22/06/12.start
				   +" AND (SORDITEM.SALE_ORDER , SORDITEM.LINE_NO) NOT IN (SELECT SALE_ORDER,LINE_NO__SORD FROM PICK_ORD_DET " 
				   +" WHERE  PICK_ORD_DET.SALE_ORDER =SORDITEM.SALE_ORDER AND  PICK_ORD_DET.LINE_NO__SORD =   SORDITEM.LINE_NO)"
				   +" AND (SORDITEM.SALE_ORDER , SORDITEM.LINE_NO) NOT IN (SELECT SALE_ORDER,LINE_NO__SORD FROM REPL_ORD_DET " 
				   +" WHERE  REPL_ORD_DET.SALE_ORDER = SORDITEM.SALE_ORDER AND  REPL_ORD_DET.LINE_NO__SORD =   SORDITEM.LINE_NO)"
				   //Chnged by Rohan on 22/06/12.end
				   */
				 //Changed by Rohan on 11/07/12 revert Changes of Manual Stock Allocation.end
				   +" ORDER BY SORDER.CUST_CODE,SORDER.SALE_ORDER,SORDITEM.ITEM_CODE__ORD"; 
			
			
				//Changed by Rohan 29-12-11 to consider only RESERV, CASE PICK AND ACTIVE PICK LOCATIONS
	            //Changed by Rohan 0n 18/01/12 as said by gulzar sir
				//resrvLoc  = discommon.getDisparams("999999","RESERV_LOCATION",conn);
				resrvLoc  = discommon.getDisparams("999999","RESERV_LOCATION",conn);
	            
				casePickLoc  = discommon.getDisparams("999999","CASE_PICK_INVSTAT",conn);
				activePickLoc  = discommon.getDisparams("999999","ACTIVE_PICK_INVSTAT",conn);
				deepStoreLoc = discommon.getDisparams("999999","DEEP_STORE_INVSTAT",conn);
				partialResrvLoc = discommon.getDisparams("999999","PRSRV_INVSTAT",conn);
	
				System.out.println("CASE_PICK_INVSTAT"+casePickLoc+"ACTIVE_PICK_INVSTAT"+activePickLoc+"RESERV_LOCATION"+resrvLoc+"PARTIAL RESERVE LOC["+partialResrvLoc+"]shipmentType["+shipType+"]");
				//Changed by Rohan 29-12-11 .end

			
			pstmt = conn.prepareStatement(getDataSql);
			
			pstmt.setString(1,siteCode);
			pstmt.setString(2,itemSerFr);
			pstmt.setString(3,itemSerTo);
			//Changed by sumit sarkar on 07/03/12 start.
			pstmt.setString(4,itemCodeFr);
			pstmt.setString(5,itemCodeTo);
			//Changed by sumit sarkar on 07/03/12 end.
			pstmt.setString(6,custCodeFr);
			pstmt.setString(7,custCodeTo);
			pstmt.setString(8,custCodeDlvFr); 	//Added by Chandni 30-May-2012
			pstmt.setString(9,custCodeDlvTo); 	//Added by Chandni 30-May-2012
			pstmt.setString(10,saleOrderFr);
			pstmt.setString(11,saleOrderTo);
			pstmt.setTimestamp(12,dateFr);
			pstmt.setTimestamp(13,dateTo);
			st = conn.createStatement();
			rs = pstmt.executeQuery();
			
			//Changed by sumit sarkar on 22/06/12 
			//sSQL =	"SELECT SUM(STOCK.QUANTITY - STOCK.ALLOC_QTY ) " 
			sSQL =	"SELECT SUM(STOCK.QUANTITY - STOCK.ALLOC_QTY - (CASE WHEN STOCK.HOLD_QTY IS NULL THEN 0 ELSE STOCK.HOLD_QTY END ) ), SUM(STOCK.HOLD_QTY )  "
					+"FROM STOCK,ITEM,LOCATION,INVSTAT " 
     				+"WHERE (ITEM.ITEM_CODE = STOCK.ITEM_CODE) "
     				+"AND (LOCATION.LOC_CODE = STOCK.LOC_CODE ) "
     				+"AND (LOCATION.INV_STAT = INVSTAT.INV_STAT) "
     				+"AND INVSTAT.AVAILABLE = ? "
     				+"AND STOCK.ITEM_CODE = ? "
     				+"AND STOCK.SITE_CODE = ? " 
     				+"AND (STOCK.QUANTITY - STOCK.ALLOC_QTY - CASE WHEN STOCK.HOLD_QTY IS NULL THEN 0 ELSE STOCK.HOLD_QTY END) > 0  "
     				+"AND (MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE) > ? ) ";
			   		//+"AND LOCATION.INV_STAT IN(?,?,?) "//Changed by Rohan on 29-12-11 to consider only RESERV, CASE PICK AND ACTIVE PICK LOCATIONS
     				//+"AND LOCATION.INV_STAT IN(?,?,?,?) ";//Changed by Pragyan on To add deep storage invstat
			   		//+"ORDER BY EXP_DATE, CREA_DATE";//Gulzar on 12/28/2011
     				//+"ORDER BY STOCK.EXP_DATE, STOCK.LOC_CODE";//Pragyan on 14/08/2012
			
			 sSingleLotSql = "SELECT SUM(STOCK.QUANTITY - STOCK.ALLOC_QTY - (CASE WHEN STOCK.HOLD_QTY IS NULL THEN 0 ELSE STOCK.HOLD_QTY END ) ), "
			 				+"SUM(STOCK.HOLD_QTY ) " 
			 				+"FROM STOCK,ITEM,LOCATION,INVSTAT " 
			 				+"WHERE (ITEM.ITEM_CODE = STOCK.ITEM_CODE) " 
			 				+"AND (LOCATION.LOC_CODE = STOCK.LOC_CODE ) " 
			 				+"AND (LOCATION.INV_STAT = INVSTAT.INV_STAT) " 
			 				+"AND INVSTAT.AVAILABLE = ? " 
			 				+"AND STOCK.ITEM_CODE = ? " 
			 				+"AND STOCK.SITE_CODE = ? "  
			 				+"AND STOCK.LOT_NO IN (SELECT LOT_NO FROM STOCK WHERE ITEM_CODE =? AND SITE_CODE =? "
			 				+"GROUP BY LOT_NO HAVING SUM(QUANTITY - ALLOC_QTY - (CASE WHEN STOCK.HOLD_QTY IS NULL THEN 0 ELSE STOCK.HOLD_QTY END) ) >= ?) "
			 				+"AND (MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE) > ? ) ";
			 				//+"AND LOCATION.INV_STAT IN(?,?,?,?) ";
			 				//+"ORDER BY STOCK.EXP_DATE, STOCK.LOC_CODE ";
					
					
			//pstmtStock = conn.prepareStatement(sSQL);
			
			//Changed by Rohan on 19/07/12 for Showing Trasporter Detail
			sqlTran = "SELECT TRAN_NAME FROM TRANSPORTER WHERE TRAN_CODE = ?";
			
			//Changed by Gulzar on 5/13/2012
			int count = 0;
			String partQty = "";
			String singleLot = "";
			String itemCode = "";
			String siteCode = "";
			int minSelfLife = 0;
			ResultSet rsStock = null;

			/*String stkSql = "SELECT COUNT(*) AS COUNT, LOT_NO FROM STOCK WHERE ITEM_CODE = ? AND SITE_CODE = ? "+
							"GROUP BY LOT_NO HAVING SUM(QUANTITY - ALLOC_QTY - (CASE WHEN HOLD_QTY IS NULL THEN 0 ELSE STOCK.HOLD_QTY END) ) >= ? ";
			pstmtStock1 = conn.prepareStatement(stkSql);*/
			double pendingQty = 0d;
			//End changes by gulzar on 5/13/2012
			boolean isActives = false;
			/*retTabSepStrBuff.append( "<?xml version='1.0' encoding='UTF-8'?><DocumentRoot><description>Datawindow Root</description><group0>" +
    		"<description>Groupscription</description><Header0><description>Header0 members</description>\r\n" );*/
			if(rs.next())
			{
				do
				{
					minSelfLife = 0;
					orderByStkStr = "";
					tranName = "";
					isActives = false;
					pendingQty = rs.getDouble("PENDING_QUANTITY");
					itemCode = checkNull(rs.getString(6));
					siteCode = checkNull(rs.getString(12));
					partQty = checkNull(rs.getString("PART_QTY"));
					singleLot = checkNull(rs.getString("SINGLE_LOT"));
					minSelfLife = rs.getInt("MIN_SHELF_LIFE");
					//Changed by sumit on 20/08/12 getting value of masterPackAllow, activePickAllow and activePickAllow start.
					masterPackAllow = checkNull(rs.getString("MASTER_PACK_ALLOW"));
					activePickAllow =checkNull( rs.getString("ACTIVE_PICK_ALLOW"));
					stockToDockAllow = checkNull(rs.getString("STOCK_TO_DOCK_ALLOW"));
					parcelPackAllow = checkNull(rs.getString("PARCELPACK_ALLOW"));
					System.out.println("masterPackAllow ["+masterPackAllow+"] activePickAllow ["+activePickAllow+"] stockToDockAllow ["+stockToDockAllow+"]parcelPackAllow ["+parcelPackAllow+"]");
					//Changed by sumit on 20/08/12 getting value of masterPackAllow, activePickAllow and activePickAllow start.
					//Changed By Pragyan 17/12/12 to get the standard UOM and order UOM.start
					//+" ,ITEM.UNIT AS UNIT_STD ,SORDDET.UNIT ORDER_UNIT,SORDDET.UNIT__STD AS  UNIT__STD, SORDDET.CONV__QTY_STDUOM"
					mbaseUnit = checkNull(rs.getString("UNIT_STD"));
					unit =  checkNull(rs.getString("ORDER_UNIT"));
					unitStd = checkNull(rs.getString("UNIT__STD"));
					convQtyStduom = rs.getDouble("CONV__QTY_STDUOM");
					System.out.println(" first mbaseUnit ["+mbaseUnit+"] unit ["+unit+"] unitStd ["+unitStd+"] convQtyStduom ["+convQtyStduom+"]");
					
					if(unitStd != "")
					{
						mbaseUnit = unitStd;
					}
					
					quantity = rs.getDouble(8);
					if(!unit.equalsIgnoreCase(mbaseUnit))
					{
						if(convQtyStduom != 0)
						{
							convFact = convQtyStduom;
						}	
						//converting for pending quantity
						ArrayList convQtyList = discommon.getConvQuantityFact(unit, mbaseUnit, itemCode, pendingQty, convFact,conn);
						System.out.println("convQtyList = "+convQtyList);
						meffQty = Double.parseDouble(convQtyList.get(1).toString());
						System.out.println("meffQty ["+meffQty+"]");		
						if(meffQty == -999999999)
						{
							meffQty = 0;								
						}
						if (convQtyStduom == 0)
						{
							convQtyStduom= Double.parseDouble(convQtyList.get(0).toString());
						}
						pendingQty = meffQty;
						
						//converting for quantity
						convQtyList = new ArrayList();
						convQtyList = discommon.getConvQuantityFact(unit, mbaseUnit, itemCode, quantity, convFact,conn);						
						quantity = Double.parseDouble(convQtyList.get(1).toString());
						System.out.println("quantity ["+quantity+"]");
		
						if(quantity == -999999999)
						{
							quantity = 0;								
						}						
					}
					//Changed By Pragyan 17/12/12 to get the standard UOM and order UOM.end
					System.out.println("pendingQty =["+pendingQty+"]");
					System.out.println("partQty =["+partQty+"]");
					System.out.println("singleLot =["+singleLot+"]");
					System.out.println("MIN_SHELF_LIFE =["+minSelfLife+"]");
					HashMap itemVolMap = getItemVoumeMap(itemCode, "", conn);
					double packSize = (Double)itemVolMap.get("PACK_SIZE");
					double itemWeight = (Double)itemVolMap.get("ITEM_WEIGHT");
					System.out.println("itemWeight =["+itemWeight+"]");
					double noArt = pendingQty/packSize;
					//Change by Rohan Bhogale on 19/07/12 To display transporte details.start
					getTranInfo = new HashMap();
					saleOrderTran = rs.getString("SALE_ORDER");
					//Changed By Pragyan 26-02-13 To use the new method and pass pick type and shipmentt type in the method.
					//getTranInfo = getTransportInfo(saleOrderTran,itemWeight * pendingQty, conn);
					//getTranInfo = getTransportInfo(saleOrderTran,itemWeight * pendingQty,noArt, conn);
					
					//Changed By Pragyan 27/02/13 To check changed values
					//if("Y".equalsIgnoreCase(globalMasterPackAllow) && "Y".equalsIgnoreCase(masterPackAllow))
					if("Y".equalsIgnoreCase(globalMasterPackAllow))
					{
						pickType = "M";
					}
					//else if("Y".equalsIgnoreCase(globalParcelPackAllow) && "Y".equalsIgnoreCase(parcelPackAllow))
					else if("Y".equalsIgnoreCase(globalParcelPackAllow))
					{
						pickType = "P";
					}
										
					getTranInfo = getTransporterInfoMap(saleOrderTran, itemWeight * pendingQty, noArt, pickType, shipType, conn);
					
					tranCod = (String)getTranInfo.get("TRAN_CODE");
					docLocation = getDocLoc(tranCod, conn);
					
					pstmtTran = conn.prepareStatement(sqlTran);	
					pstmtTran.setString(1,tranCod);
					rsTran = pstmtTran.executeQuery();
					if(rsTran.next())
					{
						tranName = rsTran.getString("TRAN_NAME");
					}
					
					if(pstmtTran != null)
					{
						pstmtTran.close();
						pstmtTran = null;
					}
					if(rsTran != null)
					{
						rsTran.close();
						rsTran = null;
					}
					
					/*HashMap itemVolMap = getItemVoumeMap(itemCode, "", conn);
					double packSize = (Double)itemVolMap.get("PACK_SIZE");*/
					
					
					//if(globalSingleLot != null && !globalSingleLot.equalsIgnoreCase(singleLot))
					if(globalSingleLot != null && !globalSingleLot.equalsIgnoreCase(singleLot) && globalSingleLot.length() > 0)
					{
						singleLot = globalSingleLot;
					}
					
					
					//Changed By Pragyan 17/01/13 To get all data for stock.start
					/*if((pendingQty % packSize) > 0)
					{
						isActives = true;
						orderByStkStr = "AND LOCATION.INV_STAT IN(?,?,?,?,?) ORDER BY STOCK.EXP_DATE,LOCATION.INV_STAT, STOCK.LOC_CODE ";
					}
					else
					{
						isActives = false;
						orderByStkStr = "AND LOCATION.INV_STAT IN(?,?,?,?) ORDER BY STOCK.EXP_DATE, STOCK.LOC_CODE ";
					}*/
					//if(directPickLoc.length() > 0)
					if(directPickLoc != null && directPickLoc.length() > 0)
					{
						orderByStkStr = "AND LOCATION.LOC_CODE IN(?) ORDER BY STOCK.EXP_DATE,LOCATION.INV_STAT, STOCK.LOC_CODE ";
					}
					else
					{
						orderByStkStr = "AND LOCATION.INV_STAT IN(?,?,?,?,?) ORDER BY STOCK.EXP_DATE,LOCATION.INV_STAT, STOCK.LOC_CODE ";
					}
					//Changed By Pragyan 17/01/13 To get all data for stock.end
					//Change by Rohan Bhogale on 19/07/12 To display transporte details.end

					//Setting of parameters
					/*pstmtStock1.setString(1,itemCode);
					pstmtStock1.setString(2,siteCode);
					pstmtStock1.setDouble(3,pendingQty);

					rsStock = pstmtStock1.executeQuery();
					if ( rsStock.next() )
					{
						count = rsStock.getInt("COUNT");
					}
					if ( singleLot.trim().length() > 0 && singleLot.trim().equalsIgnoreCase("Y") && (count <= 0) )
					{
						continue;
					}*/
					//Changed by sumit sarkar on 22/06/12 on the basis of part quntity it display condition STRAT.
					/*if ( partQty.trim().length() > 0 && partQty.trim().equalsIgnoreCase("Y") )
					{
					}*/
					
					
					
					if ( partQty.trim().length() > 0 )
					{
						System.out.println("in side if");
						//Changed 16/01/13 as the Sales Order Value changes 
						//if( "0".equalsIgnoreCase(partQty))
						if( "2".equalsIgnoreCase(partQty))
						{
							partQtyValue = "Ship Available";
						}
						//Changed 16/01/13 as the Sales Order Value changes 
						//else if ("1".equalsIgnoreCase(partQty))
						else if ("0".equalsIgnoreCase(partQty))
						{
							partQtyValue = "Ship Complete";
						}
						//Changed 16/01/13 as the Sales Order Value changes 
						else if("1".equalsIgnoreCase(partQty))
						//else if("2".equalsIgnoreCase(partQty))
						{
							partQtyValue = "Ship Complete Lines";
						}
						
						System.out.println("partQtyValue is --> ["+partQtyValue+"]");
					}
					//Changed by sumit sarkar on 22/06/12 on the basis of part quntity it display condition END.

					//End changes by Gulzar on 5/13/2012
					if(itemCodeMap.containsKey(rs.getString(6)))
					{						
						balStockQty = Double.parseDouble(itemCodeMap.get(rs.getString(6)).toString());
						bappend = false ;
					}
					else
					{
						/*sql ="SELECT SUM(STOCK.QUANTITY - STOCK.ALLOC_QTY ) " 
		  					+"FROM STOCK,ITEM,LOCATION,INVSTAT " 
		     				+"WHERE (ITEM.ITEM_CODE = STOCK.ITEM_CODE) "
		     				+"AND (LOCATION.LOC_CODE = STOCK.LOC_CODE ) "
		     				+"AND (LOCATION.INV_STAT = INVSTAT.INV_STAT) "
		     				+"AND INVSTAT.AVAILABLE = 'Y' "
		     				+"AND STOCK.ITEM_CODE = '"+ rs.getString(6) + "'"
		     				+"AND STOCK.SITE_CODE = '"+ rs.getString(12) +"'" 
		     				+"AND (STOCK.QUANTITY - STOCK.ALLOC_QTY) > 0  ";
		     			*/
						//Changed by Rohan on 29-12-11 as said by gulzar sir.start
						
						/*pstmtStock.setString(1,"Y");
						pstmtStock.setString(2,rs.getString(6));
						pstmtStock.setString(3,rs.getString(12));
						pstmtStock.setInt(4,minSelfLife);//Gulzar on 5/18/2012
						pstmtStock.setString(5,resrvLoc);
						pstmtStock.setString(6,casePickLoc);
						pstmtStock.setString(7,activePickLoc);
						pstmtStock.setString(8,deepStoreLoc);
						//Changed by Rohan on 29-12-11 as said by gulzar sir.end
						 */
						if(directPickLoc != null && directPickLoc.length() > 0)
						{
							pstmtStock = conn.prepareStatement(sSQL + orderByStkStr);
							pstmtStock.setString(1,"Y");
							pstmtStock.setString(2,rs.getString(6));
							pstmtStock.setString(3,rs.getString(12));
							pstmtStock.setInt(4,minSelfLife);
							pstmtStock.setString(5,directPickLoc);
						}
						else if ( singleLot.trim().length() > 0 && singleLot.trim().equalsIgnoreCase("Y") )
						{
							//sSingleLotSql = sSingleLotSql + orderByStkStr;
							pstmtStock = conn.prepareStatement(sSingleLotSql + orderByStkStr);
							pstmtStock.setString(1,"Y");
							pstmtStock.setString(2,itemCode);
							pstmtStock.setString(3,siteCode);
							pstmtStock.setString(4,itemCode);
							pstmtStock.setString(5,siteCode);
							pstmtStock.setDouble(6,pendingQty);
							pstmtStock.setInt(7,minSelfLife);
							pstmtStock.setString(8,resrvLoc);
							pstmtStock.setString(9,casePickLoc);
							pstmtStock.setString(10,activePickLoc);
							pstmtStock.setString(11,deepStoreLoc);
							pstmtStock.setString(12,partialResrvLoc);
							/*if(isActives)
							{
								pstmtStock.setString(12,partialResrvLoc);
							}*/
						}
						else
						{
							//sSQL = sSQL + orderByStkStr;
							pstmtStock = conn.prepareStatement(sSQL + orderByStkStr);
							pstmtStock.setString(1,"Y");
							pstmtStock.setString(2,rs.getString(6));
							pstmtStock.setString(3,rs.getString(12));
							pstmtStock.setInt(4,minSelfLife);//Gulzar on 5/18/2012
							pstmtStock.setString(5,resrvLoc);
							pstmtStock.setString(6,casePickLoc);
							pstmtStock.setString(7,activePickLoc);
							pstmtStock.setString(8,deepStoreLoc);
							pstmtStock.setString(9,partialResrvLoc);
							/*if(isActives)
							{
								pstmtStock.setString(9,partialResrvLoc);
							}*/
							//Changed by Rohan on 29-12-11 as said by gulzar sir.end
						}
						rs1 = pstmtStock.executeQuery();
						
						if (rs1.next())
						{
							bappend = true;
							balStockQty = rs1.getDouble(1);
							//CHanged by sumit sarkar getting hold quantity
							holdQty = rs1.getDouble(2);
							//Changed by sumit sarkar comment this for displaying zero item quantity 
							/*if (balStockQty > 0)
							{
								itemCodeMap.put(rs.getString(6),new Double(rs1.getDouble(1)));
							}*/							
							itemCodeMap.put(rs.getString(6),new Double(rs1.getDouble(1)));
							
							System.out.println("Bal stk qty for item ....." + rs.getString(6) + " is " + balStockQty);
						}
						if(rs1 != null)
						{
							rs1.close();
						}
						pstmtStock.clearParameters();
					}

					double itemStkQty = 0d;
					
					//if (balStockQty > 0)					
					if(itemCodeMap.containsKey(rs.getString(6)))
					{
						itemStkQty = (Double)itemCodeMap.get(rs.getString(6));
						System.out.println("balStockQty =["+itemStkQty+"]");				
						//  Changed by sankara on 23/11/12 append data in  porpar format 
						retTabSepStrBuff.append( "<Detail2>\r\n" );
						//Changed by Gulzar on 5/13/2012
						//Changed by sumit sarkar on 22/06/12 comment this( now also displaying 0 stock quantity. start.
						/*if ( partQty.trim().length() > 0 && partQty.trim().equalsIgnoreCase("N") && balStockQty < pendingQty )
						{
							itemCodeMap.remove(rs.getString(6));
							continue;
						}*/
						//Changed by sumit sarkar on 22/06/12 comment this( now also displaying 0 stock quantity. end.
						//End changed by Gulzar on 5/13/2012
						//CUST_CODE
						//Changed by sankara on 23/11/12 append cust_code in porpar format 
						//retTabSepStrBuff.append(rs.getString(1)).append("\t");							
						retTabSepStrBuff.append( "<cust_code><![CDATA[" ).append(rs.getString(1)).append( "]]></cust_code>\r\n" );
						//CUST_NAME
						//Changed by sankara on 23/11/12 append cust_name in porpar format 
						//retTabSepStrBuff.append(rs.getString(2)).append("\t");
						retTabSepStrBuff.append( "<cust_name><![CDATA[" ).append(rs.getString(2)).append( "]]></cust_name>\r\n" );
						//LINE_NO
						//Changed by sankara on 23/11/12 append line_no in porpar format 
						//retTabSepStrBuff.append(rs.getString(3)).append("\t");
						retTabSepStrBuff.append( "<line_no><![CDATA[" ).append(rs.getString(3)).append( "]]></line_no>\r\n" );   
						//SALE_ORDER
						//Changed by sankara on 23/11/12 append sale_order in porpar format 
						//retTabSepStrBuff.append(rs.getString(4)).append("\t");
						retTabSepStrBuff.append( "<sale_order><![CDATA[" ).append(rs.getString(4)).append( "]]></sale_order>\r\n" );
						//DUE_DATE
						//Changed by Rohan To display due date in dd\mm\yy format
						//retTabSepStrBuff.append(rs.getTimestamp(5)).append("\t");
						System.out.println("Due Date Format===>>>>>>>>=="+rs.getDate(5));
						//Changed by sankara on 23/11/12 append due_date in porpar format 
						//retTabSepStrBuff.append(rs.getDate(5)).append("\t");
						retTabSepStrBuff.append( "<due_date><![CDATA[" ).append(rs.getDate(5)).append( "]]></due_date>\r\n" );
						dueDate = rs.getTimestamp(5);
						//ITEM_CODE
						//Changed by sankara on 23/11/12 append item_code in porpar format 
						//retTabSepStrBuff.append(rs.getString(6)).append("\t");
						retTabSepStrBuff.append( "<item_code><![CDATA[" ).append(rs.getString(6)).append( "]]></item_code>\r\n" );        
						//DESCR
						//Changed by sankara on 23/11/12 append item_descr in porpar format 
						//retTabSepStrBuff.append(rs.getString(7)).append("\t");
						retTabSepStrBuff.append( "<item_descr><![CDATA[" ).append(rs.getString(7)).append( "]]></item_descr>\r\n" );

					    //Changed by sumit on 20/08/12 to add single lot opt AND WAVE TYPES. start
					    //Changed by sumit on 18/09/12 getting value from header field in case data start

					    /*//SINGLE LOT
						retTabSepStrBuff.append(singleLot).append("\t");

						//MASTER_PACK_ALLOW
						retTabSepStrBuff.append(masterPackAllow).append("\t");

						//ACTIVE_PICK_ALLOW
						retTabSepStrBuff.append(activePickAllow).append("\t");

						//STOCK_TO_DOCK_ALLOW
						retTabSepStrBuff.append(stockToDockAllow).append("\t");*/
					    //Changed by sumit on 18/09/12 
						if (globalSingleLot.trim().length() > 0) 
						{							
							//SINGLE LOT
							//Changed by sankara on 23/11/12 append single_lot in porpar format 
							//retTabSepStrBuff.append(globalSingleLot).append("\t");
							retTabSepStrBuff.append( "<single_lot><![CDATA[" ).append(globalSingleLot).append( "]]></single_lot>\r\n" );

							//MASTER_PACK_ALLOW
							//Changed by sankara on 23/11/12 append master_pack_allow in porpar format 
							//retTabSepStrBuff.append(globalMasterPackAllow).append("\t");
							retTabSepStrBuff.append( "<master_pack_allow><![CDATA[" ).append(globalMasterPackAllow).append( "]]></master_pack_allow>\r\n" );

							//ACTIVE_PICK_ALLOW
							//Changed by sankara on 23/11/12 append active_pack_allow in porpar format 
							//retTabSepStrBuff.append(globalActivePickAllow).append("\t");
							retTabSepStrBuff.append( "<active_pick_allow><![CDATA[" ).append(globalActivePickAllow).append( "]]></active_pick_allow>\r\n" );

							//STOCK_TO_DOCK_ALLOW
							//Changed by sankara on 23/11/12 append stock_to_dock_allow in porpar format 
							//retTabSepStrBuff.append(globalStockToDockAllow).append("\t");							
							retTabSepStrBuff.append( "<stock_to_dock_allow><![CDATA[" ).append(globalStockToDockAllow).append( "]]></stock_to_dock_allow>\r\n" );
							
							//Changed by sumit on 20/12/12 dispaly parcel pack value 
							//PARCELPACK_ALLOW
							retTabSepStrBuff.append( "<parcelpack_allow><![CDATA[" ).append(globalParcelPackAllow).append( "]]></parcelpack_allow>\r\n" );

						}
						else
						{
							//SINGLE LOT
							//Changed by sankara on 23/11/12 append single_lot in porpar format 
							//retTabSepStrBuff.append(singleLot).append("\t");
							retTabSepStrBuff.append( "<single_lot><![CDATA[" ).append(singleLot).append( "]]></single_lot>\r\n" );

							//MASTER_PACK_ALLOW
							//Changed by sankara on 23/11/12 append master_pack_allow in porpar format 
							//retTabSepStrBuff.append(masterPackAllow).append("\t");
							retTabSepStrBuff.append( "<master_pack_allow><![CDATA[" ).append(masterPackAllow).append( "]]></master_pack_allow>\r\n" );

							//ACTIVE_PICK_ALLOW
							//Changed by sankara on 23/11/12 append active_pack_allow in porpar format 
							//retTabSepStrBuff.append(activePickAllow).append("\t");
							retTabSepStrBuff.append( "<active_pick_allow><![CDATA[" ).append(activePickAllow).append( "]]></active_pick_allow>\r\n" );

							//STOCK_TO_DOCK_ALLOW
							//Changed by sankara on 23/11/12 append stock_to_dock_allow in porpar format 
							//retTabSepStrBuff.append(stockToDockAllow).append("\t");	
							retTabSepStrBuff.append( "<stock_to_dock_allow><![CDATA[" ).append(stockToDockAllow).append( "]]></stock_to_dock_allow>\r\n" );
							//Changed by sumit on 20/12/12 dispaly parcel pack value 
							//PARCELPACK_ALLOW
							retTabSepStrBuff.append( "<parcelpack_allow><![CDATA[" ).append(parcelPackAllow).append( "]]></parcelpack_allow>\r\n" );

						}	
						//Changed by sumit on 18/09/12 getting value from header field in case data end

						//Chnaged by sumit on 20/08/12 commented this . going to display below. start.
						//Changed by rohan on 19/07/12 to add transporter details.start
						/*//Tran Code
						retTabSepStrBuff.append(tranCod).append("\t");

						//Tran descr
						retTabSepStrBuff.append(tranName).append("\t");

						//LOCK_CODE_DOCK
						retTabSepStrBuff.append(docLocation).append("\t");
						 */						
						//Chnaged by sumit on 20/08/12 commented this . going to display below. end.

						//Changed by rohan on 19/07/12 to add transporter details.end
						//QUANTITY
						//Changed by sankara on 23/11/12 append quantity in porpar format 
						//retTabSepStrBuff.append(rs.getDouble(8)).append("\t");
						//Changed by sumit on 1/02/13 display pending quantity after convert in std unit.
						//retTabSepStrBuff.append( "<quantity><![CDATA[" ).append(rs.getDouble(8)).append( "]]></quantity>\r\n" );	
						retTabSepStrBuff.append( "<quantity><![CDATA[" ).append(quantity).append( "]]></quantity>\r\n" );	
						//Changed by sumit sarkar on 22/06/12 showing value of part quantity.
						//SHOWING VALUE OF PART QUANTITY 
						//Changed by sankara on 23/11/12 append part_qty in porpar format 
						//retTabSepStrBuff.append(partQtyValue).append("\t");
						retTabSepStrBuff.append( "<part_qty><![CDATA[" ).append(partQtyValue).append( "]]></part_qty>\r\n" );	
						//PENDING_QUANTITY
						//Changed by sankara on 23/11/12 append pending_quantity in porpar format 
						//retTabSepStrBuff.append(rs.getDouble(9)).append("\t");
						//Changed by sumit on 1/02/13 display pending quantity after convert in std unit.
						//retTabSepStrBuff.append( "<pending_quantity><![CDATA[" ).append(rs.getDouble(9)).append( "]]></pending_quantity>\r\n" );	
						retTabSepStrBuff.append( "<pending_quantity><![CDATA[" ).append(pendingQty).append( "]]></pending_quantity>\r\n" );	
						//STOCK_QUANTITY
						//Changed by sumit on 1/02/13 pending qty after convert
						//pendQty = rs.getDouble(9);
						pendQty = pendingQty;

						//***** check itemhashmap wheather current item_code already exists
						// if not add to itemhashmap and get the stock as follows and set in 
						//  tabdelimited string else nothing is to be done just consider the stock as 0
						balStockQtyTemp = balStockQty; // Added by chandni 01-june-2012 
						if (bappend == true)
						{
							//Changed by sankara on 23/11/12 append stock_quantity in porpar format 
							//retTabSepStrBuff.append(balStockQty).append("\t");
							retTabSepStrBuff.append( "<stock_quantity><![CDATA[" ).append(balStockQty).append( "]]></stock_quantity>\r\n" );	
						}
						else
						{
							
							//Changed by sankara on 25-06-2012 to set 0.0 instead of 0 
							//retTabSepStrBuff.append("0").append("\t");
							//Changed by sankara on 23/11/12 append stock_quantity 0.0 in porpar format 
							//retTabSepStrBuff.append("0.0").append("\t");
							retTabSepStrBuff.append( "<stock_quantity><![CDATA[" ).append("0.0").append( "]]></stock_quantity>\r\n" );	
						}
						
						//Changed by sumit on 22/08/12 getting alloc flag start.
						sql = " SELECT FN_MANUAL_STOCK_FOR_EACHITEM(?,?) AS ALLOC_FLAG FROM DUAL";
						 pstmt1 = conn.prepareStatement(sql);
						 pstmt1.setString(1,saleOrderTran);
						 pstmt1.setString(2,rs.getString(3));
						 rs2 = pstmt1.executeQuery();
						 if(rs2.next())
						 {
							 allocFlag = rs2.getString("ALLOC_FLAG");
						 }
						 if ("M".equalsIgnoreCase(allocFlag))
						 {
							 allocFlag = allocFlag;
						 }
						 else
						 {
							 allocFlag = "";
						 }
						 if(pstmt1 != null)
						 {
							 pstmt1.close();
							 pstmt1 = null;
						 }
						 if( rs2 != null)
						 {
							 rs2.close();
							 rs2 = null;
						 }						 
						//Changed by sumit on 22/08/12 getting alloc flag end.
												
						///////////////////////////////////////////////////////////////////////////////////					
						// alloc_qty to be set based on stock availability
						// it should not be more than pending quantity
						// the balance quantity to be updated in itemCodeMap
						// and to be used for the item's next iteration
						//QTY_ALLOC
						if(balStockQty >= pendQty)
						{
							allocQty = pendQty;
							balStockQty -= pendQty;
						}
						else
						{
							allocQty = balStockQty;
							balStockQty = 0;
						}
						//Changed by sumit on 22/08/12 getting alloc flag 
						//if(DefaultQtyFlag.equals("Y"))
						if(DefaultQtyFlag.equals("Y") && !"M".equalsIgnoreCase(allocFlag))
						{
							//Changed by sankara on 23/11/12 append qty_alloc in porpar format 
							//retTabSepStrBuff.append(allocQty).append("\t");
							retTabSepStrBuff.append( "<qty_alloc><![CDATA[" ).append(allocQty).append( "]]></qty_alloc>\r\n" );	
							
						}
						else
						{
							
							//Changed by sankara on 25-06-2012 to set 0.0 instead of 0 
							//retTabSepStrBuff.append("0").append("\t");
							//Changed by sankara on 23/11/12 append qty_allocvalue 0.0 in porpar format 
							//retTabSepStrBuff.append("0.0").append("\t"); 
							retTabSepStrBuff.append( "<qty_alloc><![CDATA[" ).append("0.0").append( "]]></qty_alloc>\r\n" );
						}
						
						//Changed by sumit sarkar on 22/06/12 to display hold quantity.start
						// HOLD_QUANTITY
						/*if (bappend == true)
						{
							//Changed by sankara on 23/11/12 append hold_qty in porpar format 
							//retTabSepStrBuff.append(holdQty).append("\t");
							retTabSepStrBuff.append( "<hold_qty><![CDATA[" ).append(holdQty).append( "]]></hold_qty>\r\n" );
						}
						else
						{
							
							//Changed by sankara on 25-06-2012 to set 0.0 instead of 0 
							//retTabSepStrBuff.append("0").append("\t");
							//Changed by sankara on 23/11/12 append hold_qty value 0.0 porpar format 
							//retTabSepStrBuff.append("0.0").append("\t");
							retTabSepStrBuff.append( "<hold_qty><![CDATA[" ).append("0.0").append( "]]></hold_qty>\r\n" );
						}					
						*/
						sql = "SELECT SUM(HOLD_QTY) AS HOLD_QTY FROM STOCK WHERE ITEM_CODE = ? AND SITE_CODE = ?";
						pstmt1 = conn.prepareStatement(sql);
						pstmt1.setString(1, itemCode);
						pstmt1.setString(2, siteCode);
						rs2 = pstmt1.executeQuery();
						if(rs2.next())
						{
							retTabSepStrBuff.append( "<hold_qty><![CDATA[" ).append(rs2.getDouble(1)).append( "]]></hold_qty>\r\n" );
						}
						
						rs2.close();rs2 = null;
						pstmt1.close();pstmt1 = null;
						//changed by sumit on 28/12/12 commented  and displaying hold_qty end
						// this line has to be commented later
						// as this will be a input from the user
												
						itemCodeMap.put(rs.getString(6), new Double(balStockQty));
						//Added by Chandni 1-june-2012 to add bal_qty field .
						//bal_qty
						sordItemQty= rs.getDouble(8);
						//Changed By Pragyan 25/10/12 it should always reduce the pendQty
						//pendQty
						//balStk = balStockQtyTemp - sordItemQty ; 
						balStk = balStockQtyTemp - pendQty ;
						System.out.println("balStk ::"+balStk);
						if(balStk >= 0)
						{
							//Changed by sankara on 23/11/12 append bal_qty  porpar format 
							//retTabSepStrBuff.append(balStk).append("\t");
							retTabSepStrBuff.append( "<bal_qty><![CDATA[" ).append(balStk).append( "]]></bal_qty>\r\n" );
						}
						else
						{
							
							//Changed by sankara on 25-06-2012 to set 0.0 instead of 0 
							//retTabSepStrBuff.append("0").append("\t");
							//Changed by sankara on 23/11/12 append bal_qty value 0.0 porpar format 
							//retTabSepStrBuff.append("0.0").append("\t"); 
							retTabSepStrBuff.append( "<bal_qty><![CDATA[" ).append("0.0").append( "]]></bal_qty>\r\n" );
						}
						// CHANDNI END 01-june-2012
						
						//Changed by sumit sarkar on 22/06/12 setting alloc_flag START.
						//ALLOC_FLAG
						//Changed by sumit on 22/08/12 getting alloc flag start.
						/* //allocFlag = rs.getString("ALLOC_FLAG");
						 sql = " SELECT FN_MANUAL_STOCK_FOR_EACHITEM(?,?) AS ALLOC_FLAG FROM DUAL";
						 pstmt1 = conn.prepareStatement(sql);
						 pstmt1.setString(1,saleOrderTran);
						 pstmt1.setString(2,rs.getString(3));
						 rs2 = pstmt1.executeQuery();
						 if(rs2.next())
						 {
							 allocFlag = rs2.getString("ALLOC_FLAG");
						 }
						 if ("M".equalsIgnoreCase(allocFlag))
						 {
							 allocFlag = allocFlag;
						 }
						 else
						 {
							 allocFlag = "";
						 }
						 if(pstmt1 != null)
						 {
							 pstmt1.close();
							 pstmt1 = null;
						 }
						 if( rs2 != null)
						 {
							 rs2.close();
							 rs2 = null;
						 }						 
						//Changed by sumit on 22/08/12 getting alloc flag end.
						 */						 
						 //Changed by Pragyan 17/12/12 to get the total amount for allocation
						/*sql = "SELECT QTY_ALLOC FROM SORDALLOC WHERE SALE_ORDER = ? AND LINE_NO = ? " +
						"AND (CASE WHEN WAVE_FLAG IS NULL THEN 'N' ELSE WAVE_FLAG END) = 'N'";*/
						sql = "SELECT SUM(QTY_ALLOC) AS MAN_QTY FROM SORDALLOC WHERE SALE_ORDER = ? AND LINE_NO = ? " +
						"AND (CASE WHEN WAVE_FLAG IS NULL THEN 'N' ELSE WAVE_FLAG END) = 'N'";
						pstmt1 = conn.prepareStatement(sql);
						pstmt1.setString(1, saleOrderTran);
						pstmt1.setString(2, rs.getString(3));
						rs2 = pstmt1.executeQuery();
						if( rs2.next())
						{
							//Changed by Pragyan 17/12/12 to get the total amount for allocation
							//Changed by sankara on 23/11/12 append qty_alloc porpar format 
							//retTabSepStrBuff.append(rs2.getString("QTY_ALLOC")).append("\t");
							//retTabSepStrBuff.append( "<qty_alloc><![CDATA[" ).append(rs2.getString("QTY_ALLOC")).append( "]]></qty_alloc>\r\n" );
							retTabSepStrBuff.append( "<manual_allocqty><![CDATA[" ).append((rs2.getString("MAN_QTY") == null) ? "0.0" :rs2.getString("MAN_QTY")).append( "]]></manual_allocqty>\r\n" );
						}
						else
						{
							//Changed by Pragyan 17/12/12 to get the total amount for allocation
							//Changed by sankara on 23/11/12 append qty_alloc  value 0.0 porpar format 
							//retTabSepStrBuff.append("0.0").append("\t");
							//retTabSepStrBuff.append( "<qty_alloc><![CDATA[" ).append("0.0").append( "]]></qty_alloc>\r\n" );
							retTabSepStrBuff.append( "<manual_allocqty><![CDATA[" ).append("0.0").append( "]]></manual_allocqty>\r\n" );
						}
						if(pstmt1 != null)
						 {
							 pstmt1.close();
							 pstmt1 = null;
						 }
						 if( rs2 != null)
						 {
							 rs2.close();
							 rs2 = null;
						 }					
						
						 if (allocFlag == null)
						 {
							 allocFlag = "";
						 }
						 //Changed by sankara on 23/11/12 append alloc_flag in  porpar format 
						 //retTabSepStrBuff.append(allocFlag).append("\t");
						 retTabSepStrBuff.append( "<alloc_flag><![CDATA[" ).append(allocFlag).append( "]]></alloc_flag>\r\n" );
						 //Changed by sumit sarkar on 22/06/12 setting alloc_flag END.

						 //Chnaged by sumit on 20/08/12 above commented code display here start.						
						 //Tran Code
						 //Changed by sankara on 23/11/12 append tran_code in porpar format 
						 //retTabSepStrBuff.append(tranCod).append("\t");
						 retTabSepStrBuff.append( "<tran_code><![CDATA[" ).append(tranCod).append( "]]></tran_code>\r\n" );

						 //Tran descr
						 //Changed by sankara on 23/11/12 append tran_descr in  porpar format 
						 //retTabSepStrBuff.append(tranName).append("\t");	
						 retTabSepStrBuff.append( "<tran_name><![CDATA[" ).append(tranName).append( "]]></tran_name>\r\n" );

						 //LOCK_CODE_DOCK
						 //Changed by sankara on 23/11/12 append lock_code_dock in  porpar format 
						 //retTabSepStrBuff.append(docLocation).append("\t");
						 retTabSepStrBuff.append( "<lock_code__dock><![CDATA[" ).append(docLocation).append( "]]></lock_code__dock>\r\n" );
						 //Chnaged by sumit on 20/08/12 above commented code display here end.

						 //PACK_INSTR
						packInstr = rs.getString(11);
						if (packInstr == null)
						{
							packInstr = "";
						}
						//Changed by sankara on 23/11/12 append pack_instr in  porpar format 
						//retTabSepStrBuff.append(packInstr).append("\t");
						retTabSepStrBuff.append( "<pack_instr><![CDATA[" ).append(packInstr).append( "]]></pack_instr>\r\n" );
						//SITE_CODE
						//Changed by sankara on 23/11/12 append site_code in  porpar format 
						//retTabSepStrBuff.append(rs.getString(12)).append("\t");
						retTabSepStrBuff.append( "<site_code><![CDATA[" ).append(rs.getString(12)).append( "]]></site_code>\r\n" );
						//EXP_LEV
						//Changed by sankara on 23/11/12 append exp_lev in  porpar format 
						//retTabSepStrBuff.append(rs.getString(13)).append("\t");
						retTabSepStrBuff.append( "<exp_lev><![CDATA[" ).append(rs.getString(13)).append( "]]></exp_lev>\r\n" );
						//Changed by sumit sarkar on 22/06/12 display part_qty_real start.
						//PARY_QTY_REAL
						//Changed by sankara on 23/11/12 append part_qty_real in  porpar format 
						//retTabSepStrBuff.append(partQty).append("\t");
						retTabSepStrBuff.append( "<last_col><![CDATA[" ).append("").append( "]]></last_col>\r\n" );
						retTabSepStrBuff.append( "<part_qty_real><![CDATA[" ).append(partQty).append( "]]></part_qty_real>\r\n" );
						//Changed by sumit sarkar on 22/06/12 display part_qty_real end.
						//Changed by sankara on 23/11/12 append last_col in  porpar format 			
						//retTabSepStrBuff.append("  ").append("\n");
					   
						retTabSepStrBuff.append( "</Detail2>\r\n" );
					}
					  //retTabSepStrBuff.append( "</Root>\r\n" );			
				}while(rs.next());
				//Changed by sankara on 23/11/12 closed header and root		
				 retTabSepStrBuff.append( "</Header0>\r\n</group0>\r\n</DocumentRoot>\r\n" );		
				resultString = retTabSepStrBuff.toString();
				System.out.println("ResultString....." + resultString);
				pstmt.clearParameters();	
			}
			else
			{
				errCode ="VTNOREC2";
			}
			if (!errCode.equals(""))
			{
				resultString = itmDBAccessEJB.getErrorString("", errCode, "", "", conn);
				System.out.println("resultString: "+resultString);
			}
			
			if(st != null)
			{
				st.close();
				st = null;
			}
			if(pstmt != null)
			{
				pstmt.close();
				pstmt=null;
			}
			if(pstmt1 != null)
			{
				pstmt1.close();
				pstmt1 = null;
			}
			if(pstmtStock != null)
			{
				pstmtStock.close();
				pstmtStock = null;
			}
			
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(rs1 != null)
			{
				rs1.close();
				rs1 = null;
			}
			if(rs2 != null)
			{
				rs2.close();
				rs2 = null;
			}
			if(pstmtTran != null)
			{
				pstmtTran.close();
				pstmtTran = null;
			}
			if(rsTran != null)
			{
				rsTran.close();
				rsTran = null;
			}
		}
		catch (SQLException e)
		{
			System.out.println("SQLException :StockAllocationPrcEJB :getData(Document headerDom, Document detailDom, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		catch (Exception e)
		{
			System.out.println("Exception :StockAllocationPrcEJB :getData(Document headerDom, Document detailDom, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		finally
		{
			cleanup();

			try
			{
				retTabSepStrBuff = null;
				if(conn != null)
				{		
					if(st != null)
					{
						st.close();
						st = null;
					}
					
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					if(rs1 != null)
					{
						rs1.close();
						rs1 = null;
					}
					if(rs2 != null)
					{
						rs2.close();
						rs2 = null;
					}
					if(rsTran != null)
					{
						rsTran.close();
						rsTran = null;
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt=null;
					}
					if(pstmt1 != null)
					{
						pstmt1.close();
						pstmt1 = null;
					}
					if(pstmtStock != null)
					{
						pstmtStock.close();
						pstmtStock = null;
					}
					if(pstmtTran != null)
					{
						pstmtTran.close();
						pstmtTran = null;
					}
					if(rsTran != null)
					{
						rsTran.close();
						rsTran = null;
					}
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				errString = e.getMessage();
				e.printStackTrace();
				throw new ITMException(e);
			}
		}		
		return resultString;	
	}
	//Process Method

	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();
		System.out.println("below genericUtility--------------->>>>>>>>>");
		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 :StockAllocationPrcEJB :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			retStr = e.getMessage();
			throw new ITMException(e);
		}
		return retStr;
		
	}
	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("detailDom------------------->"+detailDom);
		String childNodeName = "";
		String errCode = "";
		//String siteCode = this.siteCode;
		String postOrderFg = "N";
		String saleOrder = null;
		String expLev = null ;
		String itemCode = null;
		String lineNo = null;
		String unit = null;
		String locCode = null;
		String lotSl= null;
		String lotNo = null;
		String locType = null; // commented by chandni shah
		int locZonePref = 0;
		String locTypeParent = null; //Changes done by chandni 08-06-12(instead of loc_type, loc_type__parent should be selected)
		String locDescr = null;
		String itemShDescr = null;
		//changed by Rohan 14-04-12 [WM1ESUN006] to add sql.start 
		String sql = "";
		String sqlinvStat = "";
		String sodreAlloc = "";
		String invSt = ""; 
		//Changed by Rohan on 7/6/12 To set Reason detai null.start
		String SqlSord = "";
		PreparedStatement pstmtSord = null;
		//Changed by Rohan on 7/6/12 To set Reason detai null.end
		double qtyAllocate = 0;
		double noOfArticals = 0;
		boolean manualStock = false;
		String isActivePickChecked = "N";
		String isStockToDockChecked = "N";
		String isMasterPickChecked = "N";
		//Changed By Pragyan 31/12/12 To get Parcel Pack Flag
		String isParcelPickChecked = "N";
		String directPickLoc = "";
		HashMap saleOrderWiseMapCopy = null;
		HashMap saleOrderWiseMapCpy = null;
		boolean isStockToDock = false;
		ArrayList tempList = null;
		HashMap tempMap = null;
		String locCd = "";
		//changed by Rohan 14-04-12 [WM1ESUN006] to add sql.end 
		double allocQty = 0;
		double quantity = 0;
		double qtyAvailAlloc = 0;
		String stockQuantity = "";
		String errString = "";
		//Chnaged by sumit on 27/08/12 getting waveFlag from sord_alloc.
		String waveFlag = "";		
		//Change by Rohan on 22/08/12 to get arraylist for manual stock allocation.start
		ArrayList tempListForRepl =null;			
		//boolean manualFlagAct = false;
		//Change by Rohan on 22/08/12 to get arraylist for manual stock allocation.end
		String printMode = "";
		String singleLot = "";
		//String getDataSql= null;
		//String insertSql = null;
		//String updateSql = null;
		
		Connection conn = null;
		ResultSet rs = null;
		//ResultSet rs1 = null;
		//ResultSet rs2 = null;
		double manualAllocqty = 0.0;
		String allocFlag = "";
		//int updCnt = 0;
		int parentNodeListLength = 0;
		int childNodeListLength = 0;
		//Changed By Sankara Rao To get the Pending Quantity.
		double pendingQuantity = 0.0;
		
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
				
		PreparedStatement pstmt = null;
		//Statement st = null; 
		//HashMap itemHashMap = new HashMap();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header.start
		replCnt = 1;
		isReplHdr = false;
		replOrdCpy = "";
		
		rplCntDSO = 1;
		isReplHdrDSO = false;
		replOrdDSOCpy = "";
		
		rplCntPND = 1;
		isReplHdrPND = false;
		replPNDCpy = "";
		
		rplCntPSO = 1;
		isReplHdrPSO = false;
		replOrdPSOCpy = "";
		
		rplCntRSV = 1;
		isReplHdrRSV = false;
		replOrdRSVCpy = "";		
		//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header.end
		
		//Changed By Pragyan To store previous location code as blank.
		prevsLocCode = "";
		//Changed By Pragyan 23/02/13 To store ship type .
		String shipType = "";
		int countLoc = 0;
		//Changed By Pragyan 12/03/13 to check hazrard meterial
		String hazardous = "";
		double perItemVolume = 0.0,caseVolume = 0.0,caseWeight = 0.0,itemWeight = 0.0,caseCount = 0.0,packSize = 0d;;
     	//Changed By Pragyan 12/03/13 to define the veriable once.start
		
		
		try
		{
			//Changed sumit on 25/08/12
			waveId = "";
			//Changed by sumit on 14/12/12 getting value of printer start
			printer = "";
			printer = checkNull(genericUtility.getColumnValue("printer_name",headerDom));			
			printLabel = genericUtility.getColumnValue("print_label",headerDom);
			System.out.println("* printLabel ["+printLabel+"] printer ["+printer+"]");
			PrintService[] printServices = PrinterJob.lookupPrintServices();
			ArrayList<String> arry = new ArrayList<String>();
			//Changed by sumit on 24/11/12 adding print label condition
			
			if(printer.trim().length() == 0 && "Y".equalsIgnoreCase(printLabel))
			{
				/*errFields.add( childNodeName.toLowerCase() );
				errList.add( "NLLPRINTER" );*/
				errString="NLLPRINTER";
				errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
				return errString;
			}
			else if(printer.trim().length() > 0 && "Y".equalsIgnoreCase(printLabel))
			{				
				for (PrintService printService : printServices) 
				{
		            String name = printService.getName();
		            System.out.println("printer service name --> "+name);
		            arry.add(name);					            
		        }
				if( !arry.contains(printer.trim()))
	            {	            	
					errString="INVPRINTER";
					errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
					return errString;
	            }							
				arry.clear();				           
			}
			//Changed by sumit on 14/12/12 getting value of printer end
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId");

			siteCode = genericUtility.getColumnValue("site_code",headerDom);
			waveMode = genericUtility.getColumnValue("wave_mode",headerDom);
			shipType = genericUtility.getColumnValue("ship_type",headerDom);
			directPickLoc = genericUtility.getColumnValue("direct_pick_loc",headerDom);
			
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver = null;
			
			if(directPickLoc != null && directPickLoc.length() > 0)
			{
				sql = 	"SELECT COUNT(*) FROM LOCATION WHERE LOC_CODE= ? AND DIRECT_PICK = ?" ;
				
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, directPickLoc);
				pstmt.setString(2, "Y");
				rs = pstmt.executeQuery();
				if( rs.next())
				{					
					countLoc = rs.getInt(1); 
					if( !(countLoc > 0))
					{
						return errString = itmDBAccessEJB.getErrorString("","INVDPIKLOC","","",conn);
					}
				}
				
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;								
				}
			}
						
			pickSaleOrderDetail.clear();
			parentNodeList = detailDom.getElementsByTagName("Detail2");
			parentNodeListLength = parentNodeList.getLength(); 
			System.out.println("parentNodeListLength------------------->"+parentNodeListLength);
			saleOrderWiseMap.clear();
			itemInfoMapForRepl.clear();
			replanismentInfoList.clear();
			//Changed By Rohan on 7/5/12 To Clear list.start
			saleOrderWiseNotAllowList.clear();
			saleOrderWisePartialAllowList.clear();
			//Chnaged By Rohan on 7/5/12 To Clear list.end
			System.out.println("Clear the SaleOrder Map List------------------->Check"+saleOrderWiseMap.size());
			//Changed by Rohan to Clear 
			printMode = checkNull(discommon.getDisparams("999999","WAVE_PRINT_MODE",conn));		
			//Changed By Pragyan to create wave for mannual allocated data
			//updateMannualStockMap(detailDom, conn);
			validateSorder(detailDom,conn);
			System.out.println("saleOrderWiseNotAllowList==========>"+saleOrderWiseNotAllowList);
			//Chnaged by sumit on 23/08/12 deleting sorditem_temp start.
			sql = "DELETE FROM SORDITEM_TEMP";
			pstmt = conn.prepareStatement(sql);
			pstmt.executeUpdate();
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			//Chnaged by sumit on 23/08/12 deleting sorditem_temp end.
			
			
			for (int selectedRow = 0; selectedRow < parentNodeListLength; selectedRow++)
			{
				int count = 0;
				parentNode = parentNodeList.item(selectedRow);
				manualStock = false;
				waveFlag = "";
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				System.out.println("childNodeListLength---->>> "+ childNodeListLength);
				
				for (int childRow = 0; childRow < childNodeListLength; childRow++)
				{
					childNode = childNodeList.item(childRow);
					childNodeName = childNode.getNodeName();
 					System.out.println("childNodeName---->>> "+ childNodeName);
					if (childNodeName.equals("stock_quantity"))
					{
						stockQuantity = childNode.getFirstChild().getNodeValue();
					}
					
					if (childNodeName.equals("sale_order"))
					{
						saleOrder = childNode.getFirstChild().getNodeValue();
					}

					if (childNodeName.equals("line_no"))
					{
						lineNo = childNode.getFirstChild().getNodeValue();
					}

					if (childNodeName.equals("item_code"))
					{
						itemCode = childNode.getFirstChild().getNodeValue();
					}

					if (childNodeName.equals("qty_alloc"))
					{
					    
						allocQty = Double.parseDouble(childNode.getFirstChild().getNodeValue());
						System.out.println("qty_alloc======>"+allocQty);
					}
					if (childNodeName.equals("exp_lev"))
					{
						expLev = childNode.getFirstChild().getNodeValue();
					}
					//changed by sankara on 03-08-2012 adding pending quantity[start]
					
					if (childNodeName.equals("pending_quantity"))
					{
						pendingQuantity = Double.parseDouble(childNode.getFirstChild().getNodeValue());
					}
					if (childNodeName.equals("cust_code"))
					{
						custCode = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("single_lot"))
					{
						singleLot = childNode.getFirstChild().getNodeValue();
					}
					//changed by sankara on 03-08-2012 adding pending quantity[end]
					if (childNodeName.equals("active_pick_allow"))
					{
						isActivePickChecked = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("stock_to_dock_allow"))
					{
						isStockToDockChecked = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("master_pack_allow"))
					{
						isMasterPickChecked = childNode.getFirstChild().getNodeValue();
						System.out.println("isMasterPickChecked["+childNode.getFirstChild().getNodeValue()+"]");
					}
					//Changed By Pragyan 31/12/12 To get Parcel Pack Flag.start
					if (childNodeName.equals("parcelpack_allow"))
					{
						System.out.println("isParcelPickChecked["+childNode.getFirstChild().getNodeValue()+"]");
						isParcelPickChecked = childNode.getFirstChild().getNodeValue();
					}
					//Changed By Pragyan 31/12/12 To get Parcel Pack Flag.end
					//Changed by sumit on 14/12/12 adding validation incase of manualy allocating saleorder and modifiying qty_allow start.
					if (childNodeName.equals("manual_allocqty"))
					{
						if(childNode.getFirstChild() != null)
						{							
							manualAllocqty = Double.parseDouble(childNode.getFirstChild().getNodeValue());
							System.out.println(" manualAllocqty ["+manualAllocqty+"]");							
						}
						else
						{
							manualAllocqty = 0.0;
						}
					}
					if (childNodeName.equals("alloc_flag"))
					{							
						if(childNode.getFirstChild() != null)
						{
							System.out.println(" inside manuall flag");
							allocFlag = checkNull(childNode.getFirstChild().getNodeValue());
						}
						else
						{
							allocFlag = "";
						}
						
					}
					//Changed by sumit on 14/12/12 adding validation incase of manualy allocating saleorder and modifiying qty_allow end.
			
				}
				
				//Changed By Pragyan 26-02-13 To validate inputs combination given by the user.start
				
				System.out.println("isMasterPickChecked["+isMasterPickChecked+"]isParcelPickChecked ["+isParcelPickChecked+"]shipType["+shipType+"]");
				
				if(("Y".equalsIgnoreCase(isMasterPickChecked)) && !("A".equalsIgnoreCase(shipType) || "M".equalsIgnoreCase(shipType)))
				{
					return errString = itmDBAccessEJB.getErrorString("","ATLSTSELMP","","",conn);
				}
				else if(("Y".equalsIgnoreCase(isParcelPickChecked)) && !("A".equalsIgnoreCase(shipType) || "P".equalsIgnoreCase(shipType)))
				{
					return errString = itmDBAccessEJB.getErrorString("","ATLSTSELPP","","",conn);
				}
				else if(!("Y".equalsIgnoreCase(isParcelPickChecked) || "Y".equalsIgnoreCase(isMasterPickChecked) ) && ("M".equalsIgnoreCase(shipType) || "P".equalsIgnoreCase(shipType)))
				{
					return errString = itmDBAccessEJB.getErrorString("","ATLSTSENAN","","",conn);
				}
				//Changed By Pragyan 26-02-13 To validate inputs combination given by the user.End
				//Changed by Rohan on 15-04-13 for if active pick is N then allocate only case quantity.start
				
				packSize = (Double)getItemVoumeMap(itemCode,"",conn).get("PACK_SIZE");
				System.out.println("isActivePickChecked"+isActivePickChecked+"allocQty"+allocQty+"packSize"+packSize);
				if("N".equalsIgnoreCase(isActivePickChecked)) 
				{	
					allocQty = Math.floor(allocQty / packSize) * packSize;
					
				}	
				//Changed by Rohan on 15-04-13 for if active pick is N then allocate only case quantity.end
			
				System.out.println(" inside manuall flag");
				if("M".equalsIgnoreCase(allocFlag) && allocQty != 0 && manualAllocqty > 0)
				{
					System.out.println(" manually quantity upadated in case of manuly stock allocated");
					errString="INVMDYALLQ";
					//errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
					errString = getError(saleOrder,errString,conn);
					return errString;								
				}
				// Changed by rohan on 14/08/12 for stock allocation end.
				//Changed by sumit on 31/12/12 validation if allocation quantity is less then shiper size start			
				//Changed by Rohan on 15-04-13 for adding condition of allocqty not null
				//if("N".equalsIgnoreCase(isActivePickChecked) && allocQty < (Double)getItemVoumeMap(itemCode,"",conn).get("PACK_SIZE"))
				if("N".equalsIgnoreCase(isActivePickChecked) && allocQty != 0 && allocQty < packSize)
				{
					System.out.println(" inside sumit active");
					errString = getError(saleOrder,"INVORDQTY",conn);
					return errString;
				}
				//Changed by sumit on 31/12/12 validation if allocation quantity is less then shiper size end
				//Changed by Rohan to set resons detail null in sorder item.start
				
				SqlSord = "UPDATE SORDITEM SET REAS_DETAIL =  ? "
				+ " WHERE SALE_ORDER = ? AND LINE_NO = ?";
				System.out.println("*****saleOrder--->"+saleOrder);
				System.out.println("*****lineNo--->"+lineNo);
				
				pstmtSord = conn.prepareStatement(SqlSord);
				pstmtSord.setString(1, "");
				pstmtSord.setString(2, saleOrder);
				pstmtSord.setString(3, lineNo);
				pstmtSord.executeUpdate();

				
				if( pstmtSord != null )
				{
					pstmtSord.close();
					pstmtSord = null;
				}
				//Changed by Rohan to set resons detail null in sorder item.end
				if(saleOrderWiseNotAllowList.contains(saleOrder))
				{
					System.out.println("Enter with saleOrder"+saleOrder+"lineNo"+"1");
					//Changed by Rohan on 09-02-13 for bug fixing
					//updateSorderItemReasonDet(saleOrder, lineNo, "1","", conn);
					updateSorderItemReasonDet(saleOrder, lineNo, "0","", conn);
					continue;
				}
				System.out.println("saleOrderWiseNotAllowList************"+saleOrderWiseNotAllowList);
				//Chnaged by Rohan on 7/6/12 for bug Fixing
				//if(saleOrderWiseNotAllowList.contains(saleOrder+":"+lineNo))
				if(saleOrderWisePartialAllowList.contains(saleOrder+":"+lineNo))
				{
					System.out.println("Enter with saleOrder and lineNo$$$$$$$$$$4"+saleOrder+"lineNo"+lineNo);
					//Changed by Rohan on 09-02-13 for bug fixing
					//updateSorderItemReasonDet(saleOrder, lineNo, "2","", conn);
					updateSorderItemReasonDet(saleOrder, lineNo, "1","", conn);
					continue;
				}
				
				//changed by sankara on 03-08-2012[start]
				boolean isSingleLot = isSingleLotAllowed(itemCode,pendingQuantity,siteCode,singleLot,conn);
				if(isSingleLot == true)
				{
		            updateSorderItemReasonDet(saleOrder, lineNo, "","Stock  Not Available in Single Lot", conn);
					continue;
				}
				//changed by sankara on 03-08-2012[end]
				
				String lineNoSord = lineNo;
				lineNoSord = "   " + lineNoSord; 
				lineNoSord = lineNoSord.substring(lineNoSord.length()-3);
				
				// Changed by sumit on 14/08/12 for manual stock allocation (as per rohan) start.
				/*sql = 	" SELECT D.WAVE_FLAG FROM SORD_ALLOC S,SORD_ALLOC_DET D"+ 
						" WHERE S.TRAN_ID = D.TRAN_ID"+
						" AND S.SALE_ORDER = ?"+
						" AND D.LINE_NO__SORD = ?"+
						" AND D.ITEM_CODE = ?"+
						" AND D.EXP_LEV = ?"+
						" AND CONFIRMED = ?"; */
				
				sql = 	" SELECT D.WAVE_FLAG FROM SORDALLOC D"+
						" WHERE D.SALE_ORDER = ?"+
						" AND D.LINE_NO = ?"+
						" AND D.ITEM_CODE = ?" +
						//Changed By Pragyan 07/03/13
						" AND D.EXP_LEV = ?"+
						" AND D.ALLOC_MODE <> ?";
						//" AND CONFIRMED = ?"; 
				
						pstmt = conn.prepareStatement(sql);	
						pstmt.setString(1,saleOrder);
						pstmt.setString(2,lineNoSord);
						pstmt.setString(3,itemCode);
						pstmt.setString(4,expLev);
						//Changed By Pragyan 07/03/13
						pstmt.setString(5,"W");
						//pstmt.setString(5,"Y");
	
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					//count = rs.getInt("CNT"); 
					waveFlag = rs.getString("WAVE_FLAG");
					if(waveFlag == null)
						waveFlag = "N";
				}
				if( rs != null)
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				
			    //--;//need to close result set and prepared statment 
				//if(count == 1)
				if("N".equalsIgnoreCase(waveFlag))
				{
					
					manualStock = true;
					
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					
					sodreAlloc = "SELECT S.QTY_ALLOC AS QTY_ALLOC,S.QUANTITY AS QUANTITY,S.LOT_SL AS LOT_SL,S.LOT_NO AS LOT_NO,"+
							//Changed by Rohan on 26/06/12 for bug Fixing
							//" S.LOC_COD AS LOC_CODE,I.LOC_TYPE__PARENT AS LOC_TYPE__PARENT FROM SORDALLOC S,ITEM_CODE I"+  //Changes done by chandni 08-06-12(instead of loc_type, loc_type__parent should be selected)
							" S.LOC_CODE AS LOC_CODE,I.LOC_TYPE__PARENT AS LOC_TYPE__PARENT,I.LOC_TYPE AS LOC_TYPE,I.LOC_ZONE__PREF AS LOC_ZONE__PREF FROM SORDALLOC S,ITEM I"+ 
							" WHERE S.SALE_ORDER = ? AND S.ITEM_CODE = I.ITEM_CODE"+
							" AND S.LINE_NO = ?"+
							" AND S.ITEM_CODE = ?"+
							" AND S.EXP_LEV = ? "+
							//Changed By Pragyan 07/03/13
							" AND S.ALLOC_MODE <> ?";
			   
						pstmt = conn.prepareStatement(sodreAlloc);	
						pstmt.setString(1,saleOrder);
						pstmt.setString(2,  lineNo);
						pstmt.setString(3,itemCode);
						pstmt.setString(4,expLev);
						//Changed By Pragyan 07/03/13
						pstmt.setString(5,"W");
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						
						qtyAllocate = rs.getInt("QTY_ALLOC");
						noOfArticals = rs.getInt("QUANTITY");
						lotSl = rs.getString("LOT_SL");
						lotNo = rs.getString("LOT_NO");
						locCd = rs.getString("LOC_CODE");
						locTypeParent = rs.getString("LOC_TYPE__PARENT"); //Changes done by chandni 08-06-12(instead of loc_type, loc_type__parent should be selected)
						locType =  rs.getString("LOC_TYPE");
						locZonePref = rs.getInt("LOC_ZONE__PREF");
						
						System.out.println("lotSl===<"+lotSl);
						System.out.println("lot_no===<"+lotNo);
						System.out.println("locCd===<"+locCd);
						System.out.println("locType===<"+locType);
						System.out.println("locTypeParent===<"+locTypeParent);
					}
					
					sqlinvStat = "SELECT INV_STAT FROM LOCATION WHERE LOC_CODE= ?";
					pstmt = conn.prepareStatement(sqlinvStat);	
					pstmt.setString(1,locCd);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						invSt= rs.getString("INV_STAT");
						System.out.println("INV STATSSS"+invSt);
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					String resvInvStat = "";
					resvInvStat = discommon.getDisparams("999999","RESERV_LOCATION",conn);
					if (resvInvStat == null)
					{
						resvInvStat = "";
					}
					//double packSize = 0d;
					
					//Change by rohan on 22/08/12 to check replanishment history.start
					HashMap itmVolumeMap = getItemVoumeMap(itemCode,lotNo,conn);
					double itemPackSize = (Double)itmVolumeMap.get("PACK_SIZE");
					populateReplHistory(itemCode,siteCode,lotNo,lotSl,locCd,conn);
					double stkQuantity = getStockQuantity(itemCode,siteCode,locCd,lotNo,lotSl,qtyAllocate,conn);
					
					Map tempMapReplenishment =new HashMap();
					String lastReplenishmentID="",locCodeTo="";
					int lineNoRepl=0;
					
					if(itemInfoMapForRepl.containsKey(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCd))
					{
						ArrayList tempListTestForRepl = (ArrayList)itemInfoMapForRepl.get(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCd);
							
	                }
	                else
	                {
	                	tempListForRepl  = new ArrayList();
	                	qtyActual=0.0;                	
	                	
	                	
	                	//Changed By Pragyan as It is not reuired actives are treated separately.start
	                	/*if(qtyAllocate < itemPackSize)
	                	{
	                		tempMapReplenishment.put("QTY_AVAIL",itemPackSize);
	                		
	                		if(allocQty > 0)
	                		{	
	                			tempMapReplenishment.put("MANUAL_FLAG_ACTIVE","Y");
	                		}
	                		
	                	}
	                	else
	                	{	
	                		tempMapReplenishment.put("QTY_AVAIL",stkQuantity);
	                	}*/
	                	//Changed By Pragyan as It is not reuired actives are treated separately.
	    				tempMapReplenishment.put("QTY_ACTUAL", qtyActual);
	    				tempMapReplenishment.put("LAST_REPL_ID", lastReplenishmentID);
	    				tempMapReplenishment.put("REPL_LINE_NO", lineNoRepl);
	    				tempMapReplenishment.put("REPL_LOC_TO",locCd);
	    				tempMapReplenishment.put("IS_REPLAINSH","Y");	
	    				tempMapReplenishment.put("STOCK_QTY",stkQuantity);
	    				tempListForRepl.add(tempMapReplenishment);
	    				itemInfoMapForRepl.put(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCd, tempListForRepl);
	                }
					//Changed by Rohan on 15-04-13 for get pack size upper in coding
					//packSize = (Double)itmVolumeMap.get("PACK_SIZE");//How many item contains in the Case
					//Changed By Pragyan 12/03/13 to define the veriable once.start
					/*double perItemVolume = (Double)itmVolumeMap.get("ITEM_SIZE");//Each Item Volume
					double caseVolume = (Double)itmVolumeMap.get("LOT_SIZE");//Items Case Volume
					double caseWeight = (Double)itmVolumeMap.get("PACK_WEIGHT");
					hazardous = (String)itmVolumeMap.get("HAZARDOUS");
					double itemWeight = (Double)itmVolumeMap.get("ITEM_WEIGHT");
					double caseCount = qtyAllocate /packSize;*/
					 perItemVolume = (Double)itmVolumeMap.get("ITEM_SIZE");//Each Item Volume
					 caseVolume = (Double)itmVolumeMap.get("LOT_SIZE");//Items Case Volume
					 caseWeight = (Double)itmVolumeMap.get("PACK_WEIGHT");
					 hazardous = (String)itmVolumeMap.get("HAZARDOUS");
					 itemWeight = (Double)itmVolumeMap.get("ITEM_WEIGHT");
					 caseCount = qtyAllocate /packSize;
					 //Changed By Pragyan 12/03/13 to define the veriable once.start
					//Change by rohan on 22/08/12 to check replanishment history.end
					if(invSt != null && invSt.trim().equalsIgnoreCase(resvInvStat.trim()))
					{
						
						double palletVolume  = Double.parseDouble(discommon.getDisparams("999999","PER_PALLET__VOLUME",conn));
						//Changed by Rohan on 22/08/12 to define earlier in code
						//HashMap itmVolumeMap = getItemVoumeMap(itemCode,lotNo,conn);
					    
						if(caseCount > 0 &&  (caseCount * caseVolume) <= palletVolume && ((palletVolume - (caseCount * caseVolume)) < caseVolume))  
						 {
							 isStockToDock = true;
						 }
						 else if((qtyAllocate * perItemVolume) <= palletVolume &&  ((palletVolume - (qtyAllocate * perItemVolume)) < perItemVolume))
						 {
							 isStockToDock = true;
						 }
					}
					// Changed by sumit on 14/08/12 for stock allocation (as per rohan) end.
					//if(saleOrderWiseMap.containsKey(saleOrder+":"+locTypeParent))
					if(saleOrderWiseMap.containsKey(saleOrder+":"+locTypeParent))
                    {
						//Changed By Pragyan Demo4
                        //tempList = (ArrayList) saleOrderWiseMap.get(saleOrder);
						//tempList = (ArrayList) saleOrderWiseMap.get(saleOrder+":"+locType);
						//Changed by Rohan on 26/06/12 For Manual Stock Allocation
                        //tempList = (ArrayList) saleOrderWiseMap.get(saleOrder+":"+locTypeParent); //Changes done by chandni 08-06-12(instead of loc_type, loc_type__parent should be selected)
						tempList = (ArrayList) saleOrderWiseMap.get(saleOrder+":"+locTypeParent); 
                    }
					
                    else
                    {                    	
                        tempList  = new ArrayList();
                    }
	                // populate the map with the stock keys
                    tempMap = new HashMap();
                    
                    tempMap.put("site_code", siteCode);
                    tempMap.put("item_code", itemCode);
                    //Change by rohan on 27/06/12 
                    //tempMap.put("loc_code", locCode);
                    tempMap.put("loc_code", locCd);
                    tempMap.put("lot_no", lotNo);
                    tempMap.put("lot_sl", lotSl);
                    tempMap.put("no_art", String.valueOf(noOfArticals));
                    tempMap.put("alloc_qty", qtyAllocate);
                    tempMap.put("inv_stat", invSt);
                    if(isStockToDock)
                    {
                    	tempMap.put("stock2_dock", "Y");
                    }
                    else
                    {
                    	tempMap.put("stock2_dock", "N");
                    }
                    tempMap.put("exp_lev", expLev);
                    //Changed by Rohan on 22/08/12 to put shipper size
                    //tempMap.put("pack_size", packSize);
                    tempMap.put("pack_size", itemPackSize);
                    tempMap.put("sord_lineNo", lineNo);
                    tempMap.put("loc_type", locType);
                    tempMap.put("loc_type_parent", locTypeParent);
                    tempMap.put("loc_zone_pref", locZonePref);
                    tempMap.put("master_pack", isMasterPickChecked);
                    tempMap.put("active_pick", isActivePickChecked);
                    tempMap.put("parcel_pick", isParcelPickChecked);
                    tempMap.put("exp_lev", expLev);
                    //Changed By Pragyan add the pack_size in the map.
                    tempMap.put("pack_size", packSize);
                    tempMap.put("sord_lineNo", lineNo);
                    tempMap.put("item_weight", itemWeight);
                    
                    locCodeTo = locCodeTo != null && locCodeTo.length() > 0 ?locCodeTo:locCode;
                    tempMap.put("sugg_loc", locCodeTo);               	
					//Changed By Pragyan 12/03/13 To add hazardous 
                    tempMap.put("hazard", hazardous);
                    tempList.add(tempMap);          
                    saleOrderWiseMap.put(saleOrder+":"+locTypeParent,tempList);
                   
				}
	
				if(manualStock)
				{
					int update = 0;
					/*String lineNoSord = lineNo;
					lineNoSord = "   " + lineNoSord; 
					lineNoSord = lineNoSord.substring(lineNoSord.length()-3);*/
					//sql= "UPDATE SORD_ALLOC_DET SET WAVE_FLAG = 'Y' WHERE SALE_ORDER = ? AND LINE_NO__SORD = ?";
					sql= "UPDATE SORDALLOC SET WAVE_FLAG = 'Y' WHERE SALE_ORDER = ? AND LINE_NO = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, saleOrder);
					pstmt.setString(2, lineNoSord);
					update = pstmt.executeUpdate();
					if(update > 0)
					{
						System.out.println(" SORD_ALLOC updated ["+update+"]");
					}
					if( pstmt!= null)
					{
						pstmt.close();
						pstmt = null;
					}
				}
				
				//if(allocQty > 0 && (!manualStock))
				if(allocQty > 0)
				{
					/*
					 //commented by Pragyan - 14-06-12
					//changed by Rohan on 18-04-12 [WM1ESUN006] To clear saleOrderWiseMap.start
					if(!saleOrderWiseMap.isEmpty())
					{	
						saleOrderWiseMap.clear();
					}
					//changed by Rohan on 18-04-12 [WM1ESUN006] To clear saleOrderWiseMap.end
                   */					
					System.out.println("if calling...===>.....");	
					//Changed By Pragyan 31/12/12 To pass the Pacel pack flag to the method
					//errString = sorderAllocate(saleOrder, lineNo, itemCode, allocQty, expLev);
					//errString = sorderAllocate(headerDom, detailDom, saleOrder, lineNo, itemCode, allocQty, expLev, xtraParams, conn );
					//errString = sorderAllocate(headerDom, detailDom, saleOrder, lineNo, itemCode, allocQty,singleLot,pendingQuantity,isActivePickChecked,isMasterPickChecked,isStockToDockChecked, expLev, xtraParams, conn );
					errString = sorderAllocate(headerDom, detailDom, saleOrder, lineNo, itemCode, allocQty,singleLot,pendingQuantity,isActivePickChecked,isMasterPickChecked,isStockToDockChecked,isParcelPickChecked, expLev, xtraParams, conn );
					if (errString != null && errString.trim().length() > 0)
					{
						System.out.println("errString :"+errString);
						return errString;
					}
					//changed by Rohan on 18-04-12 [WM1ESUN006] To copy saleOrderWiseMap
					saleOrderWiseMapCpy = (HashMap) saleOrderWiseMap.clone();
	                    
				}
				
			} // out for loop 
			if(postOrderFg.equals("Y"))
			{
					
				errString = postOrder(saleOrderArr, xtraParams);
				if (errString != null && errString.trim().length() > 0)
				{
					System.out.println("errString :"+ errString);
					return errString;
				}
			}
			//HashMap saleOrderWiseMap = saleOrderWiseMapCopy;
			//System.out.println("GOING FOR CALCULATION"+saleOrderWiseMap.toString());
			//Task Work begins from hear
			//Changed by Rohan on 18-04-12 [WM1ESUN006] Not allocate stock is stock is manually allocate.start

			//errString = updateWaveTask(headerDom, detailDom,lineNo, xtraParams, conn);
			//Calling Manual stock allocation Map
			/*
		 	//Commented by Pragyan - 14-06-2012
		 	if(saleOrderWiseMapCopy != null && saleOrderWiseMapCopy.size() > 0)
			{
				System.out.println("**********1*******************");
				saleOrderWiseMap.clear();
				saleOrderWiseMap = (HashMap) saleOrderWiseMapCopy.clone();
				errString = updateWaveTask(headerDom, detailDom,lineNo, xtraParams, conn);
			}
			
			 */
			//Calling Dynamic Wave genration Map
			if(saleOrderWiseMap != null && saleOrderWiseMap.size() > 0 /*|| saleOrderWiseMap != null && saleOrderWiseMap.size() > 0*/)
			{	
				errString = updateWaveTask(headerDom, detailDom, xtraParams, conn);
			}
			
			//Changed by Rohan on 18-04-12 [WM1ESUN006] Not allocate stock is stock is manually allocate.end
			//Changed by sumit on 25/08/12 .start
			if (errString == null || errString.trim().length() == 0)
			{
				//Changed by sumit on 24/11/12 calling report label printing start.
				System.out.println(" waveMode ["+waveMode+"] printLabel ["+printLabel+"] printer ["+printer+"]");
				if( waveId != null  && waveId.trim().length() > 0 && "P".equalsIgnoreCase(waveMode) && "Y".equalsIgnoreCase(printLabel))
				{
					generatedLabelPrint(waveId,printer, conn);
				}
				//Changed by sumit on 24/11/12 calling report label printing end.
				
				if(waveId == null  || waveId.trim().length() == 0)
				{
					waveId = "1";
				}
				System.out.println(" new wave id ["+waveId+"]");
				errString = generateReport(waveId, conn);
			}
			//Changed by sumit on 25/08/12 .end
			
			if (errString != null && errString.trim().length() > 0)
			{
				System.out.println("errString ::::::::::::::::::::"+errString);
				return errString;
			}
			
					
		}//try end	
		catch(Exception e)
		{
			if ( conn != null && ! conn.isClosed() )
			{
				conn.rollback();
			}
			e.printStackTrace();
			System.out.println("Exception :StockAllocationPrcEJB :process(String xmlString2, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			errString = e.getMessage();
			//return errString ;
			throw e;
		}
		finally
		{
			System.out.println("Closing Connection....");
			try
			{
				saleOrderArr.clear();
				if(conn != null)
				{	//Changed by sumit on 01/08/12 putting condition other than process transaction will rollback start.
					/*if (errString == null || errString.trim().length() == 0)
					{
						System.out.println("SUCCESS...>>>>>>>>>>>>>>>>>>");
						conn.commit();
					} else {
						conn.rollback();
					}
					if (pstmt != null) {
						pstmt.close();
						pstmt = null;
					}
					conn.close();
					conn = null;*/
					if( pstmtSord != null )
					{
						pstmtSord.close();
						pstmtSord = null;
					}
					if( pstmt != null )
					{
						pstmt.close();
						pstmt = null;
					}
					if( rs != null )
					{
						rs.close();
						rs = null;
					}
					if ("P".equalsIgnoreCase(waveMode)) 
					{
						if (errString == null || errString.trim().length() == 0)
						{
							System.out.println("SUCCESS...>>>>>>>>>>>>>>>>>>");
							conn.commit();
						} else {
							/*int i = 0;
							while(i < savePointList.size())
							{
								Savepoint savPoint = (Savepoint)savePointList.get(i);
								if(savPoint != null)
								{
									conn.rollback(savPoint);
								}
							}*/
							conn.rollback();
						}
						if (pstmt != null) {
							pstmt.close();
							pstmt = null;
						}
						conn.close();
						conn = null;
					}
					else
					{				
						
						System.out.println("Rolling Back and Closing Connection....["+errString+"]");
						if(conn != null)
						{
							
							System.out.println("Inside Rollback Closing........................");
							conn.rollback();
							conn.close();
							conn = null;
						}
					}
					//Changed by sumit on 01/08/12 putting condition other than process transaction will rollback end.
				}
				
			}
			catch(Exception e)
			{
				errString = e.getMessage();
				e.printStackTrace();
				return errString ;
			
			}
			if (errString == null || errString.trim().length() == 0)
			{
				//Changed by sumit on 07/08/12 display massage for report generated succesfully start.
				/*errString="VTCOMPL";
				errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
				return errString;*/
				if("R".equalsIgnoreCase(waveMode))				{ 
					
					if(printMode.trim().length() == 0)
					{
						errString="PRINOTDEF";
						errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
						return errString;
					}
					else
					{
						if("JSP".equalsIgnoreCase(printMode))
						{
							errString="REPJSPCOMP";
							errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
							return errString;
						}
						else
						{
							errString="REPCOMPL";
							errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
							return errString;
						}
					}
				}
				else
				{				
					errString="VTCOMPL";
					errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
					return errString;
				}
				//Changed by sumit on 07/08/12 display massage for report generated succesfully end.
			}
			
			else
			{
				System.out.println("errString.indexOf(<Errors>)---------------"+errString.indexOf("<Errors>"));
				if(errString.indexOf("<Errors>") == -1 )
				{
					if( errString.trim().length() > 0)
					{
						System.out.println("Inside Block for ErrOr Not Found---------------");
						errString="VTPRCERR";
						errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
					}
				}
				
				return errString;
				
			}
			
		}
	
	}

	//Changed by sumit sarkar on 23/08/11 [ WM1ESUN006 ] to make compitable to call updateWaveTask() method.
	//private String sorderAllocate(String saleOrder, String lineNo, String itemCode, double allocQty, String expLev) throws ITMException
	private String sorderAllocate(Document headerDom, Document detailDom , String saleOrder, String lineNo, String itemCode, double allocQty,String singleLot,double pendingQty,String isActivePickChecked,String isMasterPackChecked,String isStockToDockChecked,String isParcelPickChecked, String expLev, String xtraParams, Connection conn ) throws ITMException
	{
		System.out.println("updateSOrder calling ....**************..........["+saleOrder+"]");
		String getDataSql = null;
		String sorditemSql=null;
		String itemCodeOrd = null ;
		String unitStd = null ;
		String lotSl= null;
		String lotNo = null;
		String locCode = null;
		String itemShDescr = null;
		String locDescr = null;
		String unit = null;
		String grade = null;
		String siteCodeMfg =null;
		String itemRef = null;
		String status =null;
		//Changed By Pragyan 
		String invStat = "";
		//Changed By Pragyan 18/02/13 to check previous replenishment Location.start
		String replHistStr = "";
		String prvReplID = "";
		String prvLocCodeTo = "";
		int prvReplLineNo = 0;
		String prvPickOrd = "";
		int prvPickLineNo = 0;
		String isRepl = "";
		String replQuantity = "";
		//Changed By Pragyan 18/02/13 to check previous replenishment Location.end
		//Changed by sankara on 03-08-2012 for adding Loctype
		String locType = "";
		String locTypeParent = "";
		int locZonePref = 0;
		double height = 0,len = 0,width =0,netwt=0;
		int noArt;
		java.sql.Date expDate = new java.sql.Date(System.currentTimeMillis());
		java.sql.Date mfgDate = new java.sql.Date(System.currentTimeMillis());
		java.sql.Date dateAlloc= new java.sql.Date(System.currentTimeMillis());
		String updateSorditem = null;
		String insertSql = null;
		String updateSordalloc = null;
		String updateSql= null;
		String flag = null;

		//Changed by Rohan on 29-12-11 as said by gulzar.start
		String resrvLoc  = "";
		String casePickLoc  = "";
		String activePickLoc  = "";
		String deepStoreLoc = "";//Changed By Pragyan
		String partialResrvLoc = "";
		//Changed by Rohan on 29-12-11 as said by gulzar.end
		
		double stockQuantity = 0;
		double qtyAvailAlloc = 0;
		double lotQtyToBeAllocated = 0;
		double qtyDesp =0;
		double quantity =0;
		double convQtyStduom = 0 ;
		double quantityStduom = 0 ;
		double pendingQuantity = 0;
		int intCnt=0;
		int updCnt=0;
		String orderByStkStr = "";
		String errString = "";
		String error = "";
		String errCode = "";
		//Connection conn = null;
		PreparedStatement pstmtStock = null;
		PreparedStatement pstmtStockInsertSordAlloc = null;
		//Changed by Rohan on 13-04-12 To create prepared statement & result set.start
		String manStockData = ""; 
		//PreparedStatement pstmt = null;
		ResultSet rSet = null;
		//Change by Rohan on 4/7/12 To add min_shilf_life
		String minShelf = "";
		PreparedStatement pstmtShelf = null;
		ResultSet rSetShelf = null;
		int minShelfLife = 0; 
		//Change by Rohan on 4/7/12 To add min_shilf_life
		Statement st = null;
		ResultSet rs = null ;
		ResultSet rsSItem = null;
		HashMap tempMap = null;
		ArrayList tempList = null;
		HashMap strAllocate = null;
		boolean isStockToDock = false;
		boolean isActives = false;
		ArrayList tempListForRepl =null;//Added by Ashish
		String directPickLoc = "";
		double palletVolume = 0.0 ,packSize = 0.0, perItemVolume = 0.0,
		caseVolume = 0.0,packSize1 = 0.0,caseVolume1 = 0.0,
		caseWeight =0.0,itemWeight = 0.0,caseCount =0.0;
		String hazardous = "";
		
		try
		{
			String dbDateFormat = genericUtility.getDBDateFormat();
			String applDateFormat = genericUtility.getApplDateFormat();
			java.util.Date currDate1 = new java.util.Date();
			SimpleDateFormat sdf = new SimpleDateFormat(applDateFormat);
			String currDateStr = sdf.format(currDate1);
			java.sql.Timestamp tranDate = java.sql.Timestamp.valueOf(genericUtility.getValidDateString( currDateStr , applDateFormat, dbDateFormat ) + " 00:00:00.0") ;

			siteCode = genericUtility.getColumnValue("site_code",headerDom);
			System.out.println("siteCode------>>>>"+ siteCode+"]Post Ordder Flag>>>["+postOrderFg+"]");
			
			//Changed by Rohan 29-12-11 to consider only RESERV, CASE PICK AND ACTIVE PICK LOCATIONS
			//double palletVolume  = Double.parseDouble(discommon.getDisparams("999999","PER_PALLET__VOLUME",conn));
			palletVolume  = Double.parseDouble(discommon.getDisparams("999999","PER_PALLET__VOLUME",conn));
			resrvLoc  = discommon.getDisparams("999999","RESERV_LOCATION",conn);
			casePickLoc  = discommon.getDisparams("999999","CASE_PICK_INVSTAT",conn);
			activePickLoc  = discommon.getDisparams("999999","ACTIVE_PICK_INVSTAT",conn);
			deepStoreLoc = discommon.getDisparams("999999","DEEP_STORE_INVSTAT",conn);
			partialResrvLoc = discommon.getDisparams("999999","PRSRV_INVSTAT",conn);
			directPickLoc = genericUtility.getColumnValue("direct_pick_loc",headerDom);
			System.out.println("CASE_PICK_INVSTAT"+casePickLoc+"ACTIVE_PICK_INVSTAT"+activePickLoc+"RESERV_LOCATION"+resrvLoc+"Reserve Location["+partialResrvLoc+"]");
			//Changed by Rohan 29-12-11 .end
			//Change by Rohan on 4/7/12 To add min_shilf_life.start
			minShelf = "SELECT MIN_SHELF_LIFE FROM SORDITEM WHERE SALE_ORDER = ? AND LINE_NO = ? AND EXP_LEV = ?";
			pstmtShelf = conn.prepareStatement(minShelf);
			
			pstmtShelf.setString(1,saleOrder);
			pstmtShelf.setString(2,  lineNo);
			pstmtShelf.setString(3,expLev);
			rSetShelf = pstmtShelf.executeQuery();
			if(rSetShelf.next())
			{
				minShelfLife = rSetShelf.getInt("MIN_SHELF_LIFE");
				System.out.println("minShelfLife======>"+minShelfLife);
			}
			
			if(rSetShelf != null)
			{
				rSetShelf.close();
				rSetShelf = null;
			}
			if(pstmtShelf != null)
			{
				pstmtShelf.close();
				pstmtShelf = null;
			}
			
				HashMap itmVolumeMap1 = getItemVoumeMap(itemCode,"",conn);
				/*double packSize1 = (Double)itmVolumeMap1.get("PACK_SIZE");
				double caseVolume1 = (Double)itmVolumeMap1.get("LOT_SIZE");//Items Case Volume
				 */				
				packSize1 = (Double)itmVolumeMap1.get("PACK_SIZE");
				caseVolume1 = (Double)itmVolumeMap1.get("LOT_SIZE");//Items Case Volume
				/*System.out.println("STOCK TO DOCK TRUE NoOfCases>>>>>>>>>>>>>>>>>["+isStockToDockChecked+"]");
				
				System.out.println("packSize1>>>>>>>>>>>>>>>>>["+packSize1+"]caseVolume1"+caseVolume1);
				if("Y".equalsIgnoreCase(isStockToDockChecked))
				{
					double NoOfCases = allocQty /packSize1;
					System.out.println("STOCK TO DOCK TRUE NoOfCases["+NoOfCases+"]");
					double qtyToStockToDock = NoOfCases * packSize1;
					System.out.println("STOCK TO DOCK TRUE qtyToStockToDock["+qtyToStockToDock+"]");
					
					System.out.println("STOCK TO DOCK TRUE CASE VOLUME (NoOfCases * caseVolume1)["+(NoOfCases * caseVolume1)+"]");
					
					if(NoOfCases > 0 &&  (NoOfCases * caseVolume1) <= palletVolume && ((palletVolume - (NoOfCases * caseVolume1)) < caseVolume1))  
					{
						System.out.println("STOCK TO DOCK TRUE");
						 isStockToDock = true;
					}
				}*/
				
				/*if((pendingQty % packSize1) > 0)
				{
					orderByStkStr = "ORDER BY STOCK.EXP_DATE,INVSTAT.ALLOC_PREF, STOCK.LOC_CODE ";
					if(isStockToDock)
					{
						orderByStkStr = "ORDER BY STOCK.EXP_DATE,QTY_AVAIL_ALLOC DESC,INVSTAT.ALLOC_PREF, STOCK.LOC_CODE ";
					}
					
				}
				else
				{
					orderByStkStr = "ORDER BY STOCK.EXP_DATE,INVSTAT.ALLOC_PREF, STOCK.LOC_CODE ";
					if(isStockToDock)
					{
						orderByStkStr = "ORDER BY STOCK.EXP_DATE,QTY_AVAIL_ALLOC DESC,INVSTAT.ALLOC_PREF, STOCK.LOC_CODE ";
					}
				}*/
				//Changed By Pragyan to check partial cases on Allocate Quantity.
				//if((pendingQty % packSize1) > 0)
				if(directPickLoc != null && directPickLoc.length() > 0)
				{
					orderByStkStr = "AND LOCATION.LOC_CODE IN(?) ORDER BY STOCK.EXP_DATE,INVSTAT.ALLOC_PREF, STOCK.LOC_CODE ";
				}
				else if((allocQty % packSize1) > 0 || (allocQty < packSize1))			
				{
					isActives = true;
					orderByStkStr = "AND LOCATION.INV_STAT IN(?,?,?,?,?) ORDER BY STOCK.EXP_DATE,INVSTAT.ALLOC_PREF, STOCK.LOC_CODE ";
				}
				else
				{
					isActives = false;
					orderByStkStr = "AND LOCATION.INV_STAT IN(?,?,?,?) ORDER BY STOCK.EXP_DATE,INVSTAT.ALLOC_PREF, STOCK.LOC_CODE ";
				}
				
				if(isActives && "N".equalsIgnoreCase(isActivePickChecked))
				{
					errString = getError(saleOrder,"INVORDQTY",conn);
					return errString;
				}
				
				if(directPickLoc != null && directPickLoc.length() > 0)
				{
					getDataSql = "SELECT STOCK.LOT_NO,STOCK.LOT_SL,"
						   +"STOCK.LOC_CODE, "
						   +"STOCK.UNIT,  "
						   +"(STOCK.QUANTITY - STOCK.ALLOC_QTY - (CASE WHEN STOCK.HOLD_QTY IS NULL THEN 0 ELSE STOCK.HOLD_QTY END)) AS QTY_AVAIL_ALLOC ,"
						   +"STOCK.GRADE,STOCK.EXP_DATE,STOCK.CONV__QTY_STDUOM,STOCK.QUANTITY, " 					   
						   +"STOCK.MFG_DATE,STOCK.SITE_CODE__MFG, "
						   +"STOCK.NO_ART,INVSTAT.INV_STAT,ITEM.LOC_TYPE__PARENT,ITEM.LOC_TYPE,ITEM.LOC_ZONE__PREF " 
						   +"FROM STOCK,ITEM,LOCATION,INVSTAT " 
						   +"WHERE (ITEM.ITEM_CODE = STOCK.ITEM_CODE) "
						   +"AND (LOCATION.LOC_CODE = STOCK.LOC_CODE ) "
						   +"AND (LOCATION.INV_STAT = INVSTAT.INV_STAT) "
						   +"AND INVSTAT.AVAILABLE = 'Y' "
						   +"AND STOCK.ITEM_CODE = ? AND STOCK.SITE_CODE = ? "
						   +"AND STOCK.LOT_NO IN (SELECT LOT_NO FROM STOCK WHERE ITEM_CODE =? AND SITE_CODE =? "
						   +"GROUP BY LOT_NO HAVING SUM(QUANTITY - ALLOC_QTY - (CASE WHEN STOCK.HOLD_QTY IS NULL THEN 0 ELSE STOCK.HOLD_QTY END) ) >= ?) " 
						   +"AND (MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE) > ? ) " 
				 		   +"AND NOT EXISTS (SELECT 1 FROM INV_RESTR I WHERE I.INV_STAT = INVSTAT.INV_STAT AND I.REF_SER = 'S-DSP' ) ";
						  //+"AND LOCATION.INV_STAT IN(?,?,?,?)";
						  /* //+"ORDER BY STOCK.EXP_DATE, STOCK.LOC_CODE";
						   + orderByStkStr;*/
						   //+" ORDER BY STOCK.EXP_DATE,INVSTAT.ALLOC_PREF, STOCK.LOC_CODE ";
					
					
							pstmtStock = conn.prepareStatement(getDataSql + orderByStkStr);
							pstmtStock.setString(1,itemCode);
							pstmtStock.setString(2,siteCode);
							pstmtStock.setString(3,itemCode);
							pstmtStock.setString(4,siteCode);
							pstmtStock.setDouble(5,pendingQty);
							pstmtStock.setInt(6,minShelfLife);
							pstmtStock.setString(7,directPickLoc);
							
				}
				else if ( singleLot.trim().length() > 0 && singleLot.trim().equalsIgnoreCase("Y") )
				{
					
					getDataSql = "SELECT STOCK.LOT_NO,STOCK.LOT_SL,"
						   +"STOCK.LOC_CODE, "
						   +"STOCK.UNIT,  "
						   +"(STOCK.QUANTITY - STOCK.ALLOC_QTY - (CASE WHEN STOCK.HOLD_QTY IS NULL THEN 0 ELSE STOCK.HOLD_QTY END)) AS QTY_AVAIL_ALLOC ,"
						   +"STOCK.GRADE,STOCK.EXP_DATE,STOCK.CONV__QTY_STDUOM,STOCK.QUANTITY, " 					   
						   +"STOCK.MFG_DATE,STOCK.SITE_CODE__MFG, "
						   +"STOCK.NO_ART,INVSTAT.INV_STAT,ITEM.LOC_TYPE__PARENT,ITEM.LOC_TYPE,ITEM.LOC_ZONE__PREF " 
						   +"FROM STOCK,ITEM,LOCATION,INVSTAT " 
						   +"WHERE (ITEM.ITEM_CODE = STOCK.ITEM_CODE) "
						   +"AND (LOCATION.LOC_CODE = STOCK.LOC_CODE ) "
						   +"AND (LOCATION.INV_STAT = INVSTAT.INV_STAT) "
						   +"AND INVSTAT.AVAILABLE = 'Y' "
						   +"AND STOCK.ITEM_CODE = ? AND STOCK.SITE_CODE = ? "
						   +"AND STOCK.LOT_NO IN (SELECT LOT_NO FROM STOCK WHERE ITEM_CODE =? AND SITE_CODE =? "
						   +"GROUP BY LOT_NO HAVING SUM(QUANTITY - ALLOC_QTY - (CASE WHEN STOCK.HOLD_QTY IS NULL THEN 0 ELSE STOCK.HOLD_QTY END) ) >= ?) " 
						   +"AND (MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE) > ? ) " 
				 		   +"AND NOT EXISTS (SELECT 1 FROM INV_RESTR I WHERE I.INV_STAT = INVSTAT.INV_STAT AND I.REF_SER = 'S-DSP' ) ";
						  //+"AND LOCATION.INV_STAT IN(?,?,?,?)";
						  /* //+"ORDER BY STOCK.EXP_DATE, STOCK.LOC_CODE";
						   + orderByStkStr;*/
						   //+" ORDER BY STOCK.EXP_DATE,INVSTAT.ALLOC_PREF, STOCK.LOC_CODE ";
					
					
							pstmtStock = conn.prepareStatement(getDataSql + orderByStkStr);
							pstmtStock.setString(1,itemCode);
							pstmtStock.setString(2,siteCode);
							pstmtStock.setString(3,itemCode);
							pstmtStock.setString(4,siteCode);
							pstmtStock.setDouble(5,pendingQty);
							pstmtStock.setInt(6,minShelfLife);
							pstmtStock.setString(7,resrvLoc);
							pstmtStock.setString(8,casePickLoc);
							//Changed by sumit on 29/12/12 hiding active pick if user no need from active start
							//pstmtStock.setString(9,activePickLoc);
							if( "N".equalsIgnoreCase(isActivePickChecked))
							{
								pstmtStock.setString(9,"");
							}
							else
							{
								pstmtStock.setString(9,activePickLoc);
							}
							//Changed by sumit on 29/12/12 hiding active pick if user no need from active end
							pstmtStock.setString(10,deepStoreLoc);
							
							if(isActives)
							{
								pstmtStock.setString(11,partialResrvLoc);
							}
				}
				else
				{
					
					getDataSql = "SELECT STOCK.LOT_NO,STOCK.LOT_SL,"
						   +"STOCK.LOC_CODE, "
						   +"STOCK.UNIT,  "
						   +"(STOCK.QUANTITY - STOCK.ALLOC_QTY - (CASE WHEN STOCK.HOLD_QTY IS NULL THEN 0 ELSE STOCK.HOLD_QTY END)) AS QTY_AVAIL_ALLOC ,"
						   +"STOCK.GRADE,STOCK.EXP_DATE,STOCK.CONV__QTY_STDUOM,STOCK.QUANTITY, " 
						   //Changed By Pragyan
						   // +"STOCK.MFG_DATE,STOCK.SITE_CODE__MFG "
						   +"STOCK.MFG_DATE,STOCK.SITE_CODE__MFG, "
						   +"STOCK.NO_ART,INVSTAT.INV_STAT,ITEM.LOC_TYPE__PARENT,ITEM.LOC_TYPE,ITEM.LOC_ZONE__PREF "  //Changes done by chandni 08-06-12(instead of loc_type, loc_type__parent should be selected)
						   +"FROM STOCK,ITEM,LOCATION,INVSTAT " 
						   +"WHERE (ITEM.ITEM_CODE = STOCK.ITEM_CODE) "
						   +"AND (LOCATION.LOC_CODE = STOCK.LOC_CODE ) "
						   +"AND (LOCATION.INV_STAT = INVSTAT.INV_STAT) "
						   +"AND INVSTAT.AVAILABLE = 'Y' "
						   +"AND STOCK.ITEM_CODE = ? AND STOCK.SITE_CODE = ? "
						   +"AND (STOCK.QUANTITY - STOCK.ALLOC_QTY - CASE WHEN STOCK.HOLD_QTY IS NULL THEN 0 ELSE STOCK.HOLD_QTY END) > 0  " // 25/06/12 manoharan 
						   +"AND (MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE) > ? ) " //Change by Rohan on 4/7/12
				 		   +"AND NOT EXISTS (SELECT 1 FROM INV_RESTR I WHERE I.INV_STAT = INVSTAT.INV_STAT AND I.REF_SER = 'S-DSP' ) ";
						   //+"AND LOCATION.INV_STAT IN(?,?,?)"//Changed by Rohan on 29-12-11 to consider only RESERV, CASE PICK AND ACTIVE PICK LOCATIONS
				 		  // +"AND LOCATION.INV_STAT IN(?,?,?,?)"//Changed by Rohan on 29-12-11 to consider only RESERV, CASE PICK AND ACTIVE PICK LOCATIONS
						  /* //+"ORDER BY EXP_DATE, CREA_DATE";//Gulzar on 12/28/2011
				 		  // +"ORDER BY STOCK.EXP_DATE, STOCK.LOC_CODE";//Pragyan on 14/08/2012
				 		   + orderByStkStr;*/
				 		  //+" ORDER BY STOCK.EXP_DATE,INVSTAT.ALLOC_PREF, STOCK.LOC_CODE ";
					
							pstmtStock = conn.prepareStatement(getDataSql + orderByStkStr);
							
							pstmtStock.setString(1,itemCode);
							pstmtStock.setString(2,siteCode);
							pstmtStock.setInt(3,minShelfLife);
							pstmtStock.setString(4,resrvLoc);
							pstmtStock.setString(5,casePickLoc);
							//Changed by sumit on 29/12/12 hiding active pick if user no need from active start
							//pstmtStock.setString(6,activePickLoc);
							if( "N".equalsIgnoreCase(isActivePickChecked))
							{
								pstmtStock.setString(6,"");
							}
							else
							{
								pstmtStock.setString(6,activePickLoc);
							}
							//Changed by sumit on 29/12/12 hiding active pick if user no need from active end
							pstmtStock.setString(7,deepStoreLoc);
							
							if(isActives)
							{
								pstmtStock.setString(8,partialResrvLoc);
							}
				}
					
			
			
			
			//Change by Rohan on 7/4/12 for min shelf flag.end
			rs = pstmtStock.executeQuery();
			System.out.println("siteCode------"+ siteCode);
			System.out.println("itemCode------"+ itemCode);
			System.out.println("Select completed");
			//String resvDisparam = checkNull(discommon.getDisparams("999999","RESERV_LOCATION",conn));

			while(rs.next())
			{
				isStockToDock = false;
				System.out.println( "INSIDE WHILE LOOP.............");
				//LOT_NO
				lotNo = rs.getString(1);
				//LOT_SL
				lotSl = rs.getString(2);
				//LOC_CODE
				locCode = rs.getString(3);
				//UNIT
				unit = rs.getString(4);
				//QTY_AVAIL_ALLO
				qtyAvailAlloc = rs.getDouble(5);
				System.out.println("qtyAvailAlloc--->"+qtyAvailAlloc);
				//GRADE
				grade = rs.getString(6);
				//EXP_DATE
				expDate =rs.getDate(7);
				//CONV__QTY_STDUOM
				convQtyStduom=rs.getDouble(8);
				//QUANTITY
				quantity= rs.getDouble(9);
				//MFG_DATE
				mfgDate = rs.getDate(10);
				//SITE_CODE__MFG
				siteCodeMfg = rs.getString(11);
				noArt = rs.getInt(12);
				invStat = rs.getString(13);
				locTypeParent = checkNull(rs.getString(14)); //Changes done by chandni 08-06-12(instead of loc_type, loc_type__parent should be selected)
				//Changed by sankara on 03-08-2012 for adding locType
				locType= rs.getString(15);
				locZonePref = rs.getInt(16);
				/*
				invallocTrace.setRefSer("S-ALC");
				invallocTrace.setRefId(saleOrder);
				invallocTrace.setRefLine(lineNo);
				invallocTrace.setSiteCode(siteCode);
				invallocTrace.setItemCode(itemCode);
				invallocTrace.setLocCode(locCode);
				invallocTrace.setLotNo(lotNo);
				invallocTrace.setLotSl(lotSl);
				*/
				/*@shish */
				//Changed by Rohan on 8/2/12 to get packsize of item.start
				HashMap itmVolumeMap = getItemVoumeMap(itemCode,lotNo,conn);
				double packSizeActive = (Double)itmVolumeMap.get("PACK_SIZE");
				//Changed by Rohan on 8/2/12 to get packsize of item.end
				System.out.println("GOING FOR populateReplHistory************************");
				//Chnaged by Rohan on 8/3/12 to update pnd location in active replanishement.start
				//populateReplHistory(itemCode,siteCode,lotNo,lotSl,locCode,conn);
				//Changed by rohan on 7/8/12 to adjust Stock Quantity.end
				//Changed by Rohan on 14-02-13 for not call adjustAvailableQty in case of prsv
				System.out.println("Return qty from function:::::"+qtyAvailAlloc);
				
				//Changed by Rohan on 14-02-13 for not call adjustAvailableQty.start
				//qtyAvailAlloc = adjustAvailableQty(itemCode,siteCode,lotNo,lotSl,locCode,qtyAvailAlloc,conn);
				/*
				if(!invStat.trim().equalsIgnoreCase(partialResrvLoc.trim()))
				{	
					qtyAvailAlloc = adjustAvailableQty(itemCode,siteCode,lotNo,lotSl,locCode,qtyAvailAlloc,conn);
				}
				*/	
				System.out.println("Return qty from function"+qtyAvailAlloc);
				//Changed by Rohan on 14-02-13 for not call adjustAvailableQty .end
								
				/*
				if(allocQty < packSizeActive)
				{
					activeRepl = true;
				}
				
				populateReplHistory(itemCode,siteCode,lotNo,lotSl,locCode,activeRepl,conn);
				System.out.println("END FOR populateReplHistory************************");
				Map tempMapReplenishment =new HashMap();
				String lastReplenishmentID="",locCodeTo="";
				int lineNoRepl=0;
				
				if(itemInfoMapForRepl.containsKey(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode))
				{
					ArrayList tempListTestForRepl = (ArrayList)itemInfoMapForRepl.get(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode);
					System.out.println("@@@@ Item Alredy exist in Map");
					System.out.println("@@@@ Existing List for "+itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode+" In Map::[ "+tempListTestForRepl.toString()+" ]");
                }
                else
                {
                	System.out.println("Enter in ELSE");
                	tempListForRepl  = new ArrayList();
                	qtyActual=0.0;
                	//Changed by Rohan on 8/2/12 to set qtyAvailAlloc in case of active.start
                	//tempMapReplenishment.put("QTY_AVAIL",qtyAvailAlloc);
                	System.out.println("allocQty>>>"+allocQty+"packSizeActive>>>>>>>"+packSizeActive);
                	
                	if(allocQty < packSizeActive)
                	{
                		tempMapReplenishment.put("QTY_AVAIL",packSizeActive);
           
                	}
                	
                	else
                	{	
                		tempMapReplenishment.put("QTY_AVAIL",qtyAvailAlloc);
                	}	
    				tempMapReplenishment.put("QTY_ACTUAL", qtyActual);
    				tempMapReplenishment.put("LAST_REPL_ID", lastReplenishmentID);
    				tempMapReplenishment.put("REPL_LINE_NO", lineNoRepl);
    				tempMapReplenishment.put("REPL_LOC_TO",locCodeTo);
    				tempMapReplenishment.put("IS_REPLAINSH","Y");
    				System.out.println("REPL_LOC_TO@@@@@@@@@@@@@"+locCodeTo);
    				
    				tempListForRepl.add(tempMapReplenishment);
    				
    				itemInfoMapForRepl.put(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode, tempListForRepl);
    				System.out.println("itemInfoMapForReplPPPPPPPPPPPPPPPPPPP"+itemInfoMapForRepl);
                }*/
				
				
				
				
				/*Ashish */
				System.out.println("allocQty"+allocQty+"qtyAvailAlloc:::"+qtyAvailAlloc);
				if (allocQty >= qtyAvailAlloc)
				{
					lotQtyToBeAllocated = qtyAvailAlloc;
					
					//Changed By Pragyan 09/11/12 To make the stock to dock if avilable quantity less then or equal to required quantity(only reserve locatio).start
					invStat = invStat != null?invStat.trim():"";
					if((invStat.equalsIgnoreCase(resrvLoc) || invStat.equalsIgnoreCase(deepStoreLoc)) && (lotQtyToBeAllocated > packSizeActive) && "Y".equalsIgnoreCase(isStockToDockChecked))
					{
						isStockToDock = true;
					}
					//Changed By Pragyan 09/11/12 To make the stock to dock if avilable quantity less then or equal to required quantity(only reserve locatio).end
				}
				else
				{
					System.out.println("Enetr in else");
					lotQtyToBeAllocated = allocQty;
				}
				//invallocTrace.setAllocQty(lotQtyToBeAllocated);	
				//	
								
				allocQty -= lotQtyToBeAllocated ;
				
				System.out.print("AllocQty = " + lotQtyToBeAllocated);
				System.out.print("AllocQty2 = " + allocQty);
				if (lotQtyToBeAllocated > 0) 
				{
					
					
					
					populateReplHistory(itemCode,siteCode,lotNo,lotSl,locCode,conn);
					Map tempMapReplenishment =new HashMap();
					String lastReplenishmentID="",locCodeTo="";
					int lineNoRepl=0;
					replHistStr = "";prvReplID = "";prvLocCodeTo = "";prvPickOrd = "";isRepl = "";replQuantity = "";
					prvReplLineNo = 0;prvPickLineNo = 0;
					
					invStat = invStat != null?invStat.trim():"";
					//Changed by Rohna on 14-02-13 to add stock qtantity in map in case of partial reserv location
					//if((invStat.equalsIgnoreCase(resrvLoc) || invStat.equalsIgnoreCase(deepStoreLoc)) && (lotQtyToBeAllocated >= packSizeActive) )
					System.out.println("invStatLLLL___>"+invStat);
					if(((invStat.equalsIgnoreCase(resrvLoc) || invStat.equalsIgnoreCase(deepStoreLoc)) && (lotQtyToBeAllocated >= packSizeActive)) || invStat.equalsIgnoreCase(partialResrvLoc))
					{
						System.out.println("Inside For Creating Repelnishment packSizeActive["+packSizeActive+"]lotQtyToBeAllocated["+lotQtyToBeAllocated+"]");
					
						if(itemInfoMapForRepl.containsKey(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode))
						{
							isStockToDock = false;
							//Changed By Pragyan 18/02/13 to check previous replenishment Location for sorting before the wave.start
							/*ArrayList tempListTestForRepl = (ArrayList)itemInfoMapForRepl.get(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode);
							locCodeTo = (String)((HashMap)tempListTestForRepl.get(0)).get("REPL_LOC_TO");*/
							System.out.println("Replenishment str for ["+quantity+"]");
							replHistStr = checkForReplenishment(itemCode, siteCode, lotNo, lotSl, locCode, lotQtyToBeAllocated, 2, conn);
							System.out.println("Replenishment str for this ["+replHistStr+"]");
							StringTokenizer stReplQtyID = new StringTokenizer(replHistStr, ":");
							
							while(stReplQtyID.hasMoreTokens())
							{
								isRepl = stReplQtyID.nextToken();
								if("Y".equalsIgnoreCase(isRepl))
								{
									replQuantity = stReplQtyID.nextToken();
								}
								else if("N".equalsIgnoreCase(isRepl))
								{
									prvReplID = stReplQtyID.nextToken();
									prvLocCodeTo = stReplQtyID.nextToken();
									prvReplLineNo = Integer.parseInt(stReplQtyID.nextToken());
									prvPickOrd = stReplQtyID.nextToken();
									prvPickLineNo = Integer.parseInt(stReplQtyID.nextToken());
								}
							}
							locCodeTo = prvLocCodeTo;
							//Changed By Pragyan 18/02/13 to check previous replenishment Location for sorting before the wave.end
							
							//Changed By Pragyan 19/02/13 change of logic for replenishments to get suggested location from current wave.start
							if(locCodeTo == "" && locCodeTo.length() <= 0)
							{
								System.out.println("Block for replenishment exist location blak ["+locCodeTo+"]");
								ArrayList tempItemInfoList = (ArrayList) itemInfoMapForRepl.get(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode);
								
								Iterator itemIterator= tempItemInfoList.iterator();
								
								while(itemIterator.hasNext())
								{
									 HashMap itemSitemap = (HashMap)itemIterator.next(); 
 								     if(itemSitemap.containsKey("SUGG_LOC_TO"))
									 {
 								    	locCodeTo= (String)itemSitemap.get("SUGG_LOC_TO");
 								    	System.out.println("Suggested Location code For current wave ["+locCodeTo+"]");
									 }
								}
							}
							//Changed By Pragyan 19/02/13 change of logic for replenishments to get suggested location from current wave.end
							System.out.println("Location Code To Found as Replenishment Exist ["+locCodeTo+"]");
		                }
		                else
		                {
		                	tempListForRepl  = new ArrayList();
		                	qtyActual=0.0;      
		                	//Changed By Pragyan 19/02/13 change of logic for replenishments.start
		                	System.out.println("prevsLocCode ["+prevsLocCode+"]");
		                	System.out.println("Location Code To Found To Create Replenishment  Before ["+locCodeTo+"]");
		                	if(!isStockToDock)
		                	{
		                	
			                	ArrayList locCodeToList = getAvilableCasePickLocationList("C", conn, locType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
			                	
			                	int suggestLocLen = locCodeToList.size();
			                	if( suggestLocLen > 0) 
			                	{
			                		    int prvLocIndex = locCodeToList.indexOf(prevsLocCode);
			                			if( prvLocIndex != -1 && (prvLocIndex + 1) < suggestLocLen)
			                			{
			                				locCodeTo = (String)locCodeToList.get((prvLocIndex + 1));
			                				System.out.println("Inside prevsLocCode1 ["+locCodeTo+"]");
			                			}
			                			else
			                			{
			                				locCodeTo = (String)locCodeToList.get(0);
			                				System.out.println("Inside prevsLocCode2 ["+locCodeTo+"]");
			                			}
			                	}
			                	
			                	prevsLocCode = locCodeTo;
		                	}
		                	//Changed By Pragyan 19/02/13 change of logic for replenishments.end
		                	
		                	
		                	
		                	if(lotQtyToBeAllocated < packSizeActive)
		                	{
		                		tempMapReplenishment.put("QTY_AVAIL",packSizeActive);
		                	}
		                	else
		                	{	
		                		tempMapReplenishment.put("QTY_AVAIL",qtyAvailAlloc);
		                	}
		                	
		    				tempMapReplenishment.put("QTY_ACTUAL", qtyActual);
		    				tempMapReplenishment.put("LAST_REPL_ID", lastReplenishmentID);
		    				tempMapReplenishment.put("REPL_LINE_NO", lineNoRepl);
		    				//Changed By Pragyan 19/02/13 change of logic for replenishments location code set as it is.start
		    				//tempMapReplenishment.put("REPL_LOC_TO",locCodeTo);
		    				tempMapReplenishment.put("REPL_LOC_TO","");
		    				tempMapReplenishment.put("SUGG_LOC_TO",locCodeTo);
		    				//Change by Rohan on 26/08/12 to remove flag
		    				//tempMapReplenishment.put("IS_REPLAINSH","Y");
		    				//Changed by rohan to add stock quantity in list
		    				tempMapReplenishment.put("STOCK_QTY",qtyAvailAlloc);
		    				tempListForRepl.add(tempMapReplenishment);
		    				itemInfoMapForRepl.put(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode, tempListForRepl);
		    				System.out.println("itemInfoMapForReplPPPPPPPPPPPPPPPPPPP"+itemInfoMapForRepl.toString());
		    				
		    				/*System.out.println("prevsLocCode ["+prevsLocCode+"]");
		                	System.out.println("Location Code To Found To Create Replenishment  Before ["+locCodeTo+"]");
		                	ArrayList locCodeToList = getAvilableCasePickLocationList("C", conn, locType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
		                	
		                	int suggestLocLen = locCodeToList.size();
		                	if( suggestLocLen > 0) 
		                	{
		                		    int prvLocIndex = locCodeToList.indexOf(prevsLocCode);
		                			if( prvLocIndex != -1 && (prvLocIndex + 1) < suggestLocLen)
		                			{
		                				locCodeTo = (String)locCodeToList.get((prvLocIndex + 1));
		                				System.out.println("Inside prevsLocCode1 ["+locCodeTo+"]");
		                			}
		                			else
		                			{
		                				locCodeTo = (String)locCodeToList.get(0);
		                				System.out.println("Inside prevsLocCode2 ["+locCodeTo+"]");
		                			}
		                	}*/
		                	
		                	//prevsLocCode = locCodeTo;
		                	
		                	System.out.println("Location Code To Found To Create Replenishment  After ["+locCodeTo+"]");
		                }
					}
					
					System.out.println("Finally  Loc Code["+locCode+"]Loc Code To["+locCodeTo+"]");
					
					strAllocate = new HashMap();
					strAllocate.put("tran_date",tranDate);
					strAllocate.put("ref_ser","S-ALC");
					strAllocate.put("ref_id",saleOrder);
					strAllocate.put("ref_line", "" + lineNo);
					strAllocate.put("site_code",siteCode);
					strAllocate.put("item_code",itemCode);
					strAllocate.put("loc_code",locCode);
					strAllocate.put("lot_no",lotNo);
					strAllocate.put("lot_sl",lotSl);
					strAllocate.put("alloc_qty",new Double(lotQtyToBeAllocated));
					strAllocate.put("chg_user",GenericUtility.getInstance().getValueFromXTRA_PARAMS(xtraParams,"loginCode"));
					strAllocate.put("chg_term",GenericUtility.getInstance().getValueFromXTRA_PARAMS(xtraParams,"termId"));
					strAllocate.put("chg_win","W_WAVEGEN");

					
					/*if("2".equalsIgnoreCase(lineNo.trim()))
					{
						
						minShelf = "select SCM_INVALLOC_TRACE.nextval as TRACENo from dual";
						pstmtShelf = conn.prepareStatement(minShelf);
						ResultSet invR = pstmtShelf.executeQuery();
						if(invR.next())
						{
							System.out.println("CURRENT Sequance No ["+invR.getInt("TRACENO")+"]");
							conn.rollback();
							errString = getError(saleOrder,"TEST",conn);
							return errString;
						}
					}*/
					
					errString = invAllocTrace.updateInvallocTrace(strAllocate, conn);
					
					
					System.out.println("errString ::: " + errString);
					if (errString != null && errString.trim().length() > 0 )
					{
						break;
					}
					strAllocate = null;
					// end 16/10/11 manoharan allocation stock for new location
					// 16/10/11 manoharan update sordalloc
					//errString = updateInvallocTrace(invallocTrace);
				
					if (!saleOrderArr.contains(saleOrder))
					{
						saleOrderArr.add(saleOrderArr.size() , saleOrder);
					}
					sorditemSql = "SELECT ITEM_CODE,ITEM_CODE__ORD,UNIT, QTY_DESP, ITEM_REF,"
								+" QUANTITY - QTY_DESP PENDING_QUANTITY "
								+" FROM SORDITEM WHERE SALE_ORDER = '" + saleOrder + "' "
								+" AND LINE_NO = '" + lineNo + "' "
								+" AND EXP_LEV = '" + expLev + "' ";
					System.out.println("sorditemSql:::"+sorditemSql);
					st = conn.createStatement();
					rsSItem = st.executeQuery(sorditemSql);
					if (rsSItem.next())
					{
						//ITEM_CODE
						itemCode = rsSItem.getString(1);
						System.out.println("itemCode::::"+ itemCode);
						//ITEM_CODE__ORD
						itemCodeOrd = rsSItem.getString(2);	
						//UNIT
						unitStd = rsSItem.getString(3);	
						//QTY_DESP
						qtyDesp = 0;
						//ITEM_REF
						itemRef = rsSItem.getString(5);	
						//PENDING_QUANTITY
						pendingQuantity = rsSItem.getDouble(6);
					}					
					rsSItem.close();
						
					//Changed by sumit on 31/01/13 changing below quantity as per unit start
					pendingQuantity = getStockQtyAfterConvert(saleOrder, lineNo, itemCodeOrd, pendingQuantity, 1, conn);					
					//Changed by sumit on 14/02/13 commented this , no need now as per manoharan sir aty_allow value as per stock unit start
					/*double newQuantity = 0.0;
					newQuantity = getStockQtyAfterConvert(saleOrder, lineNo, itemCodeOrd, lotQtyToBeAllocated, 2, conn);*/	
					//Changed by sumit on 14/02/13 commented this , no need now as per manoharan sir aty_allow value as per stock unit end
					//Changed by sumit on 31/01/13 changing below quantity as per unit end
					
					//Changed by sumit on 01/02/13 updating converted quantity 
					//updateSorditem ="UPDATE SORDITEM  SET QTY_ALLOC = CASE WHEN QTY_ALLOC IS NULL THEN 0 ELSE QTY_ALLOC END  +   " + new Double(lotQtyToBeAllocated).toString()
					//Changes done by sumit on 14/02/13 reverting previous code
					//updateSorditem ="UPDATE SORDITEM  SET QTY_ALLOC = CASE WHEN QTY_ALLOC IS NULL THEN 0 ELSE QTY_ALLOC END  +   " + new Double(newQuantity).toString()
					updateSorditem ="UPDATE SORDITEM  SET QTY_ALLOC = CASE WHEN QTY_ALLOC IS NULL THEN 0 ELSE QTY_ALLOC END  +   " + new Double(lotQtyToBeAllocated).toString()
								   +" WHERE SALE_ORDER = '" + saleOrder + "' "
								   +" AND LINE_NO = '" + lineNo + "' "
								   +" AND EXP_LEV = '" + expLev + "' ";
							  
					System.out.println("updateSql------->"+updateSorditem);
					st.executeUpdate(updateSorditem);
					System.out.println("UPDATE  SUCCESS FOR SORDITEM....>>>>>>>>");
					
					sorditemSql = "SELECT COUNT(1) FROM SORDALLOC " 
								+ " WHERE SALE_ORDER = '" + saleOrder + "' "
								+ " AND LINE_NO = '" + lineNo + "' "
								+ " AND EXP_LEV = '" + expLev + "' "
								+ " AND ITEM_CODE__ORD = '" + itemCodeOrd + "' "
								+ " AND ITEM_CODE = '" + itemCode + "' "
								+ " AND LOT_NO = '" + lotNo + "' "
								+ " AND LOT_SL = '" + lotSl + "' "
								+ " AND LOC_CODE = '" + locCode + "' " ;
					rsSItem =  st.executeQuery(sorditemSql);
					int count = 0 ;
					if (rsSItem.next())
					{
						count = rsSItem.getInt(1);
					}
					if (count > 0 )
					{
						//updateSql = "UPDATE SORDALLOC SET QTY_ALLOC =  QTY_ALLOC + " + new Double(lotQtyToBeAllocated).toString()
						updateSql = "UPDATE SORDALLOC SET WAVE_FLAG = 'Y' , QTY_ALLOC =  QTY_ALLOC + " + new Double(lotQtyToBeAllocated).toString()
								  + " WHERE SALE_ORDER = '" + saleOrder + " ' "
								  + " AND LINE_NO = '" + lineNo + "' "
								  + " AND EXP_LEV = '" + expLev + "' "
								  + " AND ITEM_CODE__ORD = '" + itemCodeOrd + "' "
								  + " AND ITEM_CODE = '" + itemCode + "' "
								  + " AND LOT_NO = '" + lotNo + "' "
								  + " AND LOT_SL = '" + lotSl + "' "
								  + " AND LOC_CODE = '" + locCode + "' " ;
						System.out.println("updateSql:::>>>>"+ updateSql);	
						st.executeUpdate(updateSql);
						System.out.println("UPDATE  SUCCESS FOR SORDALLOC....");
					}
					else
					{
						insertSql ="INSERT INTO SORDALLOC (SALE_ORDER,LINE_NO,EXP_LEV,ITEM_CODE__ORD,SITE_CODE ,"
								  +"ITEM_CODE,QUANTITY ,LOT_NO, LOT_SL, LOC_CODE, UNIT, QTY_ALLOC,"
								  +"ITEM_REF, DATE_ALLOC, STATUS,ITEM_GRADE, EXP_DATE, ALLOC_MODE, "
								  +" CONV__QTY_STDUOM, UNIT__STD, QUANTITY__STDUOM, "
								  //+"MFG_DATE, SITE_CODE__MFG ) "
								  +"MFG_DATE, SITE_CODE__MFG,WAVE_FLAG ) "
								  +"VALUES ( ?, ? , ? , ? , ? , ? , ? , ? , ? , ? , ? , ? ,"
								  //+" ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) " ;
								  +" ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ) " ;
											
						pstmtStockInsertSordAlloc = conn.prepareStatement(insertSql);
								
						System.out.println("Insert Sql :"+ insertSql );
						//SALE_ORDER
						pstmtStockInsertSordAlloc.setString(1, saleOrder);
						System.out.println("saleOrder------->"+saleOrder);
						//LINE_NO
						pstmtStockInsertSordAlloc.setString(2, lineNo);
						System.out.println("lineNo------->"+lineNo);
						//EXP_LEV
						pstmtStockInsertSordAlloc.setString(3, expLev);
						System.out.println("EXP_LEV------->"+expLev);
						//ITEM_CODE__ORD
						pstmtStockInsertSordAlloc.setString(4, itemCodeOrd);
						System.out.println("itemCode------->"+itemCodeOrd);
						//SITE_CODE
						pstmtStockInsertSordAlloc.setString(5, siteCode);
						System.out.println("siteCode------->"+siteCode);
						//ITEM_CODE
						pstmtStockInsertSordAlloc.setString(6, itemCode);
						System.out.println("itemCode------->"+itemCode);
						//QUANTITY***** set pending qty
						pstmtStockInsertSordAlloc.setDouble(7, pendingQuantity);
						System.out.println("pendingQuantity------->"+pendingQuantity);
						//LOT_NO
						pstmtStockInsertSordAlloc.setString(8, lotNo);
						System.out.println("lotNo------->"+lotNo);
						//LOT_SL
						pstmtStockInsertSordAlloc.setString(9, lotSl);
						System.out.println("lotSl------->"+lotSl);
						//LOC_CODE
						pstmtStockInsertSordAlloc.setString(10, locCode);
						System.out.println("locCode------->"+locCode);
						//UNIT
						pstmtStockInsertSordAlloc.setString(11, unit);
						System.out.println("unit------->"+unit);
						//QTY_ALLOC
						pstmtStockInsertSordAlloc.setDouble(12, lotQtyToBeAllocated);
						System.out.println("lotQtyToBeAllocated------->"+lotQtyToBeAllocated);
						//ITEM_REF
						pstmtStockInsertSordAlloc.setString(13,itemRef);
						System.out.println("itemRef------->"+itemRef);
						//DATE_ALLOC
						pstmtStockInsertSordAlloc.setDate(14,dateAlloc);
						System.out.println("dateAlloc------->"+dateAlloc);
						//STATUS
						pstmtStockInsertSordAlloc.setString(15,"P");
						System.out.println("status------->P");
						//ITEM_GRADE
						pstmtStockInsertSordAlloc.setString(16,grade);
						System.out.println("grade------->"+grade);
						//EXP_DATE
						pstmtStockInsertSordAlloc.setDate(17,expDate);
						System.out.println("expDate------->"+expDate);
						//Changed By Pragyan 07/03/13
						//ALLOC_MODE
						//pstmtStockInsertSordAlloc.setString(18,"M");
						pstmtStockInsertSordAlloc.setString(18,"W");
						//CONV__QTY_STDUOM
						pstmtStockInsertSordAlloc.setDouble(19,convQtyStduom);
						System.out.println("convQtyStduom------->"+convQtyStduom);
						//UNIT__STD
						pstmtStockInsertSordAlloc.setString(20,unitStd);
						System.out.println("unitStd------->"+unitStd);
						
						quantityStduom = convQtyStduom * lotQtyToBeAllocated ;
						//QUANTITY__STDUOM
						pstmtStockInsertSordAlloc.setDouble(21,quantityStduom);
						System.out.println("quantityStduom------->"+quantityStduom);
						//MFG_DATE
						pstmtStockInsertSordAlloc.setDate(22,mfgDate);
						System.out.println("mfgDate------->"+mfgDate);
						//SITE_CODE__MFG
						pstmtStockInsertSordAlloc.setString(23,siteCodeMfg);
						System.out.println("siteCodeMfg------->"+siteCodeMfg);
						pstmtStockInsertSordAlloc.setString(24,"Y");
						System.out.println("WAVE FLAG-------> Y");
						//QTY_DESP
						
						intCnt = pstmtStockInsertSordAlloc.executeUpdate();
						System.out.println("insertion  success ...............>>>>>>>>");
						pstmtStockInsertSordAlloc.close();
					}//end else
					st.close();
					
					System.out.println("invStat=["+invStat+"]");
					System.out.println("resvDisparam=["+resrvLoc+"]");
					/*
					 
					 if(invStat != null && invStat.trim().equalsIgnoreCase(resrvLoc.trim()))
					{
						double palletVolume  = Double.parseDouble(discommon.getDisparams("999999","PER_PALLET__VOLUME",conn));
						HashMap itmVolumeMap = getItemVoumeMap(itemCode,lotNo,conn);
						double packSize = (Double)itmVolumeMap.get("PACK_SIZE");//How many item contains in the Case
						double perItemVolume = (Double)itmVolumeMap.get("ITEM_SIZE");//Each Item Volume
						double caseVolume = (Double)itmVolumeMap.get("LOT_SIZE");//Items Case Volume
						double caseWeight = (Double)itmVolumeMap.get("PACK_WEIGHT");
						double itemWeight = (Double)itmVolumeMap.get("ITEM_WEIGHT");
						double caseCount = lotQtyToBeAllocated /packSize;
						
						if(caseCount > 0 &&  (caseCount * caseVolume) <= palletVolume && ((palletVolume - (caseCount * caseVolume)) < caseVolume))  
						 {
							 isStockToDock = true;
						 }
						 else if((lotQtyToBeAllocated * perItemVolume) <= palletVolume &&  ((palletVolume - (lotQtyToBeAllocated * perItemVolume)) < perItemVolume))
						 {
							 isStockToDock = true;
						 }
										
					}
					*/
					// as par manoharan sir allow stock to doc from any location - 06/06/12		
					//double palletVolume  = Double.parseDouble(discommon.getDisparams("999999","PER_PALLET__VOLUME",conn));
					//Changed by Rohan on 2/8/12 to call itmVolumeMap earlier
					//HashMap itmVolumeMap = getItemVoumeMap(itemCode,lotNo,conn);
					//Changed By Pragyan 12/03/13 to declare the veriables above .start
					/*double packSize = (Double)itmVolumeMap.get("PACK_SIZE");//How many item contains in the Case
					double perItemVolume = (Double)itmVolumeMap.get("ITEM_SIZE");//Each Item Volume
					double caseVolume = (Double)itmVolumeMap.get("LOT_SIZE");//Items Case Volume
					double caseWeight = (Double)itmVolumeMap.get("PACK_WEIGHT");
					double itemWeight = (Double)itmVolumeMap.get("ITEM_WEIGHT");
					double caseCount = lotQtyToBeAllocated /packSize;*/
					packSize = (Double)itmVolumeMap.get("PACK_SIZE");//How many item contains in the Case
					perItemVolume = (Double)itmVolumeMap.get("ITEM_SIZE");//Each Item Volume
					caseVolume = (Double)itmVolumeMap.get("LOT_SIZE");//Items Case Volume
					caseWeight = (Double)itmVolumeMap.get("PACK_WEIGHT");
					itemWeight = (Double)itmVolumeMap.get("ITEM_WEIGHT");
					hazardous = (String)itmVolumeMap.get("HAZARDOUS");
					caseCount = lotQtyToBeAllocated /packSize;
					//Changed By Pragyan 12/03/13 to declare the veriables above .end
					//
					/*System.out.println("CASE VOLUME----->["+caseVolume+"]");
					System.out.println("CASE caseCount----->["+caseCount+"]");
					System.out.println("(caseCount * caseVolume)----->["+(caseCount * caseVolume)+"]");
					System.out.println("((palletVolume - (caseCount * caseVolume))----->["+((palletVolume - (caseCount * caseVolume)))+"]");
					
					System.out.println("to check with floor["+Math.floor((palletVolume / caseVolume))+"]");
					System.out.println("to check with Round["+Math.round((palletVolume / caseVolume))+"]");
					System.out.println("to check with ceil["+Math.ceil((palletVolume / caseVolume))+"]");
					System.out.println("to check with ["+(palletVolume / caseVolume)+"]");
					*/
					
					//Changed By Pragyan 09/11/12 To make the stock to dock avilable quantity less then or equal to required quantity(only reserve locatio).start
					/*if(caseCount > 0 &&  (caseCount * caseVolume) <= palletVolume && ((palletVolume - (caseCount * caseVolume)) < caseVolume))  
					 {
						System.out.println("STOCK TO DOCK TRUE===============================");
						 isStockToDock = true;
					 }
					 else if((lotQtyToBeAllocated * perItemVolume) <= palletVolume &&  ((palletVolume - (lotQtyToBeAllocated * perItemVolume)) < perItemVolume))
					 {
						 System.out.println("STOCK TO DOCK TRUE----->");
						 isStockToDock = true;
					 }*/
					//Changed By Pragyan 09/11/12 To make the stock to dock avilable quantity less then or equal to required quantity(only reserve locatio).end
					
					
					//Changed By Pragyan.start
					if(saleOrderWiseMap.containsKey(saleOrder+":"+locTypeParent))
                    {
                       // tempList = (ArrayList)saleOrderWiseMap.get(saleOrder);
						//tempList = (ArrayList)saleOrderWiseMap.get(saleOrder+":"+locType);
						tempList = (ArrayList)saleOrderWiseMap.get(saleOrder+":"+locTypeParent); //Changes done by chandni 08-06-12(instead of loc_type, loc_type__parent should be selected)
                    }
                    else
                    {
                        tempList  = new ArrayList();
                    }
	                // populate the map with the stock keys
                    tempMap = new HashMap();
                    
                    tempMap.put("site_code", siteCode);
                    tempMap.put("item_code", itemCode);
                    tempMap.put("loc_code", locCode);
                    tempMap.put("lot_no", lotNo);
                    tempMap.put("lot_sl", lotSl);
                    tempMap.put("no_art", String.valueOf(noArt));
                    tempMap.put("alloc_qty", lotQtyToBeAllocated);
                    tempMap.put("inv_stat", invStat);
                    //tempMap.put("loc_type", locType);
                   // tempMap.put("loc_type", locTypeParent); //Changes done by chandni 08-06-12(instead of loc_type, loc_type__parent should be selected)
                    //changed by sankara on 03-08-2012 for adding LocType
                    tempMap.put("loc_type", locType);
                    tempMap.put("loc_type_parent", locTypeParent);
                    tempMap.put("loc_zone_pref", locZonePref);
                    
                    if(isStockToDock)
                    {
                    	tempMap.put("stock2_dock", "Y");
                    	 System.out.println("STOCK TO DOCK TRUE----YYY->");
                    }
                    else
                    {
                    	tempMap.put("stock2_dock", "N");
                    	System.out.println("STOCK TO DOCK TRUE----NNNN->");
                    }
                    tempMap.put("master_pack", isMasterPackChecked);
                    tempMap.put("active_pick", isActivePickChecked);
                    tempMap.put("parcel_pick", isParcelPickChecked);
                    tempMap.put("exp_lev", expLev);
                    //Changed By Pragyan add the pack_size in the map.
                    tempMap.put("pack_size", packSize);
                    tempMap.put("sord_lineNo", lineNo);
                    tempMap.put("item_weight", itemWeight);
                    locCodeTo = locCodeTo != null && locCodeTo.length() > 0 ?locCodeTo:locCode;
                    tempMap.put("sugg_loc", locCodeTo);
                    //Changed By Pragyan 12/03/13 To add hazardous 
                    tempMap.put("hazard", hazardous);
                    tempList.add(tempMap);
                    //saleOrderWiseMap.put(saleOrder,tempList);
                    //saleOrderWiseMap.put(saleOrder+":"+locType,tempList);
                    System.out.println("Current Key For The insertion>>>>>["+saleOrder+":"+locTypeParent+"]Templist size["+tempList.size()+"]");
                    saleOrderWiseMap.put(saleOrder+":"+locTypeParent,tempList); //Changes done by chandni 08-06-12(instead of loc_type, loc_type__parent should be selected)
                    System.out.println("Printing size of saleOrderWiseMap["+saleOrderWiseMap.size()+"]");
                    System.out.println("Printing keyset of saleOrderWiseMap["+saleOrderWiseMap.keySet()+"]");
                   	//Changed By Pragyan.end
			
				}//end of if(lotQtyToBeAllocated > 0)
			}//end of while
			
			if(st != null)
			{
				st.close();
				st = null;
			}
			if(pstmtStock != null)
			{
				pstmtStock.close();
				pstmtStock = null;
			}
			if(pstmtStockInsertSordAlloc != null)
			{
				pstmtStockInsertSordAlloc.close();
				pstmtStockInsertSordAlloc = null;
			}
			if(pstmtShelf != null)
			{
				pstmtShelf.close();
				pstmtShelf = null;
			}
			if(rSetShelf != null)
			{
				rSetShelf.close();
				rSetShelf = null;
			}
			if(rsSItem != null)
			{
				rsSItem.close();
				rsSItem = null;
			}
			if(rs != null)
			{
				rs.close();
				rs =null;
			}
			//Changed by Rohan on 29-08-12 for bug fixing
			//pstmtStock.clearParameters();
			
		}
		catch(SQLException se)
		{
			System.out.println("SQLException :" + se);
			se.printStackTrace();
			errString = se.getMessage();
			//return errString;
			throw se;
		}

		catch(Exception e)
		{
			System.out.println("Exception :" + e);
			errString = e.getMessage();
			e.printStackTrace();
			try
			{
				conn.rollback();
			}
			catch(Exception e1)
			{
				e = e1;
			}
			//return errString ;
			
			throw e;
			
			
		}
		finally
		{
			try
			{
				if(conn != null)
				{	
					if(st != null)
					{
						st.close();
						st = null;
					}
					if(pstmtStock != null)
					{
						pstmtStock.close();
						pstmtStock = null;
					}
					if(rs != null)
					{
						rs.close();
						rs =null;
					}
					
					if(rsSItem != null)
					{
						rsSItem.close();
						rsSItem = null;
					}
					if(pstmtStockInsertSordAlloc != null)
					{
						pstmtStockInsertSordAlloc.close();
						pstmtStockInsertSordAlloc = null;
					}
					if(st != null)
					{
						st.close();
						st = null;
					}
					if(pstmtShelf != null)
					{
						pstmtShelf.close();
						pstmtShelf = null;
					}
					if(rSetShelf != null)
					{
						rSetShelf.close();
						rSetShelf = null;
					}
					//conn.close();
					//conn = null;
				}
			}
			catch(Exception e)
			{
				errString = e.getMessage();
				e.printStackTrace();
				return errString ;
				
			}
			return errString;
		}
		
	}

	
	private String postOrder(ArrayList saleOrderArr, String xtraParams) throws ITMException
	{
		String errString = "";
		String lotSl= null ;
		String tranId = null ;
		String sql = null;
		String adjDrcr = null ;
		String adjCustAdv = null ;
		String adjAdvMode = null ;
		String custCode = "";
		String dueDate = "";
		String orderType = "";
		Connection conn = null;
		ResultSet rs = null;
		Statement st = null;
		StringBuffer TabSepStrBuff = new StringBuffer();
		
		//Changed by sumit sarkar on 06/9/11 [WM1ESUN006] as said by manoharan sir.
		//nvo_business_object_win_methods comp = null;
		try
		{
			System.out.println("Looking Up for NVO..........");
			//Changed by Pawan 07-Sep-11 as said by Manoharan sir.
			//Properties props = new Properties();
			//props.put("org.omg.CORBA.ORBClass", "com.sybase.CORBA.ORB");
			//ORB orb = ORB.init(((String []) (null)), props);
			//Changed by sumit sarkar on 06/9/11 [WM1ESUN006] as said by manoharan sir start.
			/*SessionManager.Manager manager = ManagerHelper.narrow(orb.string_to_object("iiop://192.168.0.217:9000"));
			SessionManager.Session session = manager.createSession("jagadmin", "");
			SessionManager.Factory factory = FactoryHelper.narrow(session.lookup("webitm4/nvo_business_object_win_methods"));
			comp = nvo_business_object_win_methodsHelper.narrow(factory.create()); */
			//Changed by sumit sarkar on 06/9/11 [WM1ESUN006] as said by manoharan sir end.
		
			System.out.println("saleOrderArr.size() ::" + saleOrderArr.size());
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;

			for(int saleOrderCtr = 0;saleOrderCtr < saleOrderArr.size(); saleOrderCtr++)
			{
				System.out.println("sale order from is ::: "+(saleOrderArr.get(saleOrderCtr)).toString());
				String saleOrderStr = (saleOrderArr.get(saleOrderCtr)).toString();
				System.out.println("saleOrderStr ---- "+ saleOrderStr);
				sql = "SELECT CUST_CODE, DUE_DATE, ORDER_TYPE FROM SORDER WHERE SALE_ORDER ='"+ ((saleOrderArr.get(saleOrderCtr)).toString()) +"'" ;  
				st = conn.createStatement();
				rs = st.executeQuery(sql);
				System.out.println(sql);
				while(rs.next())
				{
					custCode = rs.getString(1);
					dueDate = rs.getString(2);
					orderType = rs.getString(3);
					TabSepStrBuff.append(saleOrderStr).append("\t") ;
					System.out.println("sale order from is ::: "+saleOrderStr);
					TabSepStrBuff.append(saleOrderStr).append("\t") ;
					System.out.println("sale order to is ::: "+saleOrderStr);
					TabSepStrBuff.append(custCode).append("\t");
					System.out.println("custCode from::"+ custCode);
					TabSepStrBuff.append(custCode).append("\t");
					System.out.println("custCode to ::"+custCode);
					TabSepStrBuff.append(dueDate).append("\t");
					System.out.println("dueDate from ::"+ dueDate);
					TabSepStrBuff.append(dueDate).append("\t");
					System.out.println("dueDate to ::"+ dueDate);
					//lot_sl 
					TabSepStrBuff.append(" ").append("\t");
				
					TabSepStrBuff.append(" ").append("\t");
					System.out.println("orderType:::"+orderType);
					adjDrcr = itmDBAccessEJB.getEnvDis("999999", "ADJUST_DR_CR_NOTE",conn);
					if(adjDrcr.equals("NULLFOUND"))
					{
						adjDrcr = "N";
					}
					TabSepStrBuff.append(adjDrcr).append("\t");
					adjCustAdv = itmDBAccessEJB.getEnvDis("999999", "ADJUST_CUST_ADV",conn);
					if(adjCustAdv.equals("NULLFOUND"))
					{
						adjCustAdv = "N";
					}
					TabSepStrBuff.append(adjCustAdv).append("\t");
					//club_pend_ord
					TabSepStrBuff.append("N").append("\t");
					//alloc_stock
					TabSepStrBuff.append("N").append("\t");
					//club_order
					TabSepStrBuff.append("N").append("\t");
					//rfresh_db
					TabSepStrBuff.append("N").append("\t");
					//ib_changed
					TabSepStrBuff.append("0").append("\t");
					adjAdvMode = itmDBAccessEJB.getEnvDis("999999", "ADJ_ADV_CUST_SALE",conn);
					if(adjAdvMode.equals("NULLFOUND"))
					{
						adjAdvMode = "C";
					}
					TabSepStrBuff.append(adjAdvMode).append("\t");
					System.out.println("adjAdvMode::"+ adjAdvMode);
					TabSepStrBuff.append(siteCode).append("\t");
					System.out.println("siteCode::"+ siteCode);

					TabSepStrBuff.append("TEMP SITE").append("\n");
								
					String retTabSepStr = TabSepStrBuff.toString();
					
					System.out.println("Tabstring :" + retTabSepStr);
					//Changed by sumit sarkar on 06/9/11 [WM1ESUN006] as said by manoharan sir.
					//errString = comp.gbf_process("nvo_bo_post_order",retTabSepStr , "" , xtraParams);
					
					if (errString != null && errString.trim().length() > 0)
					{
						System.out.println("errString :"+ errString);
						return errString ;
					}
				}
			
			}
			
			if(st != null)
			{
				st.close();
				st = null;
			}
			
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
		}//try
		catch(SQLException se)
		{
			System.out.println("SQLException :" + se);
			se.printStackTrace();
			errString = se.getMessage();
			return errString ;
		
		}
		catch(Exception e)
		{
			System.out.println("Exception :ProcessNVOService :getComponent :==>\n"+e.getMessage());
			e.printStackTrace();
			errString = e.getMessage();
			try
			{
				conn.rollback();
			}
			catch(Exception e1)
			{
				e = e1;
			}
			return errString ;
		
		}
		finally
		{
			try
			{
				if(conn != null)
				{	
					if(st != null)
					{
						st.close();
						st = null;
					}
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				errString = e.getMessage();
				e.printStackTrace();
				return errString ; 
			}
			return errString ;
		}
		
	}
	
	//Changed by sumit sarkar on 28/08/2011 [ WM1ESUN006 ] update wave_task & wave_task_det table start.
	private String updateWaveTask(Document headerDom, Document detailDom, String xtraParams, Connection conn )throws Exception
	{
		String errString = "";		
		String insertSql ="";		
		String saleOrderFrom = "",saleOrderTo = "",custCodeFrom = "",custCodeTo = "";
		String dueDateFrom = "",dueDateTo = "";			
		String chgTerm = "";
		String chgUser = "";
		String invStatLoc= "";
		//Changed By Pragyan Demo4
		String invDeepStatLoc = "";
		String activePickInvstat = "";
		boolean isDeepStoreLoc = false;
		String invStat = "";
		//java.sql.Date currdate = new java.sql.Date( System.currentTimeMillis() ); //Commented by Chandni 01-june-2012
		java.sql.Timestamp currdate = new java.sql.Timestamp( System.currentTimeMillis() );//Added by Chandni 01-june-2012
		java.sql.Date currTrandate = new java.sql.Date( System.currentTimeMillis() ); //Added by Chandni 05-june-2012
		PreparedStatement pstmt = null;
		//Changed by sumit on 03/08/12 To get  start.
		//PreparedStatement pstmt1 = null;
		//ResultSet rs1 = null;
		//Changed by sumit on 03/08/12 end
		//ArrayList replList = new ArrayList();
		ArrayList replListPSO = new ArrayList(); // 05/07/12 manoharan  for normal reserve
		ArrayList replListDSO = new ArrayList(); // 05/07/12 manoharan  for deep storage
		ArrayList pickList = new ArrayList();
		String winNameArr[] = {"w_repl_ord","w_pick_ord","w_master_pack","w_despatch"};
		String refTypeArr[] = {"R","P","K","D"};
		String saleOrder = "";
		String tranCode = "";
		String transMode = "";
		//Changed by Rohan on 1-12-11 on [WM1ESUN006] to generate automatic ptcn number
		String ptcnID = "";
		String itemCode = "";
		String lotNo = "";
		String locCode = "";
		String suggLoc = "";
		String sLocCode = "";
	
		double quantity = 0.0;
		double itemWeight = 0.0;
		double itemVolume = 0.0;
		double packSize = 0.0;
		double caseWeight = 0.0;
		double caseVolume = 0.0;
		//Changed by sumit on 03/08/12 start.
		ArrayList ptcnList = new ArrayList();
		Set locSet = null;
		double totalWeightCurrentshipment = 0.0;
		double totActVolume = 0.0,totCaseVolume = 0.0,totCaseWeight = 0.0, totActWeight = 0.0,totCaseCount = 0.0;
		//Changed By Pragyan 25/02/13 to store the ship type and Pick type.start
		String shipType = "";
		String pickType = "";
		String directPickLoc = "";
		//Changed By Pragyan 25/02/13 to store the ship type and Pick type.end
		//Changed By Pragyan 12/03/13
		String hazardous = "";
		double totActHazVolume = 0.0,totCaseHazVolume = 0.0,totCaseHazWeight = 0.0, totActHazWeight = 0.0,totHazCaseCount = 0.0;
		
		try
		{
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId");
			saleOrderFrom = genericUtility.getColumnValue("sale_order__from",headerDom);
			saleOrderTo = genericUtility.getColumnValue("sale_order__to",headerDom);
			custCodeFrom = genericUtility.getColumnValue("cust_code__from",headerDom);
			custCodeTo = genericUtility.getColumnValue("cust_code__to",headerDom);
			dueDateFrom = genericUtility.getColumnValue("due_date__from",headerDom);
			dueDateTo = genericUtility.getColumnValue("due_date__to",headerDom);
			dueDateFrom = genericUtility.getValidDateString(dueDateFrom, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
			dueDateTo = genericUtility.getValidDateString(dueDateTo, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
			shipType = genericUtility.getColumnValue("ship_type",headerDom);
			directPickLoc = genericUtility.getColumnValue("direct_pick_loc",headerDom);
			/*pickType = checkNull(genericUtility.getColumnValue("master_pack_allow",headerDom));
			pickType = checkNull(genericUtility.getColumnValue("parcelpack_allow",headerDom));
			shipType = genericUtility.getColumnValue("ship_type",headerDom);
			pickType = ("Y".equalsIgnoreCase(pickType))?"P":"M";*/
			
			
			if("Y".equalsIgnoreCase(checkNull(genericUtility.getColumnValue("master_pack_allow",headerDom))))
			{
				pickType = "M";
			}
			else if("Y".equalsIgnoreCase(checkNull(genericUtility.getColumnValue("parcelpack_allow",headerDom))))
			{
				pickType = "P";
			}
			
			System.out.println("Current Size of The Map.......................["+saleOrderWiseMap.size()+"]");
			
			if(saleOrderWiseMap != null && saleOrderWiseMap.size() >0)
			{
				//Changed by sumit on 25/08/12 for setting space for waveId
				waveId = "";
				
				waveId = getTranId("w_wave_task", conn);
				insertSql="INSERT INTO WAVE_TASK(WAVE_ID,TRAN_DATE, " +
						"SALE_ORDER__FROM, SALE_ORDER__TO, CUST_CODE__FROM, " +
						//Changed By Pragyan 22/08/12 To add Hold Status
						//"CUST_CODE__TO,	DUE_DATE__FROM, DUE_DATE__TO, CHG_USER, CHG_TERM, CHG_DATE)" +
						"CUST_CODE__TO,	DUE_DATE__FROM, DUE_DATE__TO, CHG_USER, CHG_TERM, CHG_DATE,HOLD_STATUS,CANCEL)" +
						//"VALUES (?,?,?,?,?,?,?,?,?,?,?)";
						"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
				//Changed by Rohan on 1-12-11 on [WM1ESUN006] to add ptcn into wave_task.end
				pstmt = conn.prepareStatement(insertSql);
				pstmt.setString(1,waveId);		
			//	pstmt.setDate(2,currTrandate );  //Commented by Chandni 01-june-2012
				pstmt.setTimestamp(2,java.sql.Timestamp.valueOf (currTrandate + " 00:00:00")); 
				pstmt.setString(3,saleOrderFrom);
				pstmt.setString(4,saleOrderTo);
				pstmt.setString(5,custCodeFrom);
				pstmt.setString(6,custCodeTo);
				pstmt.setTimestamp(7,java.sql.Timestamp.valueOf( dueDateFrom + " 00:00:00"));
				pstmt.setTimestamp(8,java.sql.Timestamp.valueOf( dueDateTo + " 00:00:00"));	
				pstmt.setString(9,chgUser);
				pstmt.setString(10,chgTerm);
				//pstmt.setDate(11,currdate);  //Commented by Chandni 01-june-2012
				pstmt.setTimestamp(11,currdate); //Added by Chandni 01-june-2012
				pstmt.setString(12,"N"); 
				pstmt.setString(13,"N"); 
				pstmt.executeUpdate();
			
				System.out.println("Start Wave Genartion.......................");
									
				invStatLoc  = discommon.getDisparams("999999","RESERV_LOCATION",conn);
				invDeepStatLoc = discommon.getDisparams("999999","DEEP_STORE_INVSTAT",conn);
				activePickInvstat = discommon.getDisparams("999999","ACTIVE_PICK_INVSTAT",conn);
				
				Set sordList = saleOrderWiseMap.keySet();
				Iterator it = sordList.iterator();
				
				
				//Issue Tracker Point No  96.start
				HashMap sorderConsigMap = new HashMap();
				HashMap custConsigMap = new HashMap();
				HashMap sordMapInfoMap = null;
				String currentShipConsGrp = "";
				ArrayList tempList = null;
				HashMap tempMapOrd = null;
				
				while(it.hasNext())
				{
					totalWeightCurrentshipment = 0.0;
					totActVolume = 0.0;
					totCaseVolume = 0.0;
					totCaseWeight = 0.0;
					totActWeight = 0.0;
					totCaseCount = 0.0;
					//Changed By Pragyan 12/03/13.start
					totActHazVolume = 0.0;
					totCaseHazVolume = 0.0;
					totCaseHazWeight = 0.0;
					totActHazWeight = 0.0;
					totHazCaseCount = 0.0;
					//Changed By Pragyan 12/03/13.end
					locSet = new TreeSet();
					String sorderKey = (String)it.next();
					ArrayList itemMapList = (ArrayList)saleOrderWiseMap.get(sorderKey);
					saleOrder = sorderKey.substring(0,sorderKey.indexOf(":"));
					sordMapInfoMap = getSordInfo(saleOrder, conn);
					currentShipConsGrp = (String)sordMapInfoMap.get("SHIP_CONS_GRP");
					int itemMapListLen = itemMapList.size();
					
					for(int i =0;i<itemMapListLen;i++)
					{
						double actCount = 0.0;
						double caseCount = 0.0;
						HashMap loadMap = (HashMap)itemMapList.get(i);	
						itemCode = (String)loadMap.get("item_code");
						lotNo = (String)loadMap.get("lot_no");
						quantity = (Double)loadMap.get("alloc_qty");
						locCode = (String)loadMap.get("loc_code");
						suggLoc = (String)loadMap.get("sugg_loc");
						hazardous = (String)loadMap.get("hazard");
						HashMap dataTempMap = getItemVoumeMap(itemCode, lotNo, conn);
						itemWeight = (Double)dataTempMap.get("ITEM_WEIGHT");
						itemVolume = (Double)dataTempMap.get("ITEM_SIZE");
						packSize = (Double)dataTempMap.get("PACK_SIZE");
						caseWeight = (Double)dataTempMap.get("PACK_WEIGHT");
						caseVolume = (Double)dataTempMap.get("LOT_SIZE");
						
						invStat = (String)loadMap.get("inv_stat");
						invStat = invStat.trim();
						
						
						
						System.out.println("current item code"+itemCode+"]quantity["+quantity+"]itemWeight["+itemWeight+"]caseWeight"+caseWeight+"]caseVolume["+caseVolume+"]Loc Code["+locCode+"]invStat["+invStat+"]");
						locSet.add(suggLoc);
						//Changed By Pragyan 17-feb-13  to set quanity if active plocation and greater the packsize 
						if(quantity < packSize || invStat.equalsIgnoreCase(activePickInvstat))
						//if(quantity < packSize)
						{
							actCount = quantity;
						}
						else
						{
							actCount = quantity  % packSize;
							caseCount = Math.floor(quantity /packSize) ;
							if("Y".equalsIgnoreCase(hazardous))
							{
								totHazCaseCount = totHazCaseCount +  caseCount;
							}
							else
							{
								totCaseCount = totCaseCount +  caseCount;
							}
						}
						//Changed By Pragyan 12/03/13.start
						if("Y".equalsIgnoreCase(hazardous))
						{
							System.out.println("HAZMAT......");
							totActHazWeight = totActHazWeight + ( actCount * itemWeight );
							totActHazVolume = totActHazVolume + ( actCount * itemVolume );						
							totCaseHazVolume = totCaseHazVolume + ( caseCount * caseVolume );
							totCaseHazWeight = totCaseHazWeight + ( caseCount * caseWeight );
						}
						else
						{
							totActWeight = totActWeight + ( actCount * itemWeight );
							totActVolume = totActVolume + ( actCount * itemVolume );						
							totCaseVolume = totCaseVolume + ( caseCount * caseVolume );
							totCaseWeight = totCaseWeight + ( caseCount * caseWeight );
							
						}
						//Changed By Pragyan 12/03/13.end
						
					}
					
					//Changed By Pragyan 13/03/13 
					//totalWeightCurrentshipment = totActWeight + totCaseWeight;
					totalWeightCurrentshipment = totActWeight + totCaseWeight + totActHazWeight + totCaseHazWeight;
					System.out.println("current total weight "+totalWeightCurrentshipment+"]");
					tempMapOrd = new HashMap();
					//Changed By Pragyan 28/02/13 To store the data as a Key for different loc type parent
					//tempMapOrd.put("sale_order", saleOrder);
					tempMapOrd.put("sale_order", sorderKey);
					tempMapOrd.put("tot_weight_order", totalWeightCurrentshipment);
					tempMapOrd.put("no_art_order", totCaseCount);
					tempMapOrd.put("tot_case_weight", totCaseWeight);
					tempMapOrd.put("tot_case_volume", totCaseVolume);
					tempMapOrd.put("tot_act_weight", totActWeight);
					tempMapOrd.put("tot_act_volume", totActVolume);
					//Changed By Pragyan 12/03/13.start
					tempMapOrd.put("no_art_order_haz", totHazCaseCount);
					tempMapOrd.put("tot_case_weight_haz", totCaseHazWeight);
					tempMapOrd.put("tot_case_volume_haz", totCaseHazVolume);
					tempMapOrd.put("tot_act_weight_haz", totActHazWeight);
					tempMapOrd.put("tot_act_volume_haz", totActHazVolume);
					//Changed By Pragyan 12/03/13.end
					tempMapOrd.put("loc_set", locSet);
					//Changed By Pragyan 28/02/13 To store the data as a Key for different loc type parent
					//sorderConsigMap.put(saleOrder, currentShipConsGrp);
					sorderConsigMap.put(sorderKey, currentShipConsGrp);
					
					if(currentShipConsGrp != null && currentShipConsGrp.length() > 0)
					{
						if(custConsigMap.containsKey(currentShipConsGrp))
						{
							tempList = (ArrayList)custConsigMap.get(currentShipConsGrp);
							tempList.add(tempMapOrd);
							
						}
						else
						{
							tempList = new ArrayList();
							tempList.add(tempMapOrd);	
						}
						custConsigMap.put(currentShipConsGrp, tempList);
					}
				}
				//Issue Tracker Point No  96.end
				it = sordList.iterator();
				while(it.hasNext())
				{
						
					totalWeightCurrentshipment = 0.0;
					totActVolume = 0.0;
					totCaseVolume = 0.0;
					totCaseWeight = 0.0;
					totActWeight = 0.0;
					totCaseCount = 0.0;
					//Changed By Pragyan 12/03/13.start
					totActHazVolume = 0.0;
					totCaseHazVolume = 0.0;
					totCaseHazWeight = 0.0;
					totActHazWeight = 0.0;
					totHazCaseCount = 0.0;
					//Changed By Pragyan 12/03/13.end
					//String sorderKey = (String)it.next();;
					String sorderKey = (String)it.next();
					ArrayList itemMapList = (ArrayList)saleOrderWiseMap.get(sorderKey);
					ArrayList itemSortList = new ArrayList();
					ArrayList itemHazSortList = new ArrayList();
					//locSet = new TreeSet();
					System.out.println("wave Id :"+waveId);
					saleOrder = sorderKey.substring(0,sorderKey.indexOf(":"));
					System.out.println("Current sorder No>>>>>>>>>>>>["+saleOrder+"]");
					int itemMapListLen = itemMapList.size();
					System.out.println("Current Sorder No :["+sorderKey+"]Map Length["+itemMapListLen+"]");
					//Changed By Pragyan Demo4
					/*HashMap transPorterInfoMap = getTransportInfo(saleOrder, conn);
					tranCode = (String)transPorterInfoMap.get("TRAN_CODE");
					transMode = (String)transPorterInfoMap.get("TRANS_MODE");*/
			
					/*for(int i =0;i<itemMapListLen;i++)
					{
						
						HashMap loadMap = (HashMap)itemMapList.get(i);
						//isDeepStoreLoc = false; // 05/07/12 commented
						
						invStat = ((String)loadMap.get("inv_stat"));
						System.out.println("((String)loadMap.get(inv_stat))["+invStat+"]invStatLoc["+invStatLoc+"]invDeepStatLoc["+invDeepStatLoc+"]");
						
						if(invStat.trim().equalsIgnoreCase(invStatLoc))
						{
							replListPSO.add(loadMap);
						}
						else if(invStat.trim().equalsIgnoreCase(invDeepStatLoc))
						{
							//isDeepStoreLoc = true; // 05/07/12 commented
							replListDSO.add(loadMap);
						}	
						else
						{
							
							System.out.println("Updating Map For Pick List*****["+pickList.size()+"]*****");
							pickList.add(loadMap);
						}
						
						
					}*/
					
					/*for(int i =0;i<itemMapListLen;i++)
					{
						double actCount = 0.0;
						double caseCount = 0.0;
						HashMap loadMap = (HashMap)itemMapList.get(i);	
						itemCode = (String)loadMap.get("item_code");
						lotNo = (String)loadMap.get("lot_no");
						quantity = (Double)loadMap.get("alloc_qty");
						locCode = (String)loadMap.get("loc_code");
						HashMap dataTempMap = getItemVoumeMap(itemCode, lotNo, conn);
						itemWeight = (Double)dataTempMap.get("ITEM_WEIGHT");
						itemVolume = (Double)dataTempMap.get("ITEM_SIZE");
						packSize = (Double)dataTempMap.get("PACK_SIZE");
						caseWeight = (Double)dataTempMap.get("PACK_WEIGHT");
						caseVolume = (Double)dataTempMap.get("LOT_SIZE");
						
						System.out.println("current item code"+itemCode+"]quantity["+quantity+"]itemWeight["+itemWeight+"]caseWeight"+caseWeight+"]caseVolume["+caseVolume+"]Loc Code["+locCode+"]");
						locSet.add(locCode);
						if(quantity < packSize)
						{
							actCount = quantity;
						}
						else
						{
							actCount = quantity  % packSize;
							caseCount = quantity  / packSize;
							totCaseCount = totCaseCount +  caseCount;
						}
						totActWeight = totActWeight + ( actCount * itemWeight );
						totActVolume = totActVolume + ( actCount * itemVolume );
						
						totCaseVolume = totCaseVolume + ( caseCount * caseVolume );
						totCaseWeight = totCaseWeight + ( caseCount * caseWeight );
						
						totalWeightCurrentshipment = totalWeightCurrentshipment + ( itemWeight * quantity);
						System.out.println("current total weight "+totalWeightCurrentshipment+"]");
					}*/
					
					//Changed By Pragyan 28/02/13 To store the data as a Key for different loc type parent
					//String shipCons = (String)sorderConsigMap.get(saleOrder);
					String shipCons = (String)sorderConsigMap.get(sorderKey);
					ArrayList dataList = (ArrayList)custConsigMap.get(shipCons);
					int dataListlen = dataList.size();
					
					for(int cCgt = 0;cCgt < dataListlen;cCgt++)
					{
						HashMap sordMap = (HashMap)dataList.get(cCgt);
						
						System.out.println("totalWeightCurrentshipment BEFORE"+totalWeightCurrentshipment+"]");
						System.out.println("totCaseVolume BEFORE"+totCaseVolume+"]");
						System.out.println("totActVolume BEFORE"+totActVolume+"]");
						System.out.println("totActWeight BEFORE"+totActWeight+"]");
						System.out.println("totCaseWeight BEFORE"+totCaseWeight+"]");
						System.out.println("totCaseCount BEFORE"+totCaseCount+"]");
						
						totalWeightCurrentshipment = totalWeightCurrentshipment + (Double)sordMap.get("tot_weight_order");
						totActVolume = totActVolume + (Double)sordMap.get("tot_act_volume");
						totCaseVolume = totCaseVolume + (Double)sordMap.get("tot_case_volume");
						totCaseWeight = totCaseWeight + (Double)sordMap.get("tot_case_weight");
						totActWeight = totActWeight + (Double)sordMap.get("tot_act_weight");
						totCaseCount = totCaseCount + (Double)sordMap.get("no_art_order");
						
						//Changed By Pragyan 13/03/13.start
						totActHazVolume = totActHazVolume + (Double)sordMap.get("tot_act_volume_haz");
						totCaseHazVolume = totCaseHazVolume + (Double)sordMap.get("tot_case_volume_haz");
						totCaseHazWeight = totCaseHazWeight + (Double)sordMap.get("tot_case_weight_haz");
						totActHazWeight = totActHazWeight + (Double)sordMap.get("tot_act_weight_haz");
						totHazCaseCount = totHazCaseCount + (Double)sordMap.get("no_art_order_haz");
						//Changed By Pragyan 13/03/13.end
						
						System.out.println("totalWeightCurrentshipment AFTER"+totalWeightCurrentshipment+"]");
						System.out.println("totCaseVolume AFTER"+totCaseVolume+"]");
						System.out.println("totCaseWeight AFTER"+totCaseWeight+"]");
						System.out.println("totActVolume AFTER"+totActVolume+"]");
						System.out.println("totActWeight AFTER"+totActWeight+"]");
						System.out.println("totCaseCount AFTER"+totCaseCount+"]");			
						System.out.println("totHazCaseCount AFTER"+totHazCaseCount+"]");				
						
						//Changed By Pragyan 28/02/13 To store the data as a Key for different loc type parent
						//if(((String)sordMap.get("sale_order")).equalsIgnoreCase(saleOrder))
						if(((String)sordMap.get("sale_order")).equalsIgnoreCase(sorderKey))
						{
							locSet = (Set)sordMap.get("loc_set");
						}
					}
									
					
					
					System.out.println("Current Location Tree["+locSet.toString()+"]");
					Iterator itLoc = locSet.iterator();
					while(itLoc.hasNext())
					{
						sLocCode = (String)itLoc.next();
						System.out.println("Searching For Location ["+sLocCode+"]");
						for(int i =0;i<itemMapListLen;i++)
						{
							HashMap loadMap = (HashMap)itemMapList.get(i);	
							locCode = (String)loadMap.get("sugg_loc");
							hazardous = (String)loadMap.get("hazard");
							//if(sLocCode.equalsIgnoreCase(locCode))
							if(sLocCode.equalsIgnoreCase(locCode) && !"Y".equalsIgnoreCase(hazardous))
							{
								System.out.println("Found Location ["+locCode+"]index["+i+"]");
								itemSortList.add(loadMap);
							}
							else if(sLocCode.equalsIgnoreCase(locCode) && "Y".equalsIgnoreCase(hazardous))
							{
								itemHazSortList.add(loadMap);
							}
							
						}
					}
					
					System.out.println("Final weight for th shipment "+totalWeightCurrentshipment+"]totCaseWeight"+totCaseWeight+"]totCaseVolume["+totCaseVolume);
					//Changed By Pragyan 25/02/13 to pass the total no cases
					//Changed By Pragyan 02/12/12 to pass the total no cases
					//HashMap transPorterInfoMap = getTransportInfo(saleOrder,totalWeightCurrentshipment, conn);
					//HashMap transPorterInfoMap = getTransportInfo(saleOrder,totalWeightCurrentshipment,totCaseCount, conn);
					HashMap transPorterInfoMap = getTransporterInfoMap(saleOrder,totalWeightCurrentshipment,totCaseCount,pickType,shipType, conn);
					tranCode = (String)transPorterInfoMap.get("TRAN_CODE");
					transMode = (String)transPorterInfoMap.get("TRANS_MODE");
					
					if(tranCode == null || tranCode.length() <= 0)
					{
						
						//Changed By Prayan 25/02/13 To set Proper error messages
						//return errString = getError(saleOrder + " Total Weight["+totalWeightCurrentshipment+"] Total Case Count ["+totCaseCount+"] ", "NVLTRANCOD", conn);
						return errString = itmDBAccessEJB.getErrorString("","NVLTRANCOD","","",conn);
						
					}
					
					//Changed By Pragyan 26/12/12/ To send the List with ordered Location
					// 05/07/12 separate list for PSO and DSO as earlier logic is wrong
					//if(replList.size() > 0 || pickList.size() > 0)
					//if(replListPSO.size() > 0 || replListDSO.size() > 0 || pickList.size() > 0)
					//if(itemMapList.size() > 0)
					//if(itemSortList.size() > 0)
					if(itemSortList.size() > 0 || itemHazSortList.size() > 0)
					{
					
						ptcnID = getTranId( "w_ptcn", conn );	
						
						//Changed by sumit on 07/08/12 adding generated PTCN in list for forther use start  
						ptcnList.add(ptcnID);
						
						System.out.println("insertion of sql inside updateWaveTask on pick_ord_det success on date "+currdate);
						if( pstmt != null )
						{
							pstmt.close();
							pstmt = null;
						}
						
						//Changed by Pragyan 
						//Changed By Pragyan 26/12/12/ To send the List with ordered Location
						//errString = updatePickOrdPartII(headerDom, detailDom,waveId, siteCode,saleOrder ,xtraParams, itemMapList,ptcnID,transPorterInfoMap,totActVolume,totActWeight,totCaseVolume,totCaseWeight,totCaseCount, conn);
						//errString = updatePickOrdPartII(headerDom, detailDom,waveId, siteCode,saleOrder ,xtraParams, itemSortList,ptcnID,transPorterInfoMap,totActVolume,totActWeight,totCaseVolume,totCaseWeight,totCaseCount, conn);
						
						if(itemSortList.size() > 0)
						{
							errString = updatePickOrder(headerDom, detailDom,waveId, siteCode,saleOrder ,xtraParams, itemSortList,ptcnID,transPorterInfoMap,totActVolume,totActWeight,totCaseVolume,totCaseWeight,totCaseCount, conn);
						}
						
						if(itemHazSortList.size() > 0)
						{
							errString = updatePickOrder(headerDom, detailDom,waveId, siteCode,saleOrder ,xtraParams, itemHazSortList,ptcnID,transPorterInfoMap,totActHazVolume,totActHazWeight,totCaseHazVolume,totCaseHazWeight,totHazCaseCount, conn);
						}
												
						//System.out.println("replListPSO.size() ["+replListPSO.size()+"] replListDSO.size() ["+replListDSO.size()+"] pickList.size()"+pickList.size());	
						
						/*//if(replList.size() > 0)
						if(replListPSO.size() > 0)
						{
							isDeepStoreLoc = false;
							//Changed By Pragyan Demo4
							//updatePickOrd(headerDom, detailDom,waveId, siteCode,saleOrder ,lineNo,xtraParams, replList,true,ptcnID, conn);
							if (errString == null || errString.trim().length() == 0)
							{
								errString = updatePickOrd(headerDom, detailDom,waveId, siteCode,saleOrder ,xtraParams, replListPSO,true,isDeepStoreLoc,ptcnID,transPorterInfoMap, conn);
							}
 							
						}
						if(replListDSO.size() > 0)
						{
							isDeepStoreLoc = true;
							//Changed By Pragyan Demo4
							//updatePickOrd(headerDom, detailDom,waveId, siteCode,saleOrder ,lineNo,xtraParams, replList,true,ptcnID, conn);
							if (errString == null || errString.trim().length() == 0)
							{
								errString = updatePickOrd(headerDom, detailDom,waveId, siteCode,saleOrder ,xtraParams, replListDSO,true,isDeepStoreLoc,ptcnID,transPorterInfoMap, conn);
							}
 							
						}
						
						if(pickList.size() > 0)
						{
							System.out.println("pickList===>"+pickList.toString());
							//Changed By Pragyan Demo4
							//updatePickOrd(headerDom, detailDom,waveId, siteCode,saleOrder ,lineNo,xtraParams, pickList,false,ptcnID, conn);
							if (errString == null || errString.trim().length() == 0)
							{
								errString = updatePickOrd(headerDom, detailDom,waveId, siteCode,saleOrder ,xtraParams, pickList,false,false,ptcnID,transPorterInfoMap, conn);
							}
						}*/
						
						
						
						/*String packRefId = updateWaveTaskDet(waveId,3,conn);
						updatePacking( headerDom, detailDom, waveId,saleOrder,packRefId,xtraParams, conn);*/
						
						if (errString == null || errString.trim().length() == 0)
						{
							String dspRefId = updateWaveTaskDet(waveId,4,saleOrder,"","",ptcnID,conn);
							errString = updateShipment(headerDom, detailDom,waveId,saleOrder,dspRefId,tranCode,transMode, xtraParams, conn);
							
						}
						else
						{
							return errString;
						}
						
						
					}
					
					
					/*replListPSO.clear();
					replListDSO.clear();
					pickList.clear();*/
				//}//while(it.hasNext())
				System.out.println("End New----------Wave Genartion.......................["+errString+"]");
				//Changed by sumit 02/08/12 to print expected wave_generation as a report start.
				/*
				if (errString == null || errString.trim().length() == 0)
				{
					String printMode = checkNull(discommon.getDisparams("999999","WAVE_PRINT_MODE",conn));
					if ("R".equalsIgnoreCase(waveMode) && printMode.trim().length() > 0) 	
					{					
						System.out.println(" printMode ->["+printMode+"]");
						if(!"JSP".equalsIgnoreCase(printMode))
						{
							String printerStr  = discommon.getDisparams("999999","WAVE_PRINTER",conn);
							String reportObjName = discommon.getDisparams("999999","WAVE_REP_OBJ_NAME",conn);
							System.out.println("Printer ->["+printerStr+"]  report_obj_name ["+reportObjName+"]");
							
							for (int i=0; i< ptcnList.size(); i++)
							{
								System.out.println("inside report generation : and ptcn is ["+ptcnList.get(i)+"]");
								ibase.webitm.reports.utility.JasperReportGenerator jrGenerator = new ibase.webitm.reports.utility.JasperReportGenerator();
								String xsdString ="<Arguments>" +
											"<Argument id=\"PTCN\" name=\"PTCN\">" +
											"<argType>java.lang.String</argType>" +
											"<value>"+ptcnList.get(i)+"</value>" +
											"</Argument>" +
											"<Argument id=\"x_path\" name=\"x_path\">" +
											"<argType>java.lang.String</argType>" +
											"<value>/DocumentRoot/pick_label</value>" +
											"</Argument>" +
											"<Argument id=\"design_source\" name=\"design_source\">" +
											"<argType>java.lang.String</argType>" +
											"<value>pick_label.jrxml</value>" +
											"</Argument>" +
											"<Argument id=\"data_source\" name=\"data_source\">" +
											"<argType>java.lang.String</argType>" +
											"<value>SQL</value>" +
											"</Argument>" +
											"<Argument id=\"bind_type\" name=\"bind_type\">" +
											"<argType>java.lang.Integer</argType>" +
											"<value>0</value>" +
											"</Argument>" +
											"<Argument id=\"report_type\" name=\"report_type\">" +
											"<argType>java.lang.String</argType>" +
											"<value>JASPER</value>" +
											"</Argument>" +
											"<Argument id=\"report_save_type\" name=\"report_save_type\">" +
											"<argType>java.lang.String</argType>" +
											"<value>NATIVE</value>" +
											"</Argument>" +
											"</Arguments>";
								System.out.println(" XSD parser **->["+xsdString+"]");
								//PDFCreator
								//\\\\172.16.100.90\\unimis-hpljP3015-001						
								errString = jrGenerator.printReport(reportObjName, xsdString, chgUser, printerStr, 1, conn);
							}
							System.out.println(" PRINTING task completed--------**------->");
						}
						else
						{
							errString = writeReportInJsp(waveId, conn, siteCode, saleOrder);
							System.out.println(" written in jsp done");
						}
					}
					}
					*/
					//Changed by sumit 02/08/12 to print expected wave_generation as a report END.
				}
			}
			
			//if(errString == null && !(errString.trim().length() > 0))
			if (errString == null || errString.trim().length() == 0)
			{
				//changed by sumit on 23/08/12 update wave_status   
				//errString = updateWaveSatus(waveId, conn);
				errString = updateWaveSatus(waveId,directPickLoc, conn);
			}
			else
			{
				return errString;
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception :updateWaveTask :"  + insertSql + "\n" +e.getMessage());
			e.printStackTrace();
			errString = e.getMessage();
			throw e;
		}
		finally
		{
			try
			{
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}			
			}
			catch(Exception e)
			{
				e.printStackTrace();
				errString = e.getMessage();
				throw e;
			}
		}
		return errString;
	}
	//Changed by sumit sarkar on 28/08/2011 [ WM1ESUN006 ] for creating ref_id start.
	private String updateWaveTaskDet(String waveId ,int lineNo,String saleOrder,String subRefSer ,String subrefType ,String ptcn,Connection conn)throws Exception
	{
		String winNameArr[] = {"w_repl_ord","w_pick_ord","w_master_pack","w_despatch"};
		String refTypeArr[] = {"R","P","K","D"};
		String refId[] = new String[5];
		String returnRefId = "";
		PreparedStatement pstmt = null;
		String insertSql = "";		
		
		try
		{
			
				String refSer = getRefSer(winNameArr[lineNo-1], conn);
				returnRefId = getTranId(winNameArr[lineNo-1], conn);
				String refType = refTypeArr[lineNo-1];
				String status = "N";
				
				refSer = subRefSer.length() > 0? subRefSer:refSer;
				refType = subrefType.length() > 0?subrefType:refType;
				
				//Chnaged by sumit on 03/04/12 on adding wave_status parameter in sql.
				//insertSql = "INSERT INTO WAVE_TASK_DET(WAVE_ID ,LINE_NO, REF_SER, REF_ID, REF_TYPE, STATUS,PTCN,SALE_ORDER)" +
						//"VALUES(?,?,?,?,?,?,?,?,?)";
				insertSql = "INSERT INTO WAVE_TASK_DET(WAVE_ID ,LINE_NO, REF_SER, REF_ID, REF_TYPE, STATUS,PTCN,SALE_ORDER,WAVE_STATUS)" +
						"VALUES(?,?,?,?,?,?,?,?,?)";
				int counter = getWaveTaskDetLineNo(waveId,conn);
				
				System.out.println("Current Line No[>>>>>>>>>>>"+counter+"]");
				counter = counter + 1;
				pstmt = conn.prepareStatement(insertSql);
				pstmt.setString(1,waveId);
				pstmt.setInt(2,counter);
				pstmt.setString(3,refSer);
				pstmt.setString(4,returnRefId);
				pstmt.setString(5,refType);
				pstmt.setString(6,status);
				pstmt.setString(7,ptcn);
				pstmt.setString(8,saleOrder);
				//Chnaged by sumit on 03/04/12
				pstmt.setString(9,"W");
				pstmt.executeUpdate();
				//Changed by sumit on 27/08/12 commented start.
				//pstmt.clearParameters();
				if( pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				/*point = conn.setSavepoint();
				savePointList.add(point);
				*/				
				
			
		}		
		catch(Exception e)
		{
			e.printStackTrace();

			throw e;
		}
		finally
		{
			
			try
			{
				if( pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();

				throw e;
			}
		}
		
		return returnRefId;
	}
	
	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$-PICKING LOGIC CHANGE.START
	private String updatePickOrder(Document headerDom, Document detailDom,String waveID,String siteCode,String saleOrder, String xtraParams, ArrayList dataList,String ptcn,HashMap transportInfoMap,double totActVolume,double totActWeight,double totCaseVolume,double totCaseWeight,double totCaseCount, Connection conn )throws Exception
	{
		String errString = "";		
		String sql = "";
		String sqlHdr = "";
		String sqlDtl = "";
		String itemCode = "";
		String locCode = "";
		String lotNo = "";
		String lotSl = "";
		String noArt = "";
		String sordLineNo = "";
		String itemLocType="";
		String invStat = "";
		String invReserve = "";
		String invDeepReserve = "";
		String invPndReserve = "";
		int locZonePref = 0;
		double casePackSize = 0.0;
		double itemGrossWeight=0.0 ;
		String sqlHdrPick ="",sqlDtlPick="",sqlReplOrdHdr="",sqlReplOrdDtl=""; 
		String pickType ="";
		String  chgTerm = "", chgUser = "";		
		String stockToDock = "";
		String expLevel = "";
		java.sql.Date orderDate = new java.sql.Date( System.currentTimeMillis() );				
		PreparedStatement pstmt = null;
		PreparedStatement pstmtDet = null;
		PreparedStatement pstmtRplHdr = null;
		PreparedStatement pstmtRplDet = null;
		//Changed By Pragyan 26/02/13 To insert Repl Iss Hdr & Detail.start
		PreparedStatement pstmtIssHdr = null;
		PreparedStatement pstmtIssDet = null;
		PreparedStatement pstmtUpdWave = null ;
		PreparedStatement pstmtPickHdr = null;
		//Changed By Pragyan 26/02/13 To insert Repl Iss Hdr & Detail.end
		
		ResultSet rSet = null ;
		Double quantity;
		
		ArrayList allCasePickList = new ArrayList();
		ArrayList allActivesList = new ArrayList();
		ArrayList allMasterPackList = new ArrayList();	
		ArrayList allMasterList = new ArrayList();	
		ArrayList allStockToDockList = new ArrayList();
		ArrayList allItemPickkList = null;
		
		double palletVolume = 0.0;
		double palletMaxWeight = 0.0;
		double packetMaxVolumeActive = 0.0;
		double packetMaxWeightActive = 0.0;
		double masterPackWeight = 0.0;
		double masterPackVolume = 0.0;
		double masterPackCount = 0.0;
		double masterPackWeightPerOrder = 0.0;
		//Changed By Pragyan 25/02/13 To change the Logic according to ship type
		boolean masterPackAllow = false;
		/* 
		 * boolean isMasterPackAllow = false;*/
		String isMasterPackBestFit = "N";
		double masterPackCountPerOrder = 0.0;
		String isSinglePickMasterPack="";
		String docLoc = "", tranCode = "",custCodeDlv = "",maxWeight="",locTypeTransport = "",casePickInv = "",activePickInv = "",partialResrvLoc="";
		HashMap mapItemVolume = null;
		HashMap mapItemPick = new HashMap();
		double weightOfmasterPackCount=0.0;
		double countCasesOfmasterPackWeight=0.0;
		String locInvStat = "";
		PreparedStatement pstmtLoc = null;
		ResultSet rsLoc = null;
		String sqlLocInv = "";
		String mPackAllow = "";
		String aPickAllow = "";
		String stockToDoc = "";
		String pPickAllow = "";
		//Changed By Pragyan 25/02/13 To change the Logic according to ship type.start
		String dbShipType = "";
		/*String masterPackOverride = "N";
		String parcelPickOverride = "N";*/
		//Changed By Pragyan 25/02/13 To change the Logic according to ship type.end
		//Changed by Rohan on 24-11-12 for define variable
		int cartonCount = 0;
		//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header.start
		/*replCnt = 1;
		isReplHdr = false;
		replOrdCpy = "";*/
		boolean isActivePickHdr = false;
		String pickHdrCpy = "";
		//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header.end
		//Changed By Pragyan 26/02/13 To add direct Pick location for Master/Parcel converting from LTL.
		String directPickLoc = "";
		String sSQLIssHdr = "",sSQLIssDet = "",sSQlUpdWave = "",sSQLUpdPkHdr = "";
		String shipType = "",sugPalletNo = "";
		//Changed By Pragyan 13/03/13  for Haz Items.start
		String hazardous = "",sugCode = "",transMode = "";
		double packSize = 0.0,perItemVolume = 0.0 ,caseVolume = 0.0,caseWeight = 0.0 ,
		itemWeight = 0.0,
		activeCount = 0.0,
		cashCount = 0.0,itemVolume = 0.0;
		HashMap itmVolumeMap = null;
		ArrayList activeTempPickList = null,caseTempPickList = null, masterTempPackList = null,masterTempList  = null;
		
		try
		{
			
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId");
		
			tranCode = (String)transportInfoMap.get("TRAN_CODE");
			maxWeight = (String)transportInfoMap.get("MAX_WEIGHT");
			locTypeTransport = (String)transportInfoMap.get("LOC_TYPE");
			custCodeDlv = (String)transportInfoMap.get("CUST_CODE_DLV");
			dbShipType = (String)transportInfoMap.get("SHIP_TYPE");
			transMode = (String)transportInfoMap.get("TRANS_MODE");
			transMode = transMode != null?transMode.trim():transMode;
			
			docLoc = getDocLoc(tranCode, conn);
			if(docLoc == null || docLoc.length() == 0)
			{
				errString = getError(saleOrder,"INVDOCLOC",conn);
				return errString;
			}
			//Changed By Pragyan 28/02/12 To sel the pallet no from old PTCN
			directPickLoc = genericUtility.getColumnValue("direct_pick_loc",headerDom);
			sugPalletNo = genericUtility.getColumnValue("pallet_no",headerDom);
			shipType  = genericUtility.getColumnValue("ship_type",headerDom);;
			casePickInv  = discommon.getDisparams("999999","CASE_PICK_INVSTAT",conn);
			activePickInv  = discommon.getDisparams("999999","ACTIVE_PICK_INVSTAT",conn);
			invReserve  = discommon.getDisparams("999999","RESERV_LOCATION",conn);
			invDeepReserve = discommon.getDisparams("999999","DEEP_STORE_INVSTAT",conn);
			invPndReserve = discommon.getDisparams("999999","PND_INVSTAT",conn);
			partialResrvLoc = discommon.getDisparams("999999","PRSRV_INVSTAT",conn);
			isMasterPackBestFit  = discommon.getDisparams("999999","MASTER_PACK_BEST_FIT",conn);
			//The Dimension of pallet are 60*48*40 inches H*L*W = 115200
			palletVolume  = Double.parseDouble(discommon.getDisparams("999999","PER_PALLET__VOLUME",conn));
			palletMaxWeight  = Double.parseDouble(discommon.getDisparams("999999","PER_PALLET__WEIGHT",conn));
			//Changed by Rohan on 4-12-11 [WM1ESUN006] For master pack allow.start
			masterPackCount  = Double.parseDouble(discommon.getDisparams("999999","MASTER_PACK_CASE_COUNT",conn));
			masterPackWeight  = Double.parseDouble(discommon.getDisparams("999999","MASTER_PACK_WEIGHT",conn));
			masterPackWeightPerOrder  = Double.parseDouble(discommon.getDisparams("999999","MASTER_PACK_WEIGHT_PER_ORDER",conn));
			isSinglePickMasterPack = discommon.getDisparams("999999","MASTER_PACK_SINGLE_PICK",conn);
			//Changed by Rohan on 24-11-12 to get variable from disparam for active pick case count
			String actPkCnt = discommon.getDisparams("999999","ACTIVE_PICK_CASE_COUNT",conn);
			
			//Changed By Pragyan 25/05/13 To get the valu of values from each line item wize.start
			//Changed By Pragyan 31/12/12 To get the valu of values from each line item wize
			/*mPackAllow = genericUtility.getColumnValue("master_pack_allow",detailDom);
			mPackAllow = (mPackAllow != null && mPackAllow.length() > 0)?mPackAllow:"N";
			aPickAllow = genericUtility.getColumnValue("active_pick_allow",detailDom);
			aPickAllow = (aPickAllow != null && aPickAllow.length() > 0)?aPickAllow:"Y";
			stockToDoc = genericUtility.getColumnValue("stock_to_dock_allow",detailDom);
			stockToDoc = (stockToDoc != null && stockToDoc.length() > 0)?stockToDoc:"Y";
			pPickAllow  = genericUtility.getColumnValue("parcelpack_allow",detailDom);
			pPickAllow = (pPickAllow != null && pPickAllow.length() > 0)?pPickAllow:"Y";
			masterPackOverride = genericUtility.getColumnValue("master_override",headerDom);
			masterPackOverride = (masterPackOverride != null && masterPackOverride.length() > 0)?masterPackOverride:"N";
			parcelPickOverride = genericUtility.getColumnValue("parcel_override",headerDom);
			parcelPickOverride = (parcelPickOverride != null && parcelPickOverride.length() > 0)?parcelPickOverride:"N";
			System.out.println("mPackAllow:["+mPackAllow+"]aPickAllow["+aPickAllow+"]stockToDoc["+stockToDoc+"]Parcel Pick["+pPickAllow+"]");
			System.out.println("Master Pack Override["+masterPackOverride+"]Parcel Pick Override["+parcelPickOverride+"]");*/
			
			//Changed By Pragyan 25/05/13 To get the valu of values from each line item wize.End
			
			if(totActWeight > 0 && totActVolume > 0)
			{
				String[] itmWeightVol = new String[3];
				String itemVolumeWeight = getPackItemVolumeWeight(totActWeight , totActVolume, "A", conn);
			
				itmWeightVol = itemVolumeWeight.split(":");
				
				if(Double.parseDouble(itmWeightVol[0]) != 0.0)
				{
					 packetMaxWeightActive = Double.parseDouble(itmWeightVol[0]);
				}
				if(Double.parseDouble(itmWeightVol[1]) != 0.0)
				{
					packetMaxVolumeActive = Double.parseDouble(itmWeightVol[1]);
				}
			}
			
			
			//Changed By Pragyan 25/02/13 To check override option of master packing
			//if(totCaseVolume > 0 && totCaseWeight > 0)
			//if(totCaseVolume > 0 && totCaseWeight > 0 && totCaseWeight <= masterPackWeightPerOrder && "Y".equalsIgnoreCase(mPackAllow))
			//if(totCaseVolume > 0 && totCaseWeight > 0 &&  "Y".equalsIgnoreCase(mPackAllow) && (totCaseWeight <= masterPackWeightPerOrder || "Y".equalsIgnoreCase(masterPackOverride)))
			//if(totCaseVolume > 0 && totCaseWeight > 0 &&  "Y".equalsIgnoreCase(mPackAllow) && (totCaseWeight <= masterPackWeightPerOrder || "M".equalsIgnoreCase(dbShipType)))
			if(totCaseVolume > 0 && totCaseWeight > 0 && (totCaseWeight <= masterPackWeightPerOrder || "M".equalsIgnoreCase(shipType)))
			{
				masterPackAllow = true;
				if(totCaseWeight < masterPackWeight)
				{
					masterPackWeight = totCaseWeight;
				}
				
				String[] itmWeightVol = new String[3];
				String itemVolumeWeight = getPackItemVolumeWeight(masterPackWeight , totCaseVolume, "M", conn);
			
				itmWeightVol = itemVolumeWeight.split(":");
				
				if(Double.parseDouble(itmWeightVol[0]) != 0.0)
				{
					masterPackWeight = Double.parseDouble(itmWeightVol[0]);
				}
				if(Double.parseDouble(itmWeightVol[1]) != 0.0)
				{
					masterPackVolume = Double.parseDouble(itmWeightVol[1]);
				}
			}
			else
			{
				masterPackAllow = false;
				//mPackAllow = "N";
			}
			
			
			/*mPackAllow = genericUtility.getColumnValue("master_pack_allow",detailDom);
			mPackAllow = (mPackAllow != null && mPackAllow.length() > 0)?mPackAllow:"N";
			aPickAllow = genericUtility.getColumnValue("active_pick_allow",detailDom);
			aPickAllow = (aPickAllow != null && aPickAllow.length() > 0)?aPickAllow:"Y";
			stockToDoc = genericUtility.getColumnValue("stock_to_dock_allow",detailDom);
			stockToDoc = (stockToDoc != null && stockToDoc.length() > 0)?stockToDoc:"Y";*/
			
			//Changed by Rohan on 14/08/12 to get wave type info.end
			//System.out.println("mPackAllow:["+mPackAllow+"]aPickAllow["+aPickAllow+"]stockToDoc["+stockToDoc);
			//masterPackWeightPerOrder  = Double.parseDouble(discommon.getDisparams("999999","MASTER_PACK_WEIGHT_PER_ORDER",conn));
			if (maxWeight != null && maxWeight.length()> 0)
			{
				masterPackWeightPerOrder  = Double.parseDouble(maxWeight);
			}
			
			
			masterPackCountPerOrder = masterPackWeightPerOrder/masterPackWeight;
			System.out.println("CONF PALLET VOLUME["+palletVolume+"]PALLET MAX WEIGHT["+palletMaxWeight+"]");
			System.out.println("CONF MAX MASTER PACK COUNT["+masterPackCount+"]MAX MASTER PACK WEIGHT["+masterPackWeight+"]");
			System.out.println("CONF MASTER PACK WEIGHT PER ORDER["+masterPackWeightPerOrder+"]MAX MASTER PACK COUNT PER ORDER["+masterPackCountPerOrder+"]");
			System.out.println("IS MASTER PACK ALLOWED["+dbShipType+"]");
						
			int dataListLen = dataList.size();		
			for(int rplCtr = 0;rplCtr < dataListLen;rplCtr++)
			{
				HashMap dataMap = (HashMap)dataList.get(rplCtr);
				siteCode = (String)dataMap.get("site_code");
				itemCode = (String)dataMap.get("item_code");
				locCode = (String)dataMap.get("loc_code");
				lotNo = (String)dataMap.get("lot_no");
				lotSl = (String)dataMap.get("lot_sl");
				noArt =  (String)dataMap.get("no_art");
				System.out.println("Can not Cast");
				quantity =  (Double)dataMap.get("alloc_qty");
				System.out.println("Can not Cast"+quantity);
				stockToDock =  (String)dataMap.get("stock2_dock");
				//Changed By Pragyan 25/02/13 To get the valu of values from each line item wize.start
				mPackAllow = (String)dataMap.get("master_pack");
				aPickAllow =(String)dataMap.get("active_pick");
				pPickAllow =(String)dataMap.get("parcel_pick");
				//Changed By Pragyan 25/02/13 To get the valu of values from each line item wize.end
				expLevel = (String)dataMap.get("exp_lev");
				//Changed By Pragyan 13/03/13 to get Haz Items
				hazardous = (String)dataMap.get("hazard");
				//String sugCode = (String)dataMap.get("sugg_loc");
				sugCode = (String)dataMap.get("sugg_loc");
				invStat = (String)dataMap.get("inv_stat");
				invStat = invStat.trim();
				
				System.out.println("mPackAllow:["+mPackAllow+"]aPickAllow["+aPickAllow+"]stockToDoc["+stockToDoc+"]Parcel Pick["+pPickAllow+"]");
				System.out.println("SITE_CODE["+siteCode+"]\n LOCCODE["+locCode+"]\n Suggested Loc" +sugCode+
				"]ITEM CODE["+itemCode+"]\n LOTNO["+lotNo+"]\n LOT SL["+lotSl+"]\n ALLOC QUANTITY["+quantity+"]\n Exp Level["+expLevel+"]INVSTAT["+invStat+"]");
				//Changed By Pragyan 13/03/13 
				//HashMap itmVolumeMap = getItemVoumeMap(itemCode,lotNo,conn);
				itmVolumeMap = getItemVoumeMap(itemCode,lotNo,conn);
				//Changed By Pragyan 25/02/13 To get the valu of values from each line item wize.start
				//masterPackAllow = isMasterPackAllow;
				
				System.out.println("Check the weight and volume for master Pack ["+masterPackAllow+"]");
				
				if(!"M".equalsIgnoreCase(dbShipType) || !masterPackAllow)
				{
					mPackAllow = "N";
					System.out.println("Master Pack will not generate.........");
				}
				
				if(!"P".equalsIgnoreCase(dbShipType))
				{
					pPickAllow = "N";
					System.out.println("Parcel Pack will not generate.........");
				}
				//Changed By Pragyan 25/02/13 To get the valu of values from each line item wize.end
				
				//Changed By Pragyan 13/03/13.start
				System.out.println("mPackAllow["+mPackAllow+"]pPickAllow["+pPickAllow+"]transMode["+transMode+"]hazardous["+hazardous+"]totCaseCount["+totCaseCount+"]");
				if("Y".equalsIgnoreCase(mPackAllow) && "A".equalsIgnoreCase(transMode) && "Y".equalsIgnoreCase(hazardous) )
				{
					pPickAllow = "Y";
					mPackAllow = "N";
				}
				else if("Y".equalsIgnoreCase(mPackAllow) && !"A".equalsIgnoreCase(transMode) && "Y".equalsIgnoreCase(hazardous) )
				{
					if(totCaseCount < 2)
					{
						pPickAllow = "Y";
						mPackAllow = "N";
					}
					
				}
				dataMap.put("master_pack", mPackAllow);
				dataMap.put("parcel_pick", pPickAllow);

				
				System.out.println("Finally mPackAllow["+mPackAllow+"]pPickAllow["+pPickAllow+"]");
				
				//Changed By Pragyan 13/03/13.end
				//double packSize = (Double)itmVolumeMap.get("PACK_SIZE");//How many item contains in the Case
				packSize = (Double)itmVolumeMap.get("PACK_SIZE");//How many item contains in the Case
				//Changed By Pragyan 22/11/12 remove the floor as we need to get actual volume.start 
				/*	
			 	double perItemVolume = Math.floor((Double)itmVolumeMap.get("ITEM_SIZE"));
			 	double caseVolume = Math.floor((Double)itmVolumeMap.get("LOT_SIZE"));//Items Case Volume
				double caseWeight = Math.floor((Double)itmVolumeMap.get("PACK_WEIGHT"));
				double itemWeight = Math.floor((Double)itmVolumeMap.get("ITEM_WEIGHT"));*/
				/*double perItemVolume = (Double)itmVolumeMap.get("ITEM_SIZE");
				double caseVolume = (Double)itmVolumeMap.get("LOT_SIZE");//Items Case Volume
				double caseWeight = (Double)itmVolumeMap.get("PACK_WEIGHT");
				double itemWeight = (Double)itmVolumeMap.get("ITEM_WEIGHT");*/
				perItemVolume = (Double)itmVolumeMap.get("ITEM_SIZE");
				caseVolume = (Double)itmVolumeMap.get("LOT_SIZE");//Items Case Volume
				caseWeight = (Double)itmVolumeMap.get("PACK_WEIGHT");
				itemWeight = (Double)itmVolumeMap.get("ITEM_WEIGHT");
				//Changed By Pragyan 22/11/12 remove the floor as we need to get actual volume.end
				
				/*double activeCount = 0.0;
				double cashCount = 0.0;*/
				activeCount = 0.0;
				cashCount = 0.0;
				
				//Changed By Pragyan 13/03/13 .start
				/*ArrayList activeTempPickList = null;
				ArrayList caseTempPickList = null;
				ArrayList masterTempPackList = null;
				ArrayList masterTempList  = null;*/
				activeTempPickList = null;
				caseTempPickList = null;
				masterTempPackList = null;
				masterTempList  = null;
				//Changed By Pragyan 13/03/13 .end
				
				System.out.println("PACK_SIZE(SHIPPER SIZE)#####["+packSize+"]PER ITEM VOLUME###["+perItemVolume+"]EACH CASE VOLUME#####["+caseVolume+"]");
				System.out.println("PER ITEM WEIGHT#####["+itemWeight+"]EACH CASE WEIGHT###["+caseWeight+"]");
				
				
				//Changed By Pragyan 20/03/13 To initialize stock to dock with one veriable 
				//if("Y".equalsIgnoreCase(stockToDock) && "Y".equalsIgnoreCase(stockToDoc))
				if("Y".equalsIgnoreCase(stockToDock))
				{
					cashCount = Math.floor(quantity /packSize) ;
					if(cashCount >=1)
					{
						dataMap.put("no_art",String.valueOf(cashCount) );
					}
					else
					{
						dataMap.put("no_art",String.valueOf(1.0));
					}
					
					allStockToDockList.add(dataMap);
				}

				System.out.println("GOING --INSIDE MASTER PACK BLOCK--");
			
				//Changed By Pragyan 17-feb-12 not to generate case/master pick from active location
				//Changed By Pragyan 31/12/12 for Parcel Pick   invStat.equalsIgnoreCase(activePickInv) &&
				//if("Y".equalsIgnoreCase(mPackAllow) && quantity >= packSize && ("N".equalsIgnoreCase(stockToDock) || "N".equalsIgnoreCase(stockToDoc)))
				//if(("Y".equalsIgnoreCase(mPackAllow) || "Y".equalsIgnoreCase(pPickAllow)) && quantity >= packSize && ("N".equalsIgnoreCase(stockToDock) || "N".equalsIgnoreCase(stockToDoc)))
				if(!invStat.equalsIgnoreCase(activePickInv) && ("Y".equalsIgnoreCase(mPackAllow) || "Y".equalsIgnoreCase(pPickAllow)) && quantity >= packSize && ("N".equalsIgnoreCase(stockToDock) || "N".equalsIgnoreCase(stockToDoc)))
				{
					System.out.println("--INSIDE MASTER PACK BLOCK--");
					cashCount = Math.floor(quantity /packSize) ;
					activeCount = quantity % packSize;
					double mPackCounter = Math.floor(cashCount / masterPackCount);	
					double masterPackWeightCount = Math.floor(masterPackWeight/caseWeight);
					double totalCaseOnPallet = masterPackCount;
					double renCtr = 0;
					
					if("N".equalsIgnoreCase(aPickAllow) && activeCount > 0)
					{
						errString = getError(saleOrder,"INVORDQTY",conn);
						return errString;
					}
										
					System.out.println("TOTAL CASES TO MASTER PACK["+cashCount+"]");
					System.out.println("REMANING ITEMS TO ACTIVE PACK["+activeCount+"]");
					System.out.println("POSSIBLE MASTER PACK COUNT WEIGHT WIZE["+masterPackWeightCount+"]");
					
						int counter = 0;
						if(cashCount/mPackCounter != 0)
						{
							mPackCounter = mPackCounter + 1;
						}
						
						if(totalCaseOnPallet > cashCount)
						{
							totalCaseOnPallet = cashCount;
						}
						
						System.out.println("POSSIBLE MASTER PACK COUNT["+mPackCounter+"]");
						System.out.println("MASTER PACK STARTING COUNT["+totalCaseOnPallet+"]");
						
						//Changed By Pragyan 31/12/12 
						//if(cashCount >= 2)
						//if(totCaseCount >= 2)
						if(totCaseCount >= 2 || "Y".equalsIgnoreCase(pPickAllow))
						{	
							if("Y".equalsIgnoreCase(isSinglePickMasterPack))
							{
									/*Added by Ashish Sonawane on 7-jul-12 for Master packing with pallet wise [START]*/
									double cashCountPerPallet =Math.floor(  (cashCount * caseVolume)/palletVolume);
									totalCaseOnPallet = Math.floor(palletVolume/caseVolume);
									//double renCtr = 0;
									double volumeRmaining = Math.floor(caseVolume * cashCount); 
		
									if(totalCaseOnPallet > cashCount)
									{
										totalCaseOnPallet = cashCount;
									}
									
									if(cashCount/cashCountPerPallet != 0)
									{
										cashCountPerPallet = cashCountPerPallet + 1;
									}
									System.out.println("CASE COUNT PER PALLET["+cashCountPerPallet+"]");
									System.out.println("TOTAL POSSIBLE CASE ON THE PALLET["+totalCaseOnPallet+"]");	
									
									
									do
									{									
										
										
										double currentCaseVolume = totalCaseOnPallet * caseVolume;
										System.out.println("CURRENT CASE VOLUME TO STORE ["+currentCaseVolume+"]");
																		
										if(totalCaseOnPallet < 0)
										{
											
											break;
										}
										else
										{	
											if(allMasterPackList.size() > 0)
											{
												int allListLen = allMasterPackList.size();
												masterTempPackList = (ArrayList)allMasterPackList.get(allListLen -1);
												int innerListLen = masterTempPackList.size();
												Map tempMap = (HashMap)masterTempPackList.get(innerListLen -1);
											
												
													if(tempMap.containsKey("LAST_PACK_VOLUME"))
													{		
															double lastPackVolume = (Double)tempMap.get("LAST_PACK_VOLUME");
															double lastPackWeight = (Double)tempMap.get("LAST_PACK_WEIGHT");
															
															System.out.println("CASE LAST PACK VOLUME***************["+lastPackVolume+"]**********");
															System.out.println("CASE LAST PACK WEIGHT***************["+lastPackWeight+"]**********");
															
															if(lastPackVolume < palletVolume && lastPackWeight < palletMaxWeight)
															{
		
																double remainingVolume = palletVolume - lastPackVolume;
																System.out.println("REMAINING VOLUME TO ADJUST["+remainingVolume+"]");
																
																if(remainingVolume >= caseVolume)
																{
																	
																	if(remainingVolume >= currentCaseVolume)
																	{
																		System.out.println(">>REMAINING CASE VOLUME GRATER THEN CURRENT CASE VOLUME>>");
																		HashMap caseTempMap = (HashMap)dataMap.clone();	
																		caseTempMap.put("no_art", ""+totalCaseOnPallet);
																		caseTempMap.put("alloc_qty", totalCaseOnPallet * packSize	);
																		caseTempMap.put("LAST_PACK_VOLUME", (currentCaseVolume + lastPackVolume));
																		caseTempMap.put("LAST_PACK_WEIGHT", totalCaseOnPallet * caseWeight);								
																		masterTempPackList.add(caseTempMap);
																		int updLen = allMasterPackList.size()-1;
																		allMasterPackList.set(updLen,masterTempPackList);
																	}
																	else 
																	{
																		
																	
																		double quantityToBeStore = Math.floor(remainingVolume / caseVolume);
																		System.out.println("quantityToBeStore["+quantityToBeStore+"]");
																		System.out.println("Volume To be stored["+(remainingVolume + lastPackVolume)+"]");
																		HashMap caseTempMap = (HashMap)dataMap.clone();
																		caseTempMap.put("no_art", ""+quantityToBeStore);													
																		caseTempMap.put("alloc_qty", quantityToBeStore*packSize);
																		caseTempMap.put("LAST_PACK_VOLUME", (quantityToBeStore * caseVolume) + lastPackVolume);	
																		caseTempMap.put("LAST_PACK_WEIGHT", (Math.floor(quantityToBeStore / packSize)) * caseWeight);														
																		lastPackVolume = (quantityToBeStore * caseVolume) + lastPackVolume;
																		masterTempPackList.add(caseTempMap);
																																	
																		
																		System.out.println("caseTempPickList Values"+masterTempPackList.toString());
																		double requiredVolumeToStore = currentCaseVolume - (quantityToBeStore * caseVolume);
																		masterTempPackList = new ArrayList();
																		
																		
																		HashMap caseTempMap1 = (HashMap)dataMap.clone();
																		System.out.println("avilable quantityToBeStore["+quantityToBeStore+"]");
																		//Changed By Pragyan 17-Feb-13 to round the value up to decimal calculation 
																		//quantityToBeStore = Math.floor(requiredVolumeToStore / caseVolume);
																		quantityToBeStore = Math.round(requiredVolumeToStore / caseVolume);
																		
																		System.out.println("Avilable requiredVolumeToStore["+requiredVolumeToStore+"]");
																		System.out.println("Last Volume To be stored["+requiredVolumeToStore+"]");								
																		caseTempMap1.put("no_art", ""+quantityToBeStore);									
																		caseTempMap1.put("alloc_qty", quantityToBeStore*packSize);						
																										
																		if((requiredVolumeToStore + lastPackVolume) > palletVolume)
																		{
																			caseTempMap1.put("LAST_PACK_VOLUME", requiredVolumeToStore);
																			System.out.println("&&&& if After storing 2nd  Last Pack Volume  Volume ["+requiredVolumeToStore+"]");
																		}
																		else
																		{
																			caseTempMap1.put("LAST_PACK_VOLUME", requiredVolumeToStore + lastPackVolume);
																			System.out.println("&&&& else After storing 2nd  Last Pack Volume  Volume ["+requiredVolumeToStore + lastPackVolume+"]");
																		}													
																		caseTempMap1.put("LAST_PACK_WEIGHT", (Math.floor(quantityToBeStore / packSize)) * caseWeight);
																		masterTempPackList.add(caseTempMap1);
																		int updLen1 = masterTempPackList.size()-1;
																		allMasterPackList.add(masterTempPackList);
																	
																	}
																}
																else
																{
																	
																	
																	masterTempPackList = new ArrayList();
																	HashMap caseTempMap = (HashMap)dataMap.clone();			
																	caseTempMap.put("no_art", ""+totalCaseOnPallet);
																	caseTempMap.put("alloc_qty", totalCaseOnPallet * packSize	);
																	caseTempMap.put("LAST_PACK_VOLUME", (totalCaseOnPallet * caseVolume));	
																	caseTempMap.put("LAST_PACK_WEIGHT", totalCaseOnPallet * caseWeight);
																	masterTempPackList.add(caseTempMap);
																	allMasterPackList.add(masterTempPackList);
																	
																}
		
															}
															else
															{
																System.out.println("---LAST PACK VOLUME FULL ------");
																masterTempPackList = new ArrayList();
																HashMap caseTempMap = (HashMap)dataMap.clone();			
																caseTempMap.put("no_art", ""+totalCaseOnPallet);
																caseTempMap.put("alloc_qty", totalCaseOnPallet * packSize	);													
																caseTempMap.put("LAST_PACK_VOLUME", (totalCaseOnPallet * caseVolume) + lastPackVolume);
																caseTempMap.put("LAST_PACK_WEIGHT", totalCaseOnPallet * caseWeight);
																masterTempPackList.add(caseTempMap);
																allMasterPackList.add(masterTempPackList);
		
															}
													}
												
											}
											else
											{
												System.out.println("IN CASE MAP DOES NOT EXIST............");
												masterTempPackList = new ArrayList();
												HashMap caseTempMap = (HashMap)dataMap.clone();			
												caseTempMap.put("no_art", ""+totalCaseOnPallet);
												caseTempMap.put("alloc_qty", totalCaseOnPallet * packSize	);
												caseTempMap.put("LAST_PACK_VOLUME", (totalCaseOnPallet * caseVolume));
												caseTempMap.put("LAST_PACK_WEIGHT", totalCaseOnPallet * caseWeight);
												masterTempPackList.add(caseTempMap);
												allMasterPackList.add(masterTempPackList);				
											}
								
											volumeRmaining = volumeRmaining - totalCaseOnPallet * caseVolume;
											System.out.println("case volumes  reamining["+volumeRmaining+"]");
											
											if(totalCaseOnPallet < (volumeRmaining/caseVolume))
											{
											}
											else
											{
												totalCaseOnPallet = (volumeRmaining/caseVolume);
											}
											
											//Changed by Rohan on 24-11-11 [WMIESUN006] For bug Fixing.start
											if(volumeRmaining == 0.0)
											{
												break;
											}
											//Changed by Rohan on 24-11-11 [WMIESUN006] For bug Fixing.end
											
										}					
										System.out.println("AFTER CALCULATING CASE ON PALLET["+totalCaseOnPallet+"]");
										renCtr ++ ;
									}
									while(renCtr <= cashCountPerPallet);	
									
									
									//Change by new logic implmented by pragyan  for master packing.start>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
									
									
									/*HashMap dataMap = (HashMap)dataList.get(i);
									double cashCount = (Double)dataMap.get("alloc_qty");
									double caseWeight = (Double)dataMap.get("case_weight");
									double caseVolume = (Double)dataMap.get("case_volume");
									
								
									double packSize = 10;*/
									//Logic stands clear.start
									int allMasterListlen = allMasterList.size();
									
									if(!"Y".equalsIgnoreCase(pPickAllow))
									{
									
									
											//To store best FIT Algorithem and NFT Next Fit Algrthem as per user requirement.
											if(allMasterListlen > 0)
											{
												if("Y".equalsIgnoreCase(isMasterPackBestFit))
												{
												
												
														for(int j = 0 ;j < allMasterListlen ; j++)
														{
															
															ArrayList tempList = (ArrayList)allMasterList.get(j);
															System.out.println("Loop============"+j);
															System.out.println("Remaining cashCount Count+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ["+cashCount+"]");
															
															if(cashCount > 0)
															{
															
																	HashMap tempMap = (HashMap)tempList.get(tempList.size() -1);
																	
																	if(cashCount > 0)
																	{
																	
																			if(tempMap.containsKey("LAST_PACK_WEIGHT") && tempMap.containsKey("LAST_PACK_VOLUME") && tempMap.containsKey("LAST_PACK_COUNT"))
																			{
																				System.out.println("Item Name"+tempMap.get("item"));
																				System.out.println("Alloc Qty"+tempMap.get("alloc_qty"));
																				
																				double lastPackWeight = (Double)tempMap.get("LAST_PACK_WEIGHT");
																				double lastPackVolume = (Double)tempMap.get("LAST_PACK_VOLUME");
																				double lastPackCount = (Double)tempMap.get("LAST_PACK_COUNT");
																				System.out.println("Last Pack Volume#############["+tempMap.get("LAST_PACK_VOLUME")+"]");
																				System.out.println("Last Pack Weight#############["+tempMap.get("LAST_PACK_WEIGHT")+"]");
																				System.out.println("Last Pack Count#############["+tempMap.get("LAST_PACK_COUNT")+"]");
																				
																				double remainingWeight = masterPackWeight - lastPackWeight;
																				double remainingVolume = masterPackVolume  - 	lastPackVolume;	
																				if(remainingWeight >= caseWeight && remainingVolume >= caseVolume && lastPackCount < masterPackCount)
																				{
																					
																										
																						double caseToBeStore = Math.floor(remainingWeight / caseWeight);	
																						double caseToBeStore1 = Math.floor(remainingVolume / caseVolume);
																						
																						if(caseToBeStore > caseToBeStore1)
																						{
																							caseToBeStore = caseToBeStore1;
																						}
																						
																						if(caseToBeStore > cashCount)
																						{
																							caseToBeStore = cashCount;
																						}
																						
																						if((lastPackCount + caseToBeStore) <= masterPackCount)
																						{
																						
																							HashMap caseTempMap = (HashMap)dataMap.clone();	
																							caseTempMap.put("no_art", ""+caseToBeStore);
																							caseTempMap.put("alloc_qty", caseToBeStore * packSize);
																							caseTempMap.put("LAST_PACK_WEIGHT",lastPackWeight + (caseToBeStore * caseWeight));
																							caseTempMap.put("LAST_PACK_VOLUME", (caseToBeStore * caseVolume) + lastPackVolume);
																							caseTempMap.put("LAST_PACK_COUNT", (lastPackCount + caseToBeStore));	
																							caseTempMap.put("CASE_VOLUME_TOT", (caseToBeStore * caseVolume));
																							caseTempMap.put("CASE_WEIGHT_TOT", (caseToBeStore * caseWeight));
																							
																							tempList.add(caseTempMap);
																							cashCount = cashCount - caseToBeStore;
																					
																							allMasterList.set(j,tempList);
																						}
																				}
																			}
																	}
																	else
																	{
																		break;
																	}
																//}
															}
															else
															{
																break;
															}
														}
												}
												else
												{
													ArrayList tempList = (ArrayList)allMasterList.get(allMasterListlen-1);
													System.out.println("Remaining cashCount Count+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ["+cashCount+"]");
													
													if(cashCount > 0)
													{
													
															HashMap tempMap = (HashMap)tempList.get(tempList.size() -1);
															
															if(cashCount > 0)
															{
															
																	if(tempMap.containsKey("LAST_PACK_WEIGHT") && tempMap.containsKey("LAST_PACK_VOLUME") && tempMap.containsKey("LAST_PACK_COUNT"))
																	{
																		System.out.println("Item Name"+tempMap.get("item"));
																		System.out.println("Alloc Qty"+tempMap.get("alloc_qty"));
																		
																		double lastPackWeight = (Double)tempMap.get("LAST_PACK_WEIGHT");
																		double lastPackVolume = (Double)tempMap.get("LAST_PACK_VOLUME");
																		double lastPackCount = (Double)tempMap.get("LAST_PACK_COUNT");
																		System.out.println("Last Pack Volume#############["+tempMap.get("LAST_PACK_VOLUME")+"]");
																		System.out.println("Last Pack Weight#############["+tempMap.get("LAST_PACK_WEIGHT")+"]");
																		System.out.println("Last Pack Count#############["+tempMap.get("LAST_PACK_COUNT")+"]");
																		
																		double remainingWeight = masterPackWeight - lastPackWeight;
																		double remainingVolume = masterPackVolume  - 	lastPackVolume;	
																		if(remainingWeight >= caseWeight && remainingVolume >= caseVolume && lastPackCount < masterPackCount)
																		{
																			
																								
																				double caseToBeStore = Math.floor(remainingWeight / caseWeight);	
																				double caseToBeStore1 = Math.floor(remainingVolume / caseVolume);
																				
																				if(caseToBeStore > caseToBeStore1)
																				{
																					caseToBeStore = caseToBeStore1;
																				}
																				
																				if(caseToBeStore > cashCount)
																				{
																					caseToBeStore = cashCount;
																				}
																				
																				if((lastPackCount + caseToBeStore) <= masterPackCount)
																				{
																				
																					HashMap caseTempMap = (HashMap)dataMap.clone();	
																					caseTempMap.put("no_art", ""+caseToBeStore);
																					caseTempMap.put("alloc_qty", caseToBeStore * packSize);
																					caseTempMap.put("LAST_PACK_WEIGHT",lastPackWeight + (caseToBeStore * caseWeight));
																					caseTempMap.put("LAST_PACK_VOLUME", (caseToBeStore * caseVolume) + lastPackVolume);
																					caseTempMap.put("LAST_PACK_COUNT", (lastPackCount + caseToBeStore));	
																					caseTempMap.put("CASE_VOLUME_TOT", (caseToBeStore * caseVolume));
																					caseTempMap.put("CASE_WEIGHT_TOT", (caseToBeStore * caseWeight));
																					
																					tempList.add(caseTempMap);
																					cashCount = cashCount - caseToBeStore;
																			
																					allMasterList.set(allMasterListlen-1,tempList);
																				}
																		}
																	}
															}
															else
															{
																break;
															}
														//}
													}
													else
													{
														break;
													}
												}
											}
											//To store best FIT Algorithem and NFT Next Fit Algrthem as per user requirement.end
											//Logic stands.end
											
															
											System.out.println("Now cashCount Count======================================================================= ["+cashCount+"]");
											
											if(cashCount > 0)
											{
											
													mPackCounter = Math.floor(cashCount / masterPackCount);	
													totalCaseOnPallet = masterPackCount;
													counter = 0;
													
													if(cashCount/mPackCounter != 0)
													{
														mPackCounter = mPackCounter + 1;
													}
												
													if(totalCaseOnPallet > cashCount)
													{
														totalCaseOnPallet = cashCount;
													}
													
													System.out.println("mPackCounter["+mPackCounter+"]");
													masterPackWeightCount = Math.floor(masterPackWeight/caseWeight);
													System.out.println("masterPackWeightCount..............["+masterPackWeightCount+"]");
													System.out.println("totalCaseOnPallet["+totalCaseOnPallet+"]");
													double masterPackVolumeCount = Math.floor(masterPackVolume/caseVolume);
													System.out.println("masterPackVolumeCount--------------["+masterPackVolumeCount+"]");
													///New Veraibles Start
													
													//// New Veriables End
													
													if(masterPackWeightCount > masterPackVolumeCount)
													{
														masterPackWeightCount = masterPackVolumeCount;
													}
													
													
													do
													{
														double currentCaseCount = 	totalCaseOnPallet;			
														
														System.out.println("totalCaseOnPallet["+totalCaseOnPallet+"]");
														double casesWeightCount = Math.floor(currentCaseCount/masterPackWeightCount);
														System.out.println("CURRENT CASE COUNT["+currentCaseCount+"]");
																						
														double wCounter = 0;
														if(masterPackWeightCount > currentCaseCount)
														{
															System.out.println("masterPackWeightCount---"+masterPackWeightCount);
															masterPackWeightCount = currentCaseCount;
														}
														
														do
														{
															if(allMasterList.size() > 0)
															{
																int allListLen = allMasterList.size();
																masterTempList = (ArrayList)allMasterList.get(allListLen -1);
																int innerListLen = masterTempList.size();
																Map tempMap = (HashMap)masterTempList.get(innerListLen -1);							
											
																	if(tempMap.containsKey("LAST_PACK_WEIGHT") && tempMap.containsKey("LAST_PACK_VOLUME") && tempMap.containsKey("LAST_PACK_COUNT"))
																	{		
																			double remainingWeight = 0.0;
																			double remainingVolume = 0.0;
																			double lastPackWeight = (Double)tempMap.get("LAST_PACK_WEIGHT");
																			double lastPackVolume = (Double)tempMap.get("LAST_PACK_VOLUME");
																			double lastPackCount = (Double)tempMap.get("LAST_PACK_COUNT");
																			System.out.println("LAST PACK WEIGHT FROM THE MAP["+lastPackWeight+"]");
																			System.out.println("LAST PACK VOLUME FROM THE MAP>>>>>>>>>>>>["+lastPackVolume+"]");
																			double currentWeight = masterPackWeightCount * caseWeight;
																			double currentCaseVolume = masterPackWeightCount * caseVolume;
																			
																			
																			System.out.println("CURRENT WEIGHT TO STORE["+currentWeight+"]");
																			System.out.println("CURRENT VOLUME TO STORE["+currentCaseVolume+"]");
																			
																			if(lastPackWeight < masterPackWeight && lastPackVolume < masterPackVolume && lastPackCount < masterPackCount)
																			{
																				remainingWeight = masterPackWeight - lastPackWeight;
																				remainingVolume = masterPackVolume  - 	lastPackVolume;	
																				
																				System.out.println("REMAINING WEIGHT TO STORE ["+remainingWeight+"]");
																				System.out.println("REMAINING VOLUME TO STORE ["+remainingVolume+"]");
																				
											
																				if(remainingWeight >= caseWeight && remainingVolume >= caseVolume )
																				{
																					if(remainingWeight >= currentWeight && remainingVolume >= currentCaseVolume && (lastPackCount + masterPackWeightCount) <= masterPackCount)
																					{
																						
																						HashMap caseTempMap = (HashMap)dataMap.clone();			
																						caseTempMap.put("no_art", ""+masterPackWeightCount);
																						caseTempMap.put("alloc_qty", masterPackWeightCount * packSize	);
																						caseTempMap.put("LAST_PACK_WEIGHT", lastPackWeight + (masterPackWeightCount * caseWeight));
																						caseTempMap.put("LAST_PACK_VOLUME", (currentCaseVolume + lastPackVolume));
																						caseTempMap.put("LAST_PACK_COUNT", (lastPackCount + masterPackWeightCount));
																						caseTempMap.put("CASE_VOLUME_TOT", (masterPackWeightCount * caseVolume));
																						caseTempMap.put("CASE_WEIGHT_TOT", (masterPackWeightCount * caseWeight));
																						masterTempList.add(caseTempMap);
																						int updLen = allMasterList.size()-1;
																						allMasterList.set(updLen,masterTempList);
																						
																					}
																					else
																					{
																										
																						double caseToBeStore = Math.floor(remainingWeight / caseWeight);															
																						HashMap caseTempMap = (HashMap)dataMap.clone();	
																						caseTempMap.put("no_art", ""+caseToBeStore);
																						caseTempMap.put("alloc_qty", caseToBeStore * packSize);
																						caseTempMap.put("LAST_PACK_WEIGHT",lastPackWeight + (caseToBeStore * caseWeight));
																						caseTempMap.put("LAST_PACK_VOLUME", (caseToBeStore * caseVolume) + lastPackVolume);	
																						caseTempMap.put("LAST_PACK_COUNT", (lastPackCount + caseToBeStore));
																						caseTempMap.put("CASE_VOLUME_TOT", (caseToBeStore * caseVolume));
																						caseTempMap.put("CASE_WEIGHT_TOT", (caseToBeStore * caseWeight));
																						masterTempList.add(caseTempMap);
																						lastPackWeight = lastPackWeight + (caseToBeStore * caseWeight);
																						double requiredVolumeToStore = currentCaseVolume - (caseToBeStore * caseVolume);
																						double requiredWeightToStore = currentWeight - (caseToBeStore * caseWeight);
																						masterTempList = new ArrayList();
																						HashMap caseTempMap1 = (HashMap)dataMap.clone();	
																						caseToBeStore = Math.floor(requiredWeightToStore / caseWeight);
																						caseTempMap1.put("no_art", ""+caseToBeStore);
																						caseTempMap1.put("alloc_qty", caseToBeStore * packSize);
																						
																						if((requiredWeightToStore + lastPackWeight) > masterPackWeight)
																						{
																							caseTempMap1.put("LAST_PACK_WEIGHT", requiredWeightToStore);
																						}
																						else
																						{
																							caseTempMap1.put("LAST_PACK_WEIGHT", (requiredWeightToStore + lastPackWeight));
																						}
																						
																						if((requiredVolumeToStore + lastPackVolume) > masterPackVolume)
																						{
																							caseTempMap1.put("LAST_PACK_COUNT", (lastPackCount + caseToBeStore));
																							caseTempMap1.put("LAST_PACK_VOLUME", requiredVolumeToStore);
																							System.out.println("&&&& if After storing 2nd  Last Pack Volume  Volume ["+requiredVolumeToStore+"]");
																						}
																						else
																						{
																							caseTempMap1.put("LAST_PACK_COUNT", (lastPackCount + caseToBeStore));
																							caseTempMap1.put("LAST_PACK_VOLUME", requiredVolumeToStore + lastPackVolume);
																							System.out.println("&&&& else After storing 2nd  Last Pack Volume  Volume ["+requiredVolumeToStore + lastPackVolume+"]");
																						}		
																						caseTempMap1.put("CASE_VOLUME_TOT", (caseToBeStore * caseVolume));
																						caseTempMap1.put("CASE_WEIGHT_TOT", (caseToBeStore * caseWeight));
																						masterTempList.add(caseTempMap1);
																						int updLen1 = masterTempList.size()-1;
																						allMasterList.add(masterTempList);
																						
																					}
																				}
																				else
																				{
																					masterTempList = new ArrayList();
																					HashMap caseTempMap = (HashMap)dataMap.clone();	
																					caseTempMap.put("no_art", ""+masterPackWeightCount);
																					caseTempMap.put("alloc_qty", masterPackWeightCount * packSize	);				
																					caseTempMap.put("LAST_PACK_WEIGHT", masterPackWeightCount * caseWeight);	
																					caseTempMap.put("LAST_PACK_VOLUME", (masterPackWeightCount * caseVolume));
																					caseTempMap.put("CASE_VOLUME_TOT", (masterPackWeightCount * caseVolume));
																					caseTempMap.put("CASE_WEIGHT_TOT", (masterPackWeightCount * caseWeight));
																					caseTempMap.put("LAST_PACK_COUNT", masterPackWeightCount);
																					masterTempList.add(caseTempMap);
																					allMasterList.add(masterTempList);
																				}
																			}
																			else
																			{
																				masterTempList = new ArrayList();
																				HashMap caseTempMap = (HashMap)dataMap.clone();	
																				caseTempMap.put("no_art", ""+masterPackWeightCount);
																				caseTempMap.put("alloc_qty", masterPackWeightCount * packSize	);				
																				caseTempMap.put("LAST_PACK_WEIGHT", masterPackWeightCount * caseWeight);		
																				caseTempMap.put("LAST_PACK_VOLUME", (masterPackWeightCount * caseVolume));
																				caseTempMap.put("CASE_VOLUME_TOT", (masterPackWeightCount * caseVolume));
																				caseTempMap.put("CASE_WEIGHT_TOT", (masterPackWeightCount * caseWeight));
																				caseTempMap.put("LAST_PACK_COUNT", masterPackWeightCount);
																				masterTempList.add(caseTempMap);
																				allMasterList.add(masterTempList);
											
																			}
																	}
																
															}
															else
															{
																
																
																System.out.println("### MASTER PACK MAP Doesn't Exist.......");
																masterTempList = new ArrayList();
																HashMap caseTempMap = (HashMap)dataMap.clone();			
																caseTempMap.put("no_art", ""+masterPackWeightCount);
																caseTempMap.put("alloc_qty", masterPackWeightCount * packSize	);
																caseTempMap.put("LAST_PACK_WEIGHT", masterPackWeightCount * caseWeight);
																caseTempMap.put("LAST_PACK_VOLUME", (masterPackWeightCount * caseVolume));
																caseTempMap.put("CASE_VOLUME_TOT", (masterPackWeightCount * caseVolume));
																caseTempMap.put("CASE_WEIGHT_TOT", (masterPackWeightCount * caseWeight));
																caseTempMap.put("LAST_PACK_COUNT", masterPackWeightCount);
																masterTempList.add(caseTempMap);
																allMasterList.add(masterTempList);									
															}
																				
															
															System.out.println("masterPackWeightCount**************["+masterPackWeightCount+"]");
															
															
															currentCaseCount = currentCaseCount - masterPackWeightCount;
											
															System.out.println("currentCaseCount+++++++++++++++["+currentCaseCount+"]");
											
															if((currentCaseCount /masterPackWeightCount) < 1)
															{						
																System.out.println("masterPackWeightCount**************["+masterPackWeightCount+"]");
																
																masterPackWeightCount = currentCaseCount;
															}
											
															if(currentCaseCount <= 0)
															{
																System.out.println("currentCaseCount===============["+currentCaseCount+"]");
																break;
															}
															
															if(masterPackWeightCount <= 0)
															{
																System.out.println("masterPackWeightCount===============["+masterPackWeightCount+"]");
																break;
															}
											
															
															
															System.out.println("MASTER PACK COUNTER["+wCounter+"]MASTER PACK WEIGHT COUNT["+masterPackWeightCount+"]");
															wCounter++;
														}		
														while(wCounter <= casesWeightCount);
														/////////////////////End Weight Wize
														masterPackWeightCount = Math.floor(masterPackWeight/caseWeight);
														System.out.println("masterPackWeightCount--new "+masterPackWeightCount);
														cashCount = cashCount - totalCaseOnPallet;
														if(cashCount / masterPackCount >=1)
														{
															totalCaseOnPallet = masterPackCount;
														}
														else
														{
															totalCaseOnPallet = cashCount;
														}
														
														if(totalCaseOnPallet <=0)
														{
															break;
														}
														
														counter++;
														System.out.println("REMAINING CASE COUNT["+cashCount+"]");
														System.out.println("CURRENT PACKET COUNTER"+mPackCounter+"]COUNT["+counter+"]");
											
												}		
												while(counter < mPackCounter);
											}
									}//If parcelPack Not allowed
									
							
								
							//Change by new logic implmented by pragyan  for master packing.end>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
							}//if("Y".equalsIgnoreCase(isSinglePickMasterPack))
							/*Added by Ashish Sonawane on 7-jul-12 for Master packing with pallet wise [END]*/
							/*commented by Ashish Sonawane on 7-jul-12 as per Manoharan sir [START] */
							else
							{	
								do
								{
									double currentCaseCount = 	totalCaseOnPallet;				
									System.out.println("totalCaseOnPallet["+totalCaseOnPallet+"]");
									double casesWeightCount = Math.floor(currentCaseCount/masterPackWeightCount);
									System.out.println("CURRENT CASE COUNT["+currentCaseCount+"]");
																	
									double wCounter = 0;
									if(masterPackWeightCount > currentCaseCount)
									{
										System.out.println("masterPackWeightCount---"+masterPackWeightCount);
										masterPackWeightCount = currentCaseCount;
									}
									
									do
									{
										if(allMasterPackList.size() > 0)
										{
											int allListLen = allMasterPackList.size();
											masterTempPackList = (ArrayList)allMasterPackList.get(allListLen -1);
											int innerListLen = masterTempPackList.size();
											Map tempMap = (HashMap)masterTempPackList.get(innerListLen -1);							
						
												if(tempMap.containsKey("LAST_PACK_WEIGHT"))
												{		
														double remainingWeight = 0.0;
														double lastPackWeight = (Double)tempMap.get("LAST_PACK_WEIGHT");
														System.out.println("LAST PACK WEIGHT FROM THE MAP["+lastPackWeight+"]");
														double currentWeight = masterPackWeightCount * caseWeight;
														System.out.println("CURRENT WEIGHT TO STORE["+currentWeight+"]");
														
														if(lastPackWeight < masterPackWeight)
														{
															remainingWeight = masterPackWeight - lastPackWeight;
															System.out.println("REMAINING WEIGHT TO STORE ["+remainingWeight+"]");
															
	
															if(remainingWeight >= caseWeight)
															{
																if(remainingWeight >= currentWeight)
																{
																	
																	HashMap caseTempMap = (HashMap)dataMap.clone();			
																	caseTempMap.put("no_art", ""+masterPackWeightCount);
																	caseTempMap.put("alloc_qty", masterPackWeightCount * packSize	);
																	caseTempMap.put("LAST_PACK_WEIGHT", lastPackWeight + (masterPackWeightCount * caseWeight));
																	masterTempPackList.add(caseTempMap);
																	int updLen = allMasterPackList.size()-1;
																	allMasterPackList.set(updLen,masterTempPackList);
																	
																}
																else
																{
																					
																	double caseToBeStore = Math.floor(remainingWeight / caseWeight);															
																	HashMap caseTempMap = (HashMap)dataMap.clone();	
																	caseTempMap.put("no_art", ""+caseToBeStore);
																	caseTempMap.put("alloc_qty", caseToBeStore * packSize);
																	caseTempMap.put("LAST_PACK_WEIGHT",lastPackWeight + (caseToBeStore * caseWeight));
																	masterTempPackList.add(caseTempMap);
																	lastPackWeight = lastPackWeight + (caseToBeStore * caseWeight);
																																
																	double requiredWeightToStore = currentWeight - (caseToBeStore * caseWeight);
																	masterTempPackList = new ArrayList();
																	HashMap caseTempMap1 = (HashMap)dataMap.clone();	
																	caseToBeStore = Math.floor(requiredWeightToStore / caseWeight);
																	caseTempMap1.put("no_art", ""+caseToBeStore);
																	caseTempMap1.put("alloc_qty", caseToBeStore * packSize);
																	
																	if((requiredWeightToStore + lastPackWeight) > masterPackWeight)
																	{
																		caseTempMap1.put("LAST_PACK_WEIGHT", requiredWeightToStore);
																	}
																	else
																	{
																		caseTempMap1.put("LAST_PACK_WEIGHT", (requiredWeightToStore + lastPackWeight));
																	}
																	masterTempPackList.add(caseTempMap1);
																	int updLen1 = masterTempPackList.size()-1;
																	allMasterPackList.add(masterTempPackList);
																	
																}
															}
															else
															{
																masterTempPackList = new ArrayList();
																HashMap caseTempMap = (HashMap)dataMap.clone();	
																caseTempMap.put("no_art", ""+masterPackWeightCount);
																caseTempMap.put("alloc_qty", masterPackWeightCount * packSize	);				
																caseTempMap.put("LAST_PACK_WEIGHT", masterPackWeightCount * caseWeight);								
																masterTempPackList.add(caseTempMap);
																allMasterPackList.add(masterTempPackList);
															}
														}
														else
														{
															masterTempPackList = new ArrayList();
															HashMap caseTempMap = (HashMap)dataMap.clone();	
															caseTempMap.put("no_art", ""+masterPackWeightCount);
															caseTempMap.put("alloc_qty", masterPackWeightCount * packSize	);				
															caseTempMap.put("LAST_PACK_WEIGHT", masterPackWeightCount * caseWeight);								
															masterTempPackList.add(caseTempMap);
															allMasterPackList.add(masterTempPackList);
						
														}
												}
											
										}
										else
										{
											
											
											System.out.println("### MASTER PACK MAP Doesn't Exist.......");
											masterTempPackList = new ArrayList();
											HashMap caseTempMap = (HashMap)dataMap.clone();			
											caseTempMap.put("no_art", ""+masterPackWeightCount);
											caseTempMap.put("alloc_qty", masterPackWeightCount * packSize	);
											caseTempMap.put("LAST_PACK_WEIGHT", masterPackWeightCount * caseWeight);
											masterTempPackList.add(caseTempMap);
											allMasterPackList.add(masterTempPackList);									
										}
															
										
										System.out.println("masterPackWeightCount**************["+masterPackWeightCount+"]");
										
										
										currentCaseCount = currentCaseCount - masterPackWeightCount;
	
										System.out.println("currentCaseCount+++++++++++++++["+currentCaseCount+"]");
	
										if((currentCaseCount /masterPackWeightCount) < 1)
										{						
											System.out.println("masterPackWeightCount**************["+masterPackWeightCount+"]");
											
											masterPackWeightCount = currentCaseCount;
										}
	
										if(currentCaseCount <= 0)
										{
											System.out.println("currentCaseCount===============["+currentCaseCount+"]");
											break;
										}
										
										if(masterPackWeightCount <= 0)
										{
											System.out.println("masterPackWeightCount===============["+masterPackWeightCount+"]");
											break;
										}
	
										
										
										System.out.println("MASTER PACK COUNTER["+wCounter+"]MASTER PACK WEIGHT COUNT["+masterPackWeightCount+"]");
										wCounter++;
									}		
									while(wCounter <= casesWeightCount);
									/////////////////////End Weight Wize
									masterPackWeightCount = Math.floor(masterPackWeight/caseWeight);
									System.out.println("masterPackWeightCount--new "+masterPackWeightCount);
									cashCount = cashCount - totalCaseOnPallet;
									if(cashCount / masterPackCount >=1)
									{
										totalCaseOnPallet = masterPackCount;
									}
									else
									{
										totalCaseOnPallet = cashCount;
									}
									
									if(totalCaseOnPallet <=0)
									{
										break;
									}
									
									counter++;
									System.out.println("REMAINING CASE COUNT["+cashCount+"]");
									System.out.println("CURRENT PACKET COUNTER"+mPackCounter+"]COUNT["+counter+"]");
	
							}		
							while(counter < mPackCounter);
						}	
						
					}
					else
					{
						mPackAllow = "N";
					}
							
					/*else
					{
						masterPackAllow = false;
					}*/

				}
				//changed by Rohan on 4-12-11 [WMIESUN006] for Master Packing.end
				
				//Changed by Rohan on 4-12-11 [WMIESUN006] for Master Packing 
				//if(quantity >= packSize)
				//System.out.println("masterPackAllow"+masterPackAllow+"quantity"+quantity+"packSize"+packSize+"stockToDock"+stockToDock);
				//Changed By Pragyan 17-feb-12 not to generate case/master pick from active location 
				//Changed by rohan on 14/08/12 to generate task depending upon wave type info
				//if(!masterPackAllow && quantity >= packSize && stockToDock.equalsIgnoreCase("N"))
				//if(("N".equalsIgnoreCase(mPackAllow)) && (quantity >= packSize || "N".equalsIgnoreCase(aPickAllow)) && (stockToDock.equalsIgnoreCase("N") || "N".equalsIgnoreCase(stockToDoc)))
				//if(("N".equalsIgnoreCase(mPackAllow)) && ("N".equalsIgnoreCase(pPickAllow)) && (quantity >= packSize || "N".equalsIgnoreCase(aPickAllow)) && (stockToDock.equalsIgnoreCase("N") || "N".equalsIgnoreCase(stockToDoc)))
				if(!invStat.equalsIgnoreCase(activePickInv) && ("N".equalsIgnoreCase(mPackAllow)) && ("N".equalsIgnoreCase(pPickAllow)) && (quantity >= packSize || "N".equalsIgnoreCase(aPickAllow)) && (stockToDock.equalsIgnoreCase("N") || "N".equalsIgnoreCase(stockToDoc)))
				{
					System.out.println("--INSIDE CASE PACK BLOCK--");
					
					cashCount = Math.floor(quantity /packSize) ;
					activeCount = quantity % packSize;
					double currentvolumeActive = cashCount * caseVolume;
					System.out.println("TOTAL CASES TO MASTER PACK["+cashCount+"]");
					System.out.println("REMANING ITEMS TO ACTIVE PACK["+activeCount+"]");
					System.out.println("CURRENT TOTAL VOLUME TO STORE["+currentvolumeActive+"]");
					
					//Changed by Rohan on 16/08/12 to generate error if customer to not accept actives.start
					if("N".equalsIgnoreCase(aPickAllow) && activeCount > 0)
					{
						errString = getError(saleOrder,"INVORDQTY",conn);
						return errString;
					}
					//Changed by Rohan on 16/08/12 to generate error if customer to not accept actives.end
					
					if(cashCount > 0)
					{

							double cashCountPerPallet =Math.floor(  (cashCount * caseVolume)/palletVolume);
							double totalCaseOnPallet = Math.floor(palletVolume/caseVolume);
							double renCtr = 0;
							double volumeRmaining = Math.floor(caseVolume * cashCount); 

							if(totalCaseOnPallet > cashCount)
							{
								totalCaseOnPallet = cashCount;
							}
							
							if(cashCount/cashCountPerPallet != 0)
							{
								cashCountPerPallet = cashCountPerPallet + 1;
							}
							System.out.println("CASE COUNT PER PALLET["+cashCountPerPallet+"]");
							System.out.println("TOTAL POSSIBLE CASE ON THE PALLET["+totalCaseOnPallet+"]");	
							
							
							do
							{									
								
								
								double currentCaseVolume = totalCaseOnPallet * caseVolume;
								System.out.println("CURRENT CASE VOLUME TO STORE ["+currentCaseVolume+"]");
																
								if(totalCaseOnPallet < 0)
								{
									
									break;
								}
								else
								{	
									if(allCasePickList.size() > 0)
									{
										//Changed by Rohan on 24-11-11 [WM1ESUN006].For bug fixing.start
										/*
										caseTempPickList = (ArrayList)allCasePickList.get(allListLen -1);
										Map tempMap = (HashMap)caseTempPickList.get(caseTempPickList.size() -1);							
                                        */
										int allListLen = allCasePickList.size();
										caseTempPickList = (ArrayList)allCasePickList.get(allListLen -1);
										int innerListLen = caseTempPickList.size();
										Map tempMap = (HashMap)caseTempPickList.get(innerListLen -1);
										//Changed by Rohan on 24-11-11 [WM1ESUN006]For bug fixing.end
										
											if(tempMap.containsKey("LAST_PACK_VOLUME"))
											{		
													double lastPackVolume = (Double)tempMap.get("LAST_PACK_VOLUME");
													double lastPackWeight = (Double)tempMap.get("LAST_PACK_WEIGHT");
													
													System.out.println("CASE LAST PACK VOLUME***************["+lastPackVolume+"]**********");
													System.out.println("CASE LAST PACK WEIGHT***************["+lastPackWeight+"]**********");
													
													if(lastPackVolume < palletVolume && lastPackWeight < palletMaxWeight)
													{

														double remainingVolume = palletVolume - lastPackVolume;
														System.out.println("REMAINING VOLUME TO ADJUST["+remainingVolume+"]");
														
														if(remainingVolume >= caseVolume)
														{
															System.out.println(">>>>REMAINING VOLUME GRATER THEN OR EQUALS TO CASE VOLUME>>>>");
															if(remainingVolume >= currentCaseVolume)
															{
																System.out.println(">>REMAINING CASE VOLUME GRATER THEN CURRENT CASE VOLUME>>");
																HashMap caseTempMap = (HashMap)dataMap.clone();	
																caseTempMap.put("no_art", ""+totalCaseOnPallet);
																caseTempMap.put("alloc_qty", totalCaseOnPallet * packSize	);
																caseTempMap.put("LAST_PACK_VOLUME", (currentCaseVolume + lastPackVolume));
																caseTempMap.put("LAST_PACK_WEIGHT", totalCaseOnPallet * caseWeight);								
																caseTempPickList.add(caseTempMap);
																int updLen = allCasePickList.size()-1;
																allCasePickList.set(updLen,caseTempPickList);
															}
															else 
															{
																
																System.out.println("<<REMAINING CASE VOLUME LESS THEN CURRENT CASE VOLUME<<<");
																double quantityToBeStore = Math.floor(remainingVolume / caseVolume);
																System.out.println("quantityToBeStore["+quantityToBeStore+"]");
																System.out.println("Volume To be stored["+(remainingVolume + lastPackVolume)+"]");
																HashMap caseTempMap = (HashMap)dataMap.clone();															
																caseTempMap.put("no_art", ""+quantityToBeStore);													
																caseTempMap.put("alloc_qty", quantityToBeStore*packSize);
																caseTempMap.put("LAST_PACK_VOLUME", (quantityToBeStore * caseVolume) + lastPackVolume);	
																caseTempMap.put("LAST_PACK_WEIGHT", (Math.floor(quantityToBeStore / packSize)) * caseWeight);														
																lastPackVolume = (quantityToBeStore * caseVolume) + lastPackVolume;
																caseTempPickList.add(caseTempMap);
																															
																
																System.out.println("caseTempPickList Values"+caseTempPickList.toString());
																double requiredVolumeToStore = currentCaseVolume - (quantityToBeStore * caseVolume);
																
																caseTempPickList = new ArrayList();
																
																HashMap caseTempMap1 = (HashMap)dataMap.clone();
																System.out.println("Avilable requiredVolumeToStore["+requiredVolumeToStore+"]");
																//Changed By Pragyan 17-Feb-13 to round the value up to decimal calculation 
																//quantityToBeStore = Math.floor(requiredVolumeToStore / caseVolume);
																quantityToBeStore = Math.round(requiredVolumeToStore / caseVolume);
																System.out.println("avilable quantityToBeStore["+quantityToBeStore+"]");
																
																System.out.println("Last Volume To be stored["+requiredVolumeToStore+"]");								
																caseTempMap1.put("no_art", ""+quantityToBeStore);									
																caseTempMap1.put("alloc_qty", quantityToBeStore*packSize);						
																								
																if((requiredVolumeToStore + lastPackVolume) > palletVolume)
																{
																	caseTempMap1.put("LAST_PACK_VOLUME", requiredVolumeToStore);
																	System.out.println("&&&& if After storing 2nd  Last Pack Volume  Volume ["+requiredVolumeToStore+"]");
																}
																else
																{
																	caseTempMap1.put("LAST_PACK_VOLUME", requiredVolumeToStore + lastPackVolume);
																	System.out.println("&&&& else After storing 2nd  Last Pack Volume  Volume ["+requiredVolumeToStore + lastPackVolume+"]");
																}													
																caseTempMap1.put("LAST_PACK_WEIGHT", (Math.floor(quantityToBeStore / packSize)) * caseWeight);
																caseTempPickList.add(caseTempMap1);
																allCasePickList.add(caseTempPickList);
															
															}
														}
														else
														{
															
															System.out.println("<<<< REMAINING VOLUME LESS THEN  CASE VOLUME <<<<<");
															caseTempPickList = new ArrayList();
															HashMap caseTempMap = (HashMap)dataMap.clone();			
															caseTempMap.put("no_art", ""+totalCaseOnPallet);
															caseTempMap.put("alloc_qty", totalCaseOnPallet * packSize	);
															caseTempMap.put("LAST_PACK_VOLUME", (totalCaseOnPallet * caseVolume));	
															caseTempMap.put("LAST_PACK_WEIGHT", totalCaseOnPallet * caseWeight);
															caseTempPickList.add(caseTempMap);
															allCasePickList.add(caseTempPickList);
															
														}

													}
													else
													{
														System.out.println("---LAST PACK VOLUME FULL ------");
														caseTempPickList = new ArrayList();
														HashMap caseTempMap = (HashMap)dataMap.clone();			
														caseTempMap.put("no_art", ""+totalCaseOnPallet);
														caseTempMap.put("alloc_qty", totalCaseOnPallet * packSize	);													
														caseTempMap.put("LAST_PACK_VOLUME", (totalCaseOnPallet * caseVolume) + lastPackVolume);
														caseTempMap.put("LAST_PACK_WEIGHT", totalCaseOnPallet * caseWeight);
														caseTempPickList.add(caseTempMap);
														allCasePickList.add(caseTempPickList);

													}
											}
										
									}
									else
									{
										System.out.println("IN CASE MAP DOES NOT EXIST............");
										caseTempPickList = new ArrayList();
										HashMap caseTempMap = (HashMap)dataMap.clone();			
										caseTempMap.put("no_art", ""+totalCaseOnPallet);
										caseTempMap.put("alloc_qty", totalCaseOnPallet * packSize	);
										caseTempMap.put("LAST_PACK_VOLUME", (totalCaseOnPallet * caseVolume));
										caseTempMap.put("LAST_PACK_WEIGHT", totalCaseOnPallet * caseWeight);
										caseTempPickList.add(caseTempMap);
										allCasePickList.add(caseTempPickList);				
									}
						
									volumeRmaining = volumeRmaining - totalCaseOnPallet * caseVolume;
									System.out.println("case volumes  reamining["+volumeRmaining+"]");
									
									System.out.println("calculating Count 1"+(volumeRmaining/caseVolume)+"]");
									System.out.println("calculating Count with round 2"+Math.round((volumeRmaining/caseVolume))+"]");
									System.out.println("case Count with floor 3"+Math.floor((volumeRmaining/caseVolume))+"]");
									
									if(totalCaseOnPallet < (volumeRmaining/caseVolume))
									{
									}
									else
									{
										//Changed by sumit on 05/04/13 macking floor.
										//totalCaseOnPallet = volumeRmaining/caseVolume;
										totalCaseOnPallet = Math.round(volumeRmaining/caseVolume);
									}
									
									//Changed by Rohan on 24-11-11 [WMIESUN006] For bug Fixing.start
									//Changed by sumit on 05/04/13 modify condition.
									//if(volumeRmaining == 0.0)
									if(volumeRmaining <= 0.0)
									{
										System.out.println(" IN SIDE BREAK :::: ");
										break;
									}
									//Changed by Rohan on 24-11-11 [WMIESUN006] For bug Fixing.end
									
								}					
								System.out.println("AFTER CALCULATING CASE ON PALLET["+totalCaseOnPallet+"]");
								renCtr ++ ;
							}
							while(renCtr <= cashCountPerPallet);
						
					}
						
				}//if(quantity >= packSize)
				//Changed By Pragyan 17-feb-12 not to generate case/master pick from active location .Start
				if(invStat.equalsIgnoreCase(activePickInv) && quantity >= packSize && activeCount <= 0 && "Y".equalsIgnoreCase(aPickAllow))
				{
					System.out.println("--INSIDE ACTIVE*************************** PICK BLOCK--");
					activeCount = quantity;
				}
				//Changed By Pragyan 17-feb-12 not to generate case/master pick from active location .end
				//Storing data for activ pick order list 
				System.out.println("--INSIDE ACTIVE*************************** PICK BLOCK--");
				//Changed by Rohan on 14/08/12 to create master Pack depending upon wave_task
				//if((quantity < packSize || activeCount > 0) &&  stockToDock.equalsIgnoreCase("N") )
				if((quantity < packSize || activeCount > 0) &&  ("N".equalsIgnoreCase(stockToDock) || "N".equalsIgnoreCase(stockToDoc)) && "Y".equalsIgnoreCase(aPickAllow))
				{
					System.out.println("--INSIDE ACTIVE PICK BLOCK--");
					if(activeCount > 0)
					{
						quantity = activeCount;
					}
					//Changed by Rohan on 9/03/12 to get case packet,volume,wegiht.start
					/*String[] itmWeightVol = new String[3];
					String itemVolumeWeight = getPackItemVolumeWeight((quantity * itemWeight) , (quantity * perItemVolume), "A", conn);
				
					itmWeightVol = itemVolumeWeight.split(":");
					
					if(Double.parseDouble(itmWeightVol[0]) != 0.0)
					{
						palletMaxWeight = Double.parseDouble(itmWeightVol[0]);
					}
					if(Double.parseDouble(itmWeightVol[1]) != 0.0)
					{
						caseVolume = Double.parseDouble(itmWeightVol[1]);
					}*/
					System.out.println("packetMaxWeightActive:"+packetMaxWeightActive+"packetMaxVolumeActive:"+packetMaxVolumeActive);
					//Changed by Rohan on 9/03/12 to get case packet,volume,wegiht.end
				
					double quantityPerPallet = Math.floor(  (quantity * perItemVolume)/packetMaxVolumeActive);
					double totQtyPerPallet = Math.floor(packetMaxVolumeActive/perItemVolume);
					double renCtr = 0;
					double volumeRmaining = Math.floor(perItemVolume * quantity); 
				

					if(totQtyPerPallet > quantity)
					{
						totQtyPerPallet = quantity;
					}
					
					if(activeCount/quantityPerPallet != 0)
					{
						quantityPerPallet = quantityPerPallet + 1;
					}

					do
					{									
						
						double currentvolumeActive = totQtyPerPallet * perItemVolume;

						if(totQtyPerPallet < 0)
						{
							
							break;
						}
						else
						{									
										
							if(allActivesList.size() > 0)
							{
								
								int allActiveListLen = allActivesList.size();
								activeTempPickList = (ArrayList)allActivesList.get(allActiveListLen -1);
								int activeTempPickListLen = activeTempPickList.size();
								Map tempMap = (HashMap)activeTempPickList.get(activeTempPickListLen -1);
					
								if(tempMap.containsKey("LAST_PACK_VOLUME"))
								{
					
									double lastPackVolume = (Double)tempMap.get("LAST_PACK_VOLUME");
									double lastPackWeight = (Double)tempMap.get("LAST_PACK_WEIGHT");
									
									System.out.println("ON ACTIVE CURRENT VOLUME ACTIVE ["+currentvolumeActive+"]");
									System.out.println("ON ACTIVE lastPackVolume ["+lastPackVolume+"]");
									System.out.println("ON ACTIVE lastPackWeight ["+lastPackWeight+"]");
									
									
									if(lastPackVolume < packetMaxVolumeActive && lastPackWeight < packetMaxWeightActive)
									{

										double remainingVolume = packetMaxVolumeActive  - 	lastPackVolume;	
										System.out.println("ON ACTIVE remainingVolume ["+remainingVolume+"]");
										if(remainingVolume >= perItemVolume)
										{

											if(remainingVolume >= currentvolumeActive)
											{															
												HashMap activeTempMap = (HashMap)dataMap.clone();
												activeTempMap.put("no_art", "1");
												activeTempMap.put("alloc_qty", totQtyPerPallet);
												activeTempMap.put("LAST_PACK_VOLUME", lastPackVolume + currentvolumeActive);																
												activeTempMap.put("LAST_PACK_WEIGHT", totQtyPerPallet * itemWeight);																
												activeTempPickList.add(activeTempMap);
												int updLen = allActivesList.size()-1;
												allActivesList.set(updLen, activeTempPickList);
																						
											}
											else 
											{
												double requiredQuantityToStore = Math.floor(remainingVolume / perItemVolume);
												System.out.println("ON ACTIVE requiredQuantityToStore ["+requiredQuantityToStore+"]");
												HashMap activeTempMap = (HashMap)dataMap.clone();
												activeTempMap.put("no_art", "1");
												activeTempMap.put("alloc_qty", requiredQuantityToStore);
												activeTempMap.put("LAST_PACK_VOLUME", lastPackVolume + remainingVolume);
												activeTempMap.put("LAST_PACK_WEIGHT", requiredQuantityToStore * itemWeight);																
												activeTempPickList.add(activeTempMap);
																								
												lastPackVolume = lastPackVolume + remainingVolume;
												double reqVolumeToStore = currentvolumeActive - (requiredQuantityToStore * perItemVolume);	
												System.out.println("ON ACTIVE reqVolumeToStore ["+reqVolumeToStore+"]");
												double remain_quantity = 	Math.floor(reqVolumeToStore/perItemVolume);		
												System.out.println("ON ACTIVE remain_quantity ["+remain_quantity+"]");
												activeTempPickList = new ArrayList();
												HashMap activeTempMap1 = (HashMap)dataMap.clone();
												activeTempMap1.put("no_art", "1");
												activeTempMap1.put("alloc_qty", remain_quantity);
												//activeTempMap1.put("LAST_PACK_VOLUME", reqVolumeToStore);
												
												if((reqVolumeToStore + lastPackVolume) > packetMaxVolumeActive)
												{
													activeTempMap1.put("LAST_PACK_VOLUME", reqVolumeToStore);
													System.out.println("ON ACTIVE After storing 2nd  Last Pack Volume  Volume ["+reqVolumeToStore+"]");
												}
												else
												{
													activeTempMap1.put("LAST_PACK_VOLUME", reqVolumeToStore + lastPackVolume);
													System.out.println("ON ACTIVE After storing 2nd  Last Pack Volume  Volume ["+reqVolumeToStore + lastPackVolume+"]");
												}		
												activeTempMap1.put("LAST_PACK_WEIGHT", remain_quantity * itemWeight);																
												activeTempPickList.add(activeTempMap1);
												allActivesList.add(activeTempPickList);



											}
										}
										else
										{
											activeTempPickList = new ArrayList();
											HashMap activeTempMap1 = (HashMap)dataMap.clone();
											activeTempMap1.put("no_art", "1");
											activeTempMap1.put("alloc_qty", totQtyPerPallet);
											activeTempMap1.put("LAST_PACK_VOLUME", currentvolumeActive);
											activeTempMap1.put("LAST_PACK_WEIGHT", totQtyPerPallet * itemWeight);																
											activeTempPickList.add(activeTempMap1);
											allActivesList.add(activeTempPickList);
										}
									}
									else 
									{
											activeTempPickList = new ArrayList();
											HashMap activeTempMap1 = (HashMap)dataMap.clone();
											activeTempMap1.put("no_art", "1");
											activeTempMap1.put("alloc_qty", totQtyPerPallet);
											activeTempMap1.put("LAST_PACK_VOLUME", currentvolumeActive);
											activeTempMap1.put("LAST_PACK_WEIGHT", totQtyPerPallet * itemWeight);																
											activeTempPickList.add(activeTempMap1);
											allActivesList.add(activeTempPickList);
									}
								
								}
							}//if(allActivesList.size() > 0)
							else
							{
								activeTempPickList = new ArrayList();
								HashMap activeTempMap1 = (HashMap)dataMap.clone();
								activeTempMap1.put("no_art", "1");
								activeTempMap1.put("alloc_qty", totQtyPerPallet);
								activeTempMap1.put("LAST_PACK_VOLUME", currentvolumeActive);
								activeTempMap1.put("LAST_PACK_WEIGHT", totQtyPerPallet * itemWeight);
								activeTempPickList.add(activeTempMap1);
								allActivesList.add(activeTempPickList);
							}
														
							volumeRmaining = volumeRmaining - totQtyPerPallet * perItemVolume;
							System.out.println("ON ACTIVE volumeRmaining ["+volumeRmaining+"]totQtyPerPallet"+totQtyPerPallet);
							if(totQtyPerPallet < Math.floor((volumeRmaining/perItemVolume)))
							{
							}
							else
							{
								totQtyPerPallet =Math.floor((volumeRmaining/perItemVolume));
								System.out.println("After calculating>>>> ["+totQtyPerPallet+"]");
								totQtyPerPallet =Math.floor(volumeRmaining/perItemVolume);
								System.out.println("To be check after Floor>>>> ["+totQtyPerPallet+"]");
							}
							
							//Changed by Rohan on 24-11-11 [WMIESUN006] For bug Fixing.start
							if(volumeRmaining == 0.0)
							{
								break;
							}
							//Changed by Rohan on 24-11-11 [WMIESUN006] For bug Fixing.end
							
						}						
						renCtr ++ ;

					}
					while(renCtr <= quantityPerPallet);

								
				}//if(quantity < packSize || activeCount > 0 )
				//Chnaged by Rohan on 16/08/12 not alloacte active if not alloacte Stock.start
				else if((quantity < packSize || activeCount > 0) && "N".equalsIgnoreCase(aPickAllow))
				{
					System.out.println("GENERATING ERREOS&&&&&&&&&&&&&&&&&&&-------&&&&&&&&&&&&&&&&&&&&&&&");
					errString = getError(saleOrder,"INVORDQTY",conn);
					return errString;
			
				}
				//Changed by Rohan on 16/08/12 to generate error if customer to not accept actives.end
		
			}
			
				sqlHdrPick="INSERT INTO PICK_ORD_HDR(PICK_ORDER, ORDER_DATE, SITE_CODE,"
					+"SALE_ORDER,WAVE_ID,PICK_TYPE, CHG_USER, CHG_DATE, CHG_TERM) VALUES (?,?,?,?,?,?,?,?,?)";
	
				sqlDtlPick = "INSERT INTO PICK_ORD_DET(PICK_ORDER, LINE_NO, " +
							"SALE_ORDER, LINE_NO__SORD,	SITE_CODE, " +
							"ITEM_CODE,	LOC_CODE, LOT_NO, LOT_SL, NO_ART, QUANTITY,EXP_LEV,LOC_CODE__TO,REPL_ORDER,LINE_NO__REPL) " +
							"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			
				sqlReplOrdHdr = "INSERT INTO REPL_ORD_HDR(REPL_ORDER, ORDER_DATE, SITE_CODE, " +
								"SALE_ORDER, WAVE_ID,CHG_USER,CHG_TERM,CHG_DATE,ORDER_TYPE) VALUES (?,?,?,?,?,?,?,?,?)";
				
				sqlReplOrdDtl = "INSERT INTO REPL_ORD_DET(REPL_ORDER, LINE_NO, SALE_ORDER, LINE_NO__SORD, SITE_CODE, " +
				"ITEM_CODE, LOC_CODE, LOT_NO, LOT_SL, NO_ART, QUANTITY,PICK_ORDER,LINE_NO__PICK,EXP_LEV,LOC_CODE__TO) " +
				"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				
				String sql1 = "INSERT INTO REPL_ORD_DET(REPL_ORDER, LINE_NO, SALE_ORDER, LINE_NO__SORD, SITE_CODE, " +
				 "ITEM_CODE, LOC_CODE, LOT_NO, LOT_SL, NO_ART, QUANTITY,PICK_ORDER,LINE_NO__PICK,EXP_LEV,LOC_CODE__TO) " +
				 "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				//Changed By Pragyan 26/02/13 To add direct Pick location for Master/Parcel converting from LTL.start
				sSQLIssHdr =" INSERT INTO PICK_ISS_HDR(TRAN_ID,TRAN_DATE,PICK_ORDER,SITE_CODE,CONFIRMED,CONF_DATE,EMP_CODE__APRV," 
							+ " CHG_USER,CHG_DATE,CHG_TERM,PICK_TYPE,PALLET_NO,TRF_STATUS) " 
							+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
				
				sSQLIssDet =" INSERT INTO PICK_ISS_DET(TRAN_ID, LINE_NO , PICK_ORDER, LINE_NO__ORD, SITE_CODE, ITEM_CODE , LOC_CODE, " 
						 + " LOT_NO, LOT_SL, NO_ART, QUANTITY , LOC_CODE__TO, CASE_LABEL , LOC_CODE__SYS, CARTON_NO ) " 
						 +" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				
				sSQlUpdWave = " UPDATE WAVE_TASK_DET SET STATUS =?,WAVE_STATUS= ? WHERE REF_ID= ? ";
				
				sSQLUpdPkHdr = " UPDATE PICK_ORD_HDR SET STATUS ='C' WHERE PICK_ORDER = ?";
				
				if(directPickLoc != null && directPickLoc.length() > 0)
				{
					pstmtPickHdr = conn.prepareStatement(sSQLUpdPkHdr);
					pstmtIssHdr = conn.prepareStatement(sSQLIssHdr);
					pstmtIssDet = conn.prepareStatement(sSQLIssDet);
					pstmtUpdWave = conn.prepareStatement(sSQlUpdWave);
				}
				//ResultSet rsWaveStatus = null;
				//Changed By Pragyan 26/02/13 To add direct Pick location for Master/Parcel converting from LTL.end
				
				PreparedStatement pstmtRplStk = conn.prepareStatement(sql1);
				pstmt = conn.prepareStatement(sqlHdrPick);
				pstmtDet = conn.prepareStatement(sqlDtlPick);				
				pstmtRplHdr = conn.prepareStatement(sqlReplOrdHdr);
				pstmtRplDet = conn.prepareStatement(sqlReplOrdDtl);
	
				if(allStockToDockList.size() > 0)
				{
						
						int stkToDockLen = allStockToDockList.size();
						for(int rptr = 0;rptr < stkToDockLen; rptr ++)
						{
							
							Map tempMap = (HashMap)allStockToDockList.get(rptr);
							siteCode = (String)tempMap.get("site_code");
							itemCode = (String)tempMap.get("item_code");
							locCode = (String)tempMap.get("loc_code");
							lotNo = (String)tempMap.get("lot_no");
							lotSl = (String)tempMap.get("lot_sl");
							noArt =  (String)tempMap.get("no_art");
							quantity =  (Double)tempMap.get("alloc_qty");
							expLevel =  (String)tempMap.get("exp_lev");
							sordLineNo = (String)tempMap.get("sord_lineNo");
							itemLocType = (String)tempMap.get("loc_type");
							locZonePref = Integer.parseInt(String.valueOf(tempMap.get("loc_zone_pref")));
							invStat = (String)tempMap.get("inv_stat");
							invStat = invStat.trim();
							
							String pndLoc = "";
							String replRefDeepId = "";
							
							if(invStat.equalsIgnoreCase(invDeepReserve))
							{
								replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"RS-DSO","E",ptcn,conn);
								pndLoc = getAvilablePickLocation("N", conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
							}
							else
							{
								replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"S-DOC","S",ptcn,conn);
							}
							
							pstmtRplHdr.setString(1,replRefDeepId);
							pstmtRplHdr.setDate(2,orderDate);
							pstmtRplHdr.setString(3,siteCode);
							pstmtRplHdr.setString(4,saleOrder);
							pstmtRplHdr.setString(5,waveID);
							pstmtRplHdr.setString(6,chgUser);
							pstmtRplHdr.setString(7,chgTerm);
							pstmtRplHdr.setDate(8,orderDate);
					
							String replRefPNDId = "";
							if(invStat.equalsIgnoreCase(invDeepReserve))
							{
								pstmtRplHdr.setString(9,"H"); 
								//pstmtRplHdr.executeUpdate();
								pstmtRplHdr.addBatch();
								replRefPNDId = updateWaveTaskDet(waveID,1,saleOrder,"RP-PND","N",ptcn,conn);
								pstmtRplHdr.setString(1,replRefPNDId);
								pstmtRplHdr.setString(9,"L"); 
								//pstmtRplHdr.executeUpdate();
								pstmtRplHdr.addBatch();
								//pstmtRplHdr.clearParameters();
							}
							else
							{
								pstmtRplHdr.setString(9,"D"); 
								//pstmtRplHdr.executeUpdate();
								pstmtRplHdr.addBatch();
							}
							
							pstmtRplStk.setString(1,replRefDeepId);
							pstmtRplStk.setInt(2,rptr +1);
							pstmtRplStk.setString(3,saleOrder);
							pstmtRplStk.setString(4,sordLineNo);
							pstmtRplStk.setString(5,siteCode);
							pstmtRplStk.setString(6,itemCode);
							pstmtRplStk.setString(7,locCode);
							pstmtRplStk.setString(8,lotNo);
							pstmtRplStk.setString(9,lotSl);
							pstmtRplStk.setDouble(10,Double.parseDouble(noArt));
							pstmtRplStk.setDouble(11, quantity);
							/*pstmtRplStk.setString(12, replRefPNDId);
							pstmtRplStk.setInt(13, rptr +1);*/
							 pstmtRplStk.setString(12,"");
							 pstmtRplStk.setInt(13, 0);
							pstmtRplStk.setString(14, expLevel);
							
							if(invStat.equalsIgnoreCase(invDeepReserve))
							{
								if(pndLoc != null && pndLoc.length() > 0)
		                        {
									//pndLocation = (String)pndLocList.get(rptr);
									 pstmtRplStk.setString(15,pndLoc);
		                        }
		                        else
		                        {
		                        	 pstmtRplStk.setString(15,"");
		                        	errString = getError(saleOrder,"INVPNDLOC",conn);
		                			return errString;
		                        }
								 //pstmtRplStk.executeUpdate();
								pstmtRplStk.addBatch();
								 
								 pstmtRplStk.setString(1,replRefPNDId);
								 pstmtRplStk.setString(7,pndLoc);
								 pstmtRplStk.setString(12,replRefDeepId);
								 pstmtRplStk.setInt(13, rptr +1);
								 pstmtRplStk.setString(15,docLoc);
								 pstmtRplStk.addBatch();
								 updateCartonMaster(replRefPNDId, (rptr +1),Double.parseDouble("1"),ptcn,"S-DOC", xtraParams,"",itemCode, conn);
							}
							else
							{
								
								 pstmtRplStk.setString(15,docLoc);
								 pstmtRplStk.addBatch();  
								 updateCartonMaster(replRefDeepId, (rptr +1),Double.parseDouble("1"),ptcn,"S-DOC", xtraParams,"",itemCode,conn);
							}
							
							// pstmtRplStk.executeUpdate();
							
							 
					}
						
						pstmtRplHdr.executeBatch();
						pstmtRplStk.executeBatch();
						pstmtRplHdr.clearParameters();
						pstmtRplStk.clearParameters();

				}
				
				
				
		
				int allCasePickListLen = allCasePickList.size();
				System.out.println("allCasePickList-=-=-=-=-===>"+allCasePickList.toString());
				if(allCasePickListLen > 0)
				{
					double packSizeCase = 0.0;
					boolean isPick = false;
					for(int cCTR = 0;cCTR < allCasePickListLen; cCTR ++)
					{
						pickType = "C";
						isPick = true;
						ArrayList tempListToRepl = (ArrayList)allCasePickList.get(cCTR);
						int tempListToReplLen = tempListToRepl.size();
						String isCreateReplHeader ="N";
						String pickRefId = "";					
						//Chnged by Rohan on 06-02-13 for define variable
						String lineNo ="";
						ArrayList tempList = (ArrayList)allCasePickList.get(cCTR);
						int tempLen = tempList.size();
						int replCtr = 1;
						
						for(int aCtr = 0;aCtr < tempLen;aCtr++)
						{
							String replRefDeepId ="",replRefPNDId="";
							Map tempMap = (HashMap)tempList.get(aCtr);
							siteCode = (String)tempMap.get("site_code");
							itemCode = (String)tempMap.get("item_code");
							locCode = (String)tempMap.get("loc_code");
							lotNo = (String)tempMap.get("lot_no");
							lotSl = (String)tempMap.get("lot_sl");
							noArt =  (String)tempMap.get("no_art");
							quantity =  (Double)tempMap.get("alloc_qty");
							System.out.println("quantity^^^^^"+quantity);
							expLevel =  (String)tempMap.get("exp_lev");
							sordLineNo = (String)tempMap.get("sord_lineNo");
							itemLocType = (String)tempMap.get("loc_type");
							locZonePref = Integer.parseInt(String.valueOf(tempMap.get("loc_zone_pref")));
							invStat = (String)tempMap.get("inv_stat");
							invStat = invStat.trim();
							packSizeCase = (Double)tempMap.get("pack_size");
							System.out.println("Invstat Stored in the Data ["+invStat+"]Deep Storage["+invDeepReserve+"]Reserve["+invReserve+"]");
							String pndLoc = getAvilablePickLocation("N", conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
							String casePkDeepLoc = getAvilablePickLocation(pickType, conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
							isCreateReplHeader = checkForReplenishment(itemCode,siteCode,lotNo,lotSl,locCode,quantity,1,conn);
							
							if("Y".equalsIgnoreCase(isCreateReplHeader) && (invStat.equalsIgnoreCase(invDeepReserve) || invStat.equalsIgnoreCase(invReserve)))
							{
									pstmtRplHdr.setDate(2,orderDate);
									pstmtRplHdr.setString(3, siteCode);
									pstmtRplHdr.setString(4,saleOrder);
									pstmtRplHdr.setString(5,waveID);
									pstmtRplHdr.setString(6,chgUser);
									pstmtRplHdr.setString(7,chgTerm);
									pstmtRplHdr.setDate(8,orderDate);
								
								if(invStat.equalsIgnoreCase(invDeepReserve))
								{
									replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"R-DSO","E",ptcn,conn);
									pstmtRplHdr.setString(1,replRefDeepId);
									pstmtRplHdr.setString(9,"F"); 
									pstmtRplHdr.executeUpdate();				
									replRefPNDId = updateWaveTaskDet(waveID,1,saleOrder,"R-PND","N",ptcn,conn);
									pstmtRplHdr.setString(1,replRefPNDId);
									pstmtRplHdr.setString(9,"J");
									pstmtRplHdr.executeUpdate();				
									pstmtRplHdr.clearParameters();
								}
								else
								{
									replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"","",ptcn,conn);
									pstmtRplHdr.setString(1,replRefDeepId);
									pstmtRplHdr.setString(9,"C");
									pstmtRplHdr.executeUpdate();
									pstmtRplHdr.clearParameters();
								}
							}
							
							if(isPick)
							{
								pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"C-PICK","C",ptcn,conn);
								pstmt.setString(1,pickRefId);
								pstmt.setDate( 2, orderDate );
								pstmt.setString(3,siteCode);
								pstmt.setString(4,saleOrder);
								pstmt.setString(5,waveID);
								pstmt.setString(6,pickType);
								pstmt.setString(7,chgUser);
								pstmt.setDate(8,orderDate);
								pstmt.setString(9,chgTerm);
								pstmt.executeUpdate();
								isPick = false;
							}
												
							int pickCtr = 0;
							String isRepl="";
							String replQuantity="",prvReplID="",prvLocCodeTo="",prvPickOrd = "";
							int prvReplLineNo=0,prvPickLineNo=0;
							pickCtr= aCtr + 1;							
							String replQuantityID="";
							
							if((invStat.equalsIgnoreCase(invDeepReserve) || invStat.equalsIgnoreCase(invReserve)))
							{
							
								replQuantityID = checkForReplenishment(itemCode, siteCode, lotNo, lotSl, locCode, quantity, 2, conn);
								System.out.println("replQuantityID::"+replQuantityID);
								StringTokenizer stReplQtyID = new StringTokenizer(replQuantityID, ":");
								
								while(stReplQtyID.hasMoreTokens())
								{
									isRepl = stReplQtyID.nextToken();
									if("Y".equalsIgnoreCase(isRepl))
									{
										replQuantity=stReplQtyID.nextToken();
									}
									else if("N".equalsIgnoreCase(isRepl))
									{
										prvReplID=stReplQtyID.nextToken();
										prvLocCodeTo=stReplQtyID.nextToken();
										//Changed by Rohan on 06-02-13 for checking null repanishment
										//prvReplLineNo=Integer.parseInt(stReplQtyID.nextToken());
										//pickOrd !=null && pickOrd.length() > 0?pickOrd:"0"
										lineNo = stReplQtyID.nextToken();
										System.out.println("lineNo-->"+lineNo);
										if("null".equalsIgnoreCase(lineNo))
										{
											lineNo ="0";
										}
										//prvReplLineNo=Integer.parseInt(lineNo != null &&  lineNo.length() > 0?lineNo:"0");
										prvReplLineNo=Integer.parseInt(lineNo);
										prvPickOrd=stReplQtyID.nextToken();
										prvPickLineNo=Integer.parseInt(stReplQtyID.nextToken());
									}
								}
								if("Y".equalsIgnoreCase(isRepl))
								{
									
									pstmtRplDet.setString(1,replRefDeepId);
									pstmtRplDet.setInt(2,replCtr);
									pstmtRplDet.setString(3,saleOrder);
									pstmtRplDet.setString(4,sordLineNo);
									pstmtRplDet.setString(5,siteCode);
									pstmtRplDet.setString(6,itemCode);
									pstmtRplDet.setString(7,locCode);
									pstmtRplDet.setString(8,lotNo);
									pstmtRplDet.setString(9,lotSl);
									pstmtRplDet.setDouble(10,( Double.parseDouble(replQuantity)/packSizeCase));
									pstmtRplDet.setDouble(11, Double.parseDouble(replQuantity));//Changes Done By Ashish
									/*pstmtRplDet.setString(12,replRefPNDId);
									pstmtRplDet.setInt(13,replCtr);*/
									pstmtRplDet.setString(12,"");
									pstmtRplDet.setInt(13,0);
									pstmtRplDet.setString(14,expLevel);
									if(invStat.equalsIgnoreCase(invDeepReserve))
									{
										if(pndLoc != null && pndLoc.length() > 0)
										{
											pstmtRplDet.setString(15,pndLoc);
										}
										else
										{
											errString = getError(saleOrder,"INVPNDLOC",conn);
				                			return errString;
										}
										pstmtRplDet.executeUpdate();
										pstmtRplDet.setString(1,replRefPNDId);
										pstmtRplDet.setString(12,replRefDeepId);
										pstmtRplDet.setInt(13,replCtr);
										pstmtRplDet.setString(7,pndLoc);
										if(casePkDeepLoc != null && casePkDeepLoc.length() > 0)
			                            {
			                            	pstmtRplDet.setString(15,casePkDeepLoc);
			                            }
			                            else
			                            {
			                            	errString = getError(saleOrder,"INVCPKLOC",conn);
				                			return errString;
			                            }
										pstmtRplDet.executeUpdate();
										pstmtRplDet.clearParameters();
									}
									else
									{
										if(casePkDeepLoc != null && casePkDeepLoc.length() > 0)
			                            {
			                            	pstmtRplDet.setString(15,casePkDeepLoc);
			                            }
			                            else
			                            {
			                            	errString = getError(saleOrder,"INVCPKLOC",conn);
				                			return errString;
			                            }
										pstmtRplDet.executeUpdate();
										pstmtRplDet.clearParameters();
									}
								}
							}

							pstmtDet.setString(1,pickRefId);
							pstmtDet.setInt(2,pickCtr);
							pstmtDet.setString(3,saleOrder);
							pstmtDet.setString(4,sordLineNo);
							pstmtDet.setString(5,siteCode);
							pstmtDet.setString(6,itemCode);
							if("Y".equalsIgnoreCase(isRepl))
							{	
								pstmtDet.setString(7,casePkDeepLoc);
							}
							else if(prvLocCodeTo != null && prvLocCodeTo.length() > 0)
							{
								pstmtDet.setString(7,prvLocCodeTo);
							}
							else
							{
								pstmtDet.setString(7,locCode);
							}
                          	pstmtDet.setString(8,lotNo);
							pstmtDet.setString(9,lotSl);
							pstmtDet.setDouble(10,Double.parseDouble(noArt));
							pstmtDet.setDouble(11,quantity);
							pstmtDet.setString(12,expLevel);
							pstmtDet.setString(13,docLoc);
							
							if("Y".equalsIgnoreCase(isRepl))
							{
								if(invStat.equalsIgnoreCase(invDeepReserve))
								{
									pstmtDet.setString(14, replRefPNDId);
									pstmtDet.setInt(15, replCtr);
								}
								else
								{
									pstmtDet.setString(14, replRefDeepId);
									pstmtDet.setInt(15, replCtr);
								}
							}
							else
							{
								if(invStat.equalsIgnoreCase(invDeepReserve))
								{
									if("0".equalsIgnoreCase(prvPickOrd))
									{
										pstmtDet.setString(14, "");
										
									}
									else
									{
										pstmtDet.setString(14, prvPickOrd);
									}
									pstmtDet.setInt(15, prvPickLineNo);
								}
								else
								{
									pstmtDet.setString(14, prvReplID);
									pstmtDet.setInt(15, prvReplLineNo);
								}
							}
							
							pstmtDet.executeUpdate();
							pstmtDet.clearParameters();
						
							if((invStat.equalsIgnoreCase(invDeepReserve) || invStat.equalsIgnoreCase(invReserve)))
							{
								if("Y".equalsIgnoreCase(isRepl))
								{	
									updateReplenishmentRecord(itemCode, siteCode, lotNo, lotSl, locCode, quantity, replRefDeepId,casePkDeepLoc,replCtr, 1,casePackSize,false, conn);
								}
								else
								{
									updateReplenishmentRecord(itemCode, siteCode, lotNo, lotSl, locCode, quantity, prvReplID,"",9999, 2,casePackSize,false, conn);
								}
							}
							updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"C-PICK", xtraParams,"",itemCode, conn);
						}		
			
					}
			
				}
				
								
				int lengthOfMaster = allMasterPackList.size();
				if(lengthOfMaster > 0)
				{
					double ctrMaster = 0.0;
					double totalWeight =0.0;
					int totalNoArt=0;
					String packRefId="",pickRefId="";
					String issTranID = "",palletNo = "";
					int cntSingleMasterPick =0;
					//double caseVolume=0.0;
					//double caseWeight=0.0;
					caseVolume = 0.0;
					caseWeight = 0.0;
					double caseVolumeTotal=0.0;
					double caseWeightTotal=0.0;
					boolean isPick = false;
					double packSizeCase = 0.0;
					pickType = "M";
					for(int cCTR = 0;cCTR < lengthOfMaster; cCTR ++)
					{
						isPick = true;
						ArrayList tempListToRepl = (ArrayList)allMasterPackList.get(cCTR);
						int tempListToReplLen = tempListToRepl.size();
						String isCreateReplHeader ="N";
						
						ArrayList tempList = (ArrayList)allMasterPackList.get(cCTR);
						int tempLen = tempList.size();				
						int replCtr = 1;

						for(int aCtr = 0;aCtr < tempLen;aCtr++)
						{
							String replRefDeepId ="",replRefPNDId="";
							Map tempMap = (HashMap)tempList.get(aCtr);
							siteCode = (String)tempMap.get("site_code");
							itemCode = (String)tempMap.get("item_code");
							locCode = (String)tempMap.get("loc_code");
							lotNo = (String)tempMap.get("lot_no");
							lotSl = (String)tempMap.get("lot_sl");
							noArt =  (String)tempMap.get("no_art");
							quantity =  (Double)tempMap.get("alloc_qty");
							expLevel =  (String)tempMap.get("exp_lev");
							sordLineNo = (String)tempMap.get("sord_lineNo");
							itemGrossWeight =(Double)tempMap.get("item_weight");
							itemLocType = (String)tempMap.get("loc_type");
							//Changed By Pragyan 25/02/13 To set master/parcel pick values.start
							mPackAllow = (String)tempMap.get("master_pack");
							pPickAllow =(String)tempMap.get("parcel_pick");
							//Changed By Pragyan 27/02/13 To Pick type set as "M" for both Parcel & Master
							//pickType = ("Y".equalsIgnoreCase(pPickAllow))?"P":"M";
							//Changed By Pragyan 25/02/13 To set master/parcel pick values.end
							//pPickAllow = (String)tempMap.get("parcel_pick");
							
							locZonePref = Integer.parseInt(String.valueOf(tempMap.get("loc_zone_pref")));
							invStat = (String)tempMap.get("inv_stat");
							invStat = invStat.trim();
							packSizeCase = (Double)tempMap.get("pack_size");
							mapItemVolume = getItemVoumeMap(itemCode, lotNo, conn);				
							caseVolume = Math.floor((Double)mapItemVolume.get("LOT_SIZE"));
							caseWeight =Math.floor( (Double)mapItemVolume.get("PACK_WEIGHT"));
							caseVolumeTotal = Double.parseDouble(noArt)*caseVolume;
							caseWeightTotal = Double.parseDouble(noArt)*caseWeight;
							System.out.println("CURRENTLY LOOKING FOR ITEM_CODE ["+itemCode+"]LOCATION CODE["+locCode+"]QUANTITY["+quantity+"]NO OF ART["+noArt+"]Counter["+aCtr+"]");
							
							String pndLoc = getAvilablePickLocation("N", conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
							String casMpkDeepLoc = getAvilablePickLocation(pickType, conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);

							isCreateReplHeader = checkForReplenishment(itemCode,siteCode,lotNo,lotSl,locCode,quantity,1,conn);
							
							if("Y".equalsIgnoreCase(isCreateReplHeader) && (invStat.equalsIgnoreCase(invDeepReserve) || invStat.equalsIgnoreCase(invReserve)))
							{	
								
									pstmtRplHdr.setDate(2,orderDate);
									pstmtRplHdr.setString(3, siteCode);
									pstmtRplHdr.setString(4,saleOrder);
									pstmtRplHdr.setString(5,waveID);
									pstmtRplHdr.setString(6,chgUser);
									pstmtRplHdr.setString(7,chgTerm);
									pstmtRplHdr.setDate(8,orderDate);
								
								if(invStat.equalsIgnoreCase(invDeepReserve))
								{
									replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"R-DSO","E",ptcn,conn);
									pstmtRplHdr.setString(1,replRefDeepId);
									pstmtRplHdr.setString(9,"G"); 
									pstmtRplHdr.executeUpdate();				
									replRefPNDId = updateWaveTaskDet(waveID,1,saleOrder,"R-PND","N",ptcn,conn);
									pstmtRplHdr.setString(1,replRefPNDId);
									pstmtRplHdr.setString(9,"K");
									pstmtRplHdr.executeUpdate();				
									pstmtRplHdr.clearParameters();
								}
								else
								{
									replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"","",ptcn,conn);
									pstmtRplHdr.setString(1,replRefDeepId);
									pstmtRplHdr.setString(9,"M");
									pstmtRplHdr.executeUpdate();
									pstmtRplHdr.clearParameters();
								}
								
							}	
														
							if(isPick)
							{
								if(!("Y".equalsIgnoreCase(isSinglePickMasterPack)))
								{
									packRefId = updateWaveTaskDet(waveID,3,saleOrder,"","",ptcn,conn);
									updatePacking(waveID,saleOrder,packRefId,pickRefId,ptcn,xtraParams, conn);
								}
								
								if(("Y".equalsIgnoreCase(isSinglePickMasterPack)) && cCTR == 0)
								{
									if(("Y".equalsIgnoreCase(pPickAllow)))
									{
										pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"P-PICK","P",ptcn,conn);
									}
									else
									{
										pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"M-PICK","M",ptcn,conn);
									}
									pstmt.setString(1,pickRefId);
									pstmt.setDate( 2, orderDate );
									pstmt.setString(3,siteCode);
									pstmt.setString(4,saleOrder);
									pstmt.setString(5,waveID);
									pstmt.setString(6,pickType);
									pstmt.setString(7,chgUser);
									pstmt.setDate(8,orderDate);
									pstmt.setString(9,chgTerm);
									pstmt.executeUpdate();
									//Changed By Pragyan 26/02/13 For Master/Parcel convert.start
									if(directPickLoc != null && directPickLoc.length() > 0)
									{
										issTranID = getTranId("w_case_pick", conn);
										//palletNo = getPalletNo(siteCode, lotNo, lotSl, itemCode,oldPtcn, conn);
										palletNo = sugPalletNo;
										pstmtIssHdr.setString(1,issTranID);
										pstmtIssHdr.setDate(2,orderDate);
										pstmtIssHdr.setString(3,pickRefId);
										pstmtIssHdr.setString(4,siteCode);
										pstmtIssHdr.setString(5,"Y");
										//pstmtIssHdr.setString(5,"N");
										pstmtIssHdr.setDate(6,orderDate);
										pstmtIssHdr.setString(7,chgUser);
										pstmtIssHdr.setString(8,chgUser);
										pstmtIssHdr.setDate(9,orderDate);
										pstmtIssHdr.setString(10,chgTerm);
										pstmtIssHdr.setString(11,pickType);
										pstmtIssHdr.setString(12,palletNo);
										//pstmtIssHdr.setString(13,"Y");
										pstmtIssHdr.setString(13,"N");
										pstmtIssHdr.executeUpdate();
										pstmtIssHdr.clearParameters();
										
										pstmtUpdWave.setString(1, "Y");
										pstmtUpdWave.setString(2, "V");
										pstmtUpdWave.setString(3, pickRefId);
										pstmtUpdWave.executeUpdate();
										pstmtUpdWave.clearParameters();
										pstmtPickHdr.setString(1, pickRefId);
										pstmtPickHdr.executeUpdate();
										//updatePalletNo(ptcn, palletNo, conn);
									
									}
										
									//Changed By Pragyan 26/02/13 For Master/Parcel convert.end
								}
								else if (!("Y".equalsIgnoreCase(isSinglePickMasterPack)))
								{
									if(("Y".equalsIgnoreCase(pPickAllow)))
									{
										pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"P-PICK","P",ptcn,conn);
									}
									else
									{
										pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"M-PICK","M",ptcn,conn);
									}
									pstmt.setString(1,pickRefId);
									pstmt.setDate( 2, orderDate );
									pstmt.setString(3,siteCode);
									pstmt.setString(4,saleOrder);
									pstmt.setString(5,waveID);
									pstmt.setString(6,pickType);
									pstmt.setString(7,chgUser);
									pstmt.setDate(8,orderDate);
									pstmt.setString(9,chgTerm);
									pstmt.executeUpdate();
								}
								isPick = false;
							}

							if("Y".equalsIgnoreCase(isSinglePickMasterPack))
							{
								totalWeight =totalWeight + caseWeightTotal;
								totalNoArt = totalNoArt + (int)(Double.parseDouble(noArt));
								System.out.println("totalNoArt till counter ["+aCtr+"] "+totalNoArt);
								System.out.println("totalWeight till counter ["+aCtr+"] "+totalWeight);
							}
							int pickCtr = 0;
							String isRepl="";
							String replQuantity="",prvReplID="",prvLocCodeTo="",prvPickOrd = "";
							int prvReplLineNo=0,prvPickLineNo=0;
							pickCtr= aCtr + 1;
							String replQuantityID="";
							
							if((invStat.equalsIgnoreCase(invDeepReserve) || invStat.equalsIgnoreCase(invReserve)))
							{
								replQuantityID = checkForReplenishment(itemCode, siteCode, lotNo, lotSl, locCode, quantity, 2, conn);
								StringTokenizer stReplQtyID = new StringTokenizer(replQuantityID, ":");
								
								while(stReplQtyID.hasMoreTokens())
								{
									isRepl = stReplQtyID.nextToken();
									if("Y".equalsIgnoreCase(isRepl))
									{
										replQuantity=stReplQtyID.nextToken();
									}
									else if("N".equalsIgnoreCase(isRepl))
									{
										prvReplID=stReplQtyID.nextToken();
										prvLocCodeTo=stReplQtyID.nextToken();
										prvReplLineNo=Integer.parseInt(stReplQtyID.nextToken());
										prvPickOrd=stReplQtyID.nextToken();
										prvPickLineNo=Integer.parseInt(stReplQtyID.nextToken());
									}
								}
								
								if("Y".equalsIgnoreCase(isRepl))
								{
									pstmtRplDet.setString(1,replRefDeepId);
									pstmtRplDet.setInt(2,replCtr);
									pstmtRplDet.setString(3,saleOrder);
									pstmtRplDet.setString(4,sordLineNo);
									pstmtRplDet.setString(5,siteCode);
									pstmtRplDet.setString(6,itemCode);
									pstmtRplDet.setString(7,locCode);
									pstmtRplDet.setString(8,lotNo);
									pstmtRplDet.setString(9,lotSl);
									pstmtRplDet.setDouble(10,( Double.parseDouble(replQuantity)/packSizeCase));
									pstmtRplDet.setDouble(11, Double.parseDouble(replQuantity));
									/*pstmtRplDet.setString(12,replRefPNDId);
									pstmtRplDet.setInt(13,replCtr);*/
									pstmtRplDet.setString(12,"");
									pstmtRplDet.setInt(13,0);
									pstmtRplDet.setString(14,expLevel);
									if(invStat.equalsIgnoreCase(invDeepReserve))
									{
										if(pndLoc != null && pndLoc.length() > 0)
										{
											pstmtRplDet.setString(15,pndLoc);
										}
										else
										{
											errString = getError(saleOrder,"INVPNDLOC",conn);
				                			return errString;
										}
										pstmtRplDet.executeUpdate();
										pstmtRplDet.setString(1,replRefPNDId);
										pstmtRplDet.setString(12,replRefDeepId);
										pstmtRplDet.setInt(13,replCtr);
										pstmtRplDet.setString(7,pndLoc);
										if(casMpkDeepLoc != null && casMpkDeepLoc.length() > 0)
			                            {
			                            	pstmtRplDet.setString(15,casMpkDeepLoc);
			                            }
			                            else
			                            {
			                            	errString = getError(saleOrder,"INVCPKLOC",conn);
				                			return errString;
			                            }
										pstmtRplDet.executeUpdate();
										pstmtRplDet.clearParameters();
									}
									else
									{
										if(casMpkDeepLoc != null && casMpkDeepLoc.length() > 0)
			                            {
			                            	pstmtRplDet.setString(15,casMpkDeepLoc);
			                            }
			                            else
			                            {
			                            	errString = getError(saleOrder,"INVCPKLOC",conn);
				                			return errString;
			                            }
										pstmtRplDet.executeUpdate();
										pstmtRplDet.clearParameters();
									}
								}
							}
							
							int storeMasterCount = 0;
							pstmtDet.setString(1,pickRefId);
							if("Y".equalsIgnoreCase(isSinglePickMasterPack))
							{
								storeMasterCount = cntSingleMasterPick + 1;
								pstmtDet.setInt(2,storeMasterCount);
								cntSingleMasterPick++;
							}
							else
							{	
								pstmtDet.setInt(2,pickCtr);
							}
							pstmtDet.setString(3,saleOrder);
							pstmtDet.setString(4,sordLineNo);
							pstmtDet.setString(5,siteCode);
							pstmtDet.setString(6,itemCode);

							if("Y".equalsIgnoreCase(isRepl))
							{	
								pstmtDet.setString(7,casMpkDeepLoc);
							}
							else if(prvLocCodeTo != null && prvLocCodeTo.length() > 0)
							{
								pstmtDet.setString(7,prvLocCodeTo);
							}
							else
							{
								pstmtDet.setString(7,locCode);
							}
                            pstmtDet.setString(8,lotNo);
							pstmtDet.setString(9,lotSl);
							pstmtDet.setDouble(10,Double.parseDouble(noArt));
							pstmtDet.setDouble(11,quantity);
							pstmtDet.setString(12,expLevel);
							pstmtDet.setString(13,docLoc);
							if("Y".equalsIgnoreCase(isRepl))
							{
								
								if(invStat.equalsIgnoreCase(invDeepReserve))
								{
									pstmtDet.setString(14, replRefPNDId);
									pstmtDet.setInt(15, replCtr);
								}
								else
								{
									pstmtDet.setString(14, replRefDeepId);
									pstmtDet.setInt(15, replCtr);
								}
								
							}
							else
							{
								if("0".equalsIgnoreCase(prvPickOrd))
								{
									pstmtDet.setString(14, "");
									
								}
								else
								{
									pstmtDet.setString(14, prvPickOrd);
								}
								pstmtDet.setInt(15, prvPickLineNo);
							}
							pstmtDet.executeUpdate();
							pstmtDet.clearParameters();
							//Changed By Pragyan 26/02/13 For Master/Parcel convert.start
							if(directPickLoc != null && directPickLoc.length() > 0)
							{
								pstmtIssDet.setString(1, issTranID);
								pstmtIssDet.setInt(2, storeMasterCount);
								pstmtIssDet.setString(3, pickRefId);
								pstmtIssDet.setInt(4, storeMasterCount);
								pstmtIssDet.setString(5, siteCode);
								pstmtIssDet.setString(6, itemCode);
								pstmtIssDet.setString(7, directPickLoc);
								pstmtIssDet.setString(8, lotNo);
								pstmtIssDet.setString(9, lotSl);
								pstmtIssDet.setDouble(10,Double.parseDouble(noArt));
								pstmtIssDet.setDouble(11,quantity);
								pstmtIssDet.setString(12, docLoc);
								pstmtIssDet.setString(13, "");
								pstmtIssDet.setString(14, docLoc);
								pstmtIssDet.setString(15, "");
								pstmtIssDet.executeUpdate();
								pstmtIssDet.clearParameters();
								
								/*pstmtUpdWave.setString(1, pickRefId);
								pstmtUpdWave.executeUpdate();
								pstmtPickHdr.setString(1, pickRefId);
								pstmtPickHdr.executeUpdate();*/
								
							}
							//Changed By Pragyan 26/02/13 For Master/Parcel convert.end
							
							if((invStat.equalsIgnoreCase(invDeepReserve) || invStat.equalsIgnoreCase(invReserve)))
							{
								if("Y".equalsIgnoreCase(isRepl))
								{	
									updateReplenishmentRecord(itemCode, siteCode, lotNo, lotSl, locCode, quantity, replRefDeepId,casMpkDeepLoc,replCtr, 1,casePackSize,false, conn);
								}
								else
								{
									updateReplenishmentRecord(itemCode, siteCode, lotNo, lotSl, locCode, quantity, prvReplID,"",9999, 2,casePackSize,false, conn);
								}
							}
							
							if((!"Y".equalsIgnoreCase(pPickAllow)))
							{
								HashMap tempPickMap = new HashMap();
								tempPickMap.put("pick_order", pickRefId);
								tempPickMap.put("line_no_pick", pickCtr);
								tempPickMap.put("no_art", Double.parseDouble(noArt));
								tempPickMap.put("case_weight", caseWeight);
								tempPickMap.put("case_volume", caseVolume);
								
								if(mapItemPick.containsKey(itemCode))
								{
									allItemPickkList = (ArrayList)mapItemPick.get(itemCode);
									allItemPickkList.add(tempPickMap);
									mapItemPick.put(itemCode, allItemPickkList);
								}
								else
								{								
									allItemPickkList = new ArrayList();
									allItemPickkList.add(tempPickMap);
									mapItemPick.put(itemCode, allItemPickkList);
								}
							}
							else
							{
								updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"P-PICK", xtraParams,"",itemCode, conn);
							}
							
							
							
							/*updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"M-PICK", xtraParams, conn);//Not Required;
							
							if("Y".equalsIgnoreCase(isSinglePickMasterPack))
							{
								double cashCount = Double.parseDouble(noArt);
								double mPackCounter = Math.floor(cashCount / masterPackCount);	
								double masterPackWeightCount = Math.floor(masterPackWeight/caseWeight);
								double totalCaseOnPallet = masterPackCount;
								int counter = 0;
								if(cashCount/mPackCounter != 0)
								{
									mPackCounter = mPackCounter + 1;
								}
								if(totalCaseOnPallet > cashCount)
								{
									totalCaseOnPallet = cashCount;
								}
								do
								{
									double currentCaseCount = 	totalCaseOnPallet;				
									double casesWeightCount = Math.floor(currentCaseCount/masterPackWeightCount);		
									double wCounter = 0;
									if(masterPackWeightCount > currentCaseCount)
									{
										masterPackWeightCount = currentCaseCount;
									}
									
									do
									{
										System.out.println("$$$$$$ INSERTING DATA $$$$$$$$$$$["+masterPackWeightCount+"]$$$$$$$$$$$");
										packRefId = updateWaveTaskDet(waveID,3,saleOrder,"","",ptcn,conn);
										updatePacking(waveID,saleOrder,packRefId,pickRefId,ptcn,xtraParams, conn);
										System.out.println("$$$$$$ INSERTING DATA Volume without floor$$$$$$$$$$$["+masterPackWeightCount*caseVolume+"]$$$$$$$$$$$");
										System.out.println("$$$$$$ INSERTING DATA Volume without floor $$$$$$$$$$$["+masterPackWeightCount*caseWeight+"]$$$$$$$$$$$");
										caseVolumeTotal = Math.floor(masterPackWeightCount*caseVolume);
										caseWeightTotal = Math.floor(masterPackWeightCount*caseWeight);
										updateCartonMaster(packRefId, counter + 1,Double.parseDouble("1"),ptcn,"M-PACK", xtraParams, conn,caseWeightTotal,caseVolumeTotal,pickType);
										updateMasterCarton(pickRefId, packRefId, (int)masterPackWeightCount, conn);
										currentCaseCount = currentCaseCount - masterPackWeightCount;
										if((currentCaseCount /masterPackWeightCount) < 1)
										{						
											masterPackWeightCount = currentCaseCount;
										}
										if(currentCaseCount <= 0)
										{
											System.out.println("BREAK1===============["+currentCaseCount+"]");
											break;
										}
										if(masterPackWeightCount <= 0)
										{
											break;
										}			
										wCounter++;
									}		
									while(wCounter <= casesWeightCount);
									masterPackWeightCount = Math.floor(masterPackWeight/caseWeight);
									cashCount = cashCount - totalCaseOnPallet;
									if(cashCount / masterPackCount >=1)
									{
										totalCaseOnPallet = masterPackCount;
									}
									else
									{
										totalCaseOnPallet = cashCount;
									}
									if(totalCaseOnPallet <=0)
									{
										break;
									}
									counter++;
								}while(counter < mPackCounter);
							}*/
						}	
						if(!("Y".equalsIgnoreCase(isSinglePickMasterPack)))
						{	
							updateCartonMaster(pickRefId, cCTR + 1,Double.parseDouble("1"),ptcn,"M-PACK", xtraParams, conn,caseWeightTotal,caseVolumeTotal,pickType,"");
							System.out.println("updateCartonMaster M-PACK 6");
						}			
						
						ctrMaster++;
					}
					
					if((!"Y".equalsIgnoreCase(pPickAllow)))
					{
						int allMasterListlen = allMasterList.size();
						String masterCartonNo = "";
						for(int j = 0 ;j < allMasterListlen ; j++)
						{
							caseWeightTotal = 0.0;
							caseVolumeTotal = 0.0;
							ArrayList tempList = (ArrayList)allMasterList.get(j);
							System.out.println("Loop============"+j);
							packRefId = updateWaveTaskDet(waveID,3,saleOrder,"","",ptcn,conn);
							updatePacking(waveID,saleOrder,packRefId,pickRefId,ptcn,xtraParams, conn);
							
							
							if(directPickLoc != null && directPickLoc.length() > 0)
							{
								pstmtUpdWave.setString(1, "N");
								pstmtUpdWave.setString(2, "C");
								pstmtUpdWave.setString(3, packRefId);
								pstmtUpdWave.executeUpdate();
								pstmtUpdWave.clearParameters();
							}
							
							for(int ctrM =0 ; ctrM < tempList.size() ; ctrM++)
							{	//caseTempMap.put("CASE_VOLUME_TOT", (caseToBeStore * caseWeight));
								//caseTempMap.put("CASE_WEIGHT_TOT", (caseToBeStore * caseVolume));
								HashMap tempMap = (HashMap)tempList.get(ctrM);
								caseWeightTotal = caseWeightTotal + (Double)tempMap.get("CASE_WEIGHT_TOT");
								caseVolumeTotal = caseVolumeTotal + (Double)tempMap.get("CASE_VOLUME_TOT");
							}
							System.out.println("CURRENT CASE WEIGHT TOTAL["+caseWeightTotal+"]");
							System.out.println("CURRENT CASE VOLUME TOTAL["+caseVolumeTotal+"]");
							
							masterCartonNo = updateCartonMaster(packRefId, j + 1,Double.parseDouble("1"),ptcn,"M-PACK", xtraParams, conn,caseWeightTotal,caseVolumeTotal,pickType,"");
							
							for(int k =0 ; k < tempList.size() ; k++)
							{
								
								HashMap tempMap = (HashMap)tempList.get(k);
								itemCode = (String)tempMap.get("item_code");
								noArt = (String)tempMap.get("no_art");
								System.out.println("Item Name["+itemCode+"]");
								System.out.println("No Of Art["+noArt+"]");
								System.out.println("Alloc Qty["+tempMap.get("alloc_qty")+"]");
								ArrayList valList = (ArrayList)mapItemPick.get(itemCode);
								int valListLen = valList.size();
								for(int vCtr = 0; vCtr < valListLen;vCtr++)
								{
									HashMap vMap = (HashMap)valList.get(vCtr);
									double currentnoArt = (Double)vMap.get("no_art");
									
									if(currentnoArt <= 0.0)
									{
										continue;
									}
									
									pickRefId = (String)vMap.get("pick_order");
									int pickCtr = (Integer)vMap.get("line_no_pick");
									
									System.out.println("Pick Order["+pickRefId+"]");
									System.out.println("Line No Pick["+vMap.get("line_no_pick")+"]");
									System.out.println("Total No art["+currentnoArt+"]");
									System.out.println("case Weight["+vMap.get("case_weight")+"]");
									System.out.println("case Volume["+vMap.get("case_volume")+"]");
									updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"M-PICK", xtraParams,masterCartonNo,itemCode, conn);
									vMap.put("no_art", currentnoArt - Double.parseDouble(noArt));
								}
								
							}
							
						}

						if(directPickLoc != null && directPickLoc.length() > 0)
						{
							updatePalletNo(ptcn, palletNo, conn);
						}
						
						
					}
				}
				
				System.out.println("allActivesListLen::::"+allActivesList.toString());
				int allActivesListLen = allActivesList.size();
				if(allActivesListLen > 0)
				{
					int pickCtr =  1;
					double packSizeCase = 0;
					int cnt = 0;
					String pickRefId = "";
					//String replRefId ="";
					String replRefDeepId = "";
					String replRefPndId ="";
					//Changed by Rohan on 24-11-12 to get variable from disparam for active pick case count.start			
					cartonCount = 0;

					pstmtRplHdr.setString(1,replRefDeepId);
					pstmtRplHdr.setDate(2,orderDate);
					pstmtRplHdr.setString(3, siteCode);
					pstmtRplHdr.setString(4,saleOrder);
					pstmtRplHdr.setString(5,waveID);
					pstmtRplHdr.setString(6,chgUser);
					pstmtRplHdr.setString(7,chgTerm);
					pstmtRplHdr.setDate(8,orderDate);
					pstmtRplHdr.setString(9,"Q");
					
					for(int cCTR = 0;cCTR < allActivesListLen; cCTR ++)
					{
						pickType = "A";
						pstmt.setDate( 2, orderDate );
						pstmt.setString(3,siteCode);
						pstmt.setString(4,saleOrder);
						pstmt.setString(5,waveID);
						pstmt.setString(6,pickType);
						pstmt.setString(7,chgUser);
						pstmt.setDate(8,orderDate);
						pstmt.setString(9,chgTerm);
						//pstmt.executeUpdate();
						double itemVolumeTotal = 0.0;
						double itemWeightTotal =  0.0;	
						ArrayList tempList = (ArrayList)allActivesList.get(cCTR);
						
						int tempLen = tempList.size();
						
						for(int aCtr = 0;aCtr < tempLen;aCtr++)
						{
								Map tempMap = (HashMap)tempList.get(aCtr);
								siteCode = (String)tempMap.get("site_code");
								itemCode = (String)tempMap.get("item_code");
								replRefDeepId = "";
								System.out.println("Item CODEEEE====>"+itemCode);
								locCode = (String)tempMap.get("loc_code");
								lotNo = (String)tempMap.get("lot_no");
								lotSl = (String)tempMap.get("lot_sl");
								noArt =  (String)tempMap.get("no_art");
								System.out.println("Checking purpose"+tempMap.get("no_art"));
								quantity =  (Double)tempMap.get("alloc_qty");
								System.out.println("Checking purpose"+tempMap.get("alloc_qty"));
							    
                                //Changed by Rohan 14-12-11 [WM1ESUN006] To add exp_lev in repl_ord_det
								expLevel =  (String)tempMap.get("exp_lev");
								casePackSize =  (Double)tempMap.get("pack_size");	
								sordLineNo = (String)tempMap.get("sord_lineNo");
								itemLocType = (String)tempMap.get("loc_type");
								locZonePref = Integer.parseInt(String.valueOf(tempMap.get("loc_zone_pref")));
								locInvStat = (String)tempMap.get("inv_stat");
								locInvStat = locInvStat.trim();
								System.out.println("Current Loc Inv Stat ["+locInvStat+"]");
								String pndLoc =  "";//getAvilablePickLocation("N", conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
								String actPkDeepLoc = "";//getAvilablePickLocation(pickType, conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
							
								mapItemVolume = getItemVoumeMap(itemCode, lotNo, conn);														
								//double itemVolume = Math.floor((Double)mapItemVolume.get("ITEM_SIZE"));
								itemVolume = Math.floor((Double)mapItemVolume.get("ITEM_SIZE"));
								//double itemWeight= Math.floor((Double)mapItemVolume.get("ITEM_WEIGHT"));
								itemWeight= Math.floor((Double)mapItemVolume.get("ITEM_WEIGHT"));
								packSizeCase = (Double)mapItemVolume.get("PACK_SIZE");
								/*double itemVolumeTotal = quantity*itemVolume;
								double itemWeightTotal = quantity*itemWeight;	*/
								
								int refCtr = 1;
							
								pstmtRplDet.setString(1,replRefDeepId);
							
								pstmtRplDet.setInt(2,replCnt);
								
								pstmtRplDet.setString(3,saleOrder);
								pstmtRplDet.setString(4,sordLineNo);
								pstmtRplDet.setString(5,siteCode);
								pstmtRplDet.setString(6,itemCode);
								pstmtRplDet.setString(7,locCode);
								pstmtRplDet.setString(8,lotNo);
								pstmtRplDet.setString(9,lotSl);
								pstmtRplDet.setDouble(10,Double.parseDouble(noArt));
								pstmtRplDet.setDouble(11, casePackSize);
								pstmtRplDet.setInt(13,replCnt);
							    pstmtRplDet.setString(14,expLevel);
                              /* 
                                if(pndLoc != null && pndLoc.length() > 0)
                                {
                                	pstmtRplDet.setString(15,pndLoc);
                                }
                                else
                                {
                                	pstmtRplDet.setString(15,"");
                                	errString = getError(saleOrder,"INVPNDLOC",conn);
    	                			return errString;
                                }*/
          					
								//pstmtDet.setInt(2,pickCtr);
								pstmtDet.setString(3,saleOrder);
								pstmtDet.setString(4,sordLineNo);
								pstmtDet.setString(5,siteCode);
								pstmtDet.setString(6,itemCode);
								pstmtDet.setString(7,locCode);
								//pstmtDet.setString(7,actPkDeepLoc);
								pstmtDet.setString(8,lotNo);
								pstmtDet.setString(9,lotSl);
								pstmtDet.setDouble(10,Double.parseDouble(noArt));
								pstmtDet.setDouble(11,quantity);	
								pstmtDet.setString(12,expLevel);
								//Changed By Pragyan Demo4
								pstmtDet.setString(13,docLoc);
								//Changed By Pragyan 10/12/12 As the bug found after replenishment issue.statrt
								//pstmtDet.setString(14,replRefDeepId);
								//pstmtDet.setInt(15,replCnt);
								pstmtDet.setString(14,"");
								pstmtDet.setInt(15,0);
								//Changed By Pragyan 10/12/12 As the bug found after replenishment issue.end
								
								 
								ArrayList tempReplList = new ArrayList();
								ArrayList tempCaseReplList = new ArrayList();
								//if(locInvStat.equalsIgnoreCase(invDeepReserve) || locInvStat.equalsIgnoreCase(invReserve))
								
								///Changed By Pragyan 07/03/13 to check Direct pick location
								//if(!locInvStat.equalsIgnoreCase(activePickInv))
								if(!locInvStat.equalsIgnoreCase(activePickInv) && !(directPickLoc != null && directPickLoc.length() > 0))
								{
									 tempReplList = getActiveCaseReplMap("I",locInvStat,invPndReserve,invDeepReserve,invReserve, itemCode, siteCode, locCode, lotNo, lotSl, quantity, conn);
									 tempCaseReplList = getActiveCaseReplMap("",locInvStat,invPndReserve,invDeepReserve,invReserve, itemCode, siteCode, locCode, lotNo, lotSl, quantity, conn);
								}					
								
								if(tempReplList.size() > 0)
								{
									
									System.out.println("Inside tempReplList......");
									String locCodeAct =(String) tempReplList.get(0);
									double avilableQty = (Double) tempReplList.get(1);
									String acReplOrder =(String) tempReplList.get(2);
									String replLineNo =(String) tempReplList.get(3);
									String acPrvReplOrder =(String) tempReplList.get(4);
									String acPrvLineNo =(String) tempReplList.get(5);
									
									if(quantity >= avilableQty)
									{
											System.out.println("Inside tempReplList.. Quantity..Greater  then equals to avilabel quantity..");
											if(!isActivePickHdr)
											{
												pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"A-PICK","A",ptcn,conn);
												pickHdrCpy = pickRefId;
												isActivePickHdr = true;
												pstmt.setString(1,pickRefId);
												pstmt.executeUpdate();
											}
											else
											{
												pickRefId = pickHdrCpy;
												pickCtr++;
											}
											/*pstmt.setString(1,pickRefId);
											pstmt.executeUpdate();*/
											pstmtDet.setString(1,pickRefId);
											pstmtDet.setInt(2,pickCtr);
											pstmtDet.setString(7,locCodeAct);
											pstmtDet.setDouble(10,Double.parseDouble(noArt));
											pstmtDet.setDouble(11,avilableQty);
											pstmtDet.setString(14,acReplOrder);
											pstmtDet.setInt(15,Integer.parseInt(replLineNo));
											pstmtDet.executeUpdate();
											
											//updateReplOrdDet( "",itemCode, siteCode, locCode, lotNo, lotSl,locCodeAct,0.0,acReplOrder,replLineNo, conn);
											if(locInvStat.equalsIgnoreCase(invDeepReserve))
											{
												updateReplOrdDet( "",itemCode, siteCode, locCode, lotNo, lotSl,locCodeAct,0.0,acPrvReplOrder,acPrvLineNo, conn);
											}
											else
											{
												updateReplOrdDet( "",itemCode, siteCode, locCode, lotNo, lotSl,locCodeAct,0.0,acReplOrder,replLineNo, conn);
											}
											itemVolumeTotal = itemVolumeTotal + avilableQty*itemVolume;
											itemWeightTotal = itemWeightTotal + avilableQty*itemWeight;
											//updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"A-PICK", xtraParams, conn,itemWeightTotal,itemVolumeTotal,pickType);
											
											double quantityToUpd = quantity - avilableQty;
											if(quantityToUpd > 0)
											{
												System.out.println("Inside tempReplList.. Quantity..quantityToUpd more..");
												
												ArrayList tempReplCaseList = getActiveCaseReplMap("",locInvStat,invPndReserve,invDeepReserve,invReserve, itemCode, siteCode, locCode, lotNo, lotSl, quantity, conn);
				
												if(tempReplCaseList.size() > 0)
												{
													System.out.println("Inside tempReplList.. tempReplCaseList..quantityToUpd more..");
													String locCodeCase =(String) tempReplCaseList.get(0);
													double avilableCaseQty = (Double) tempReplCaseList.get(1);
													String cReplOrder =(String) tempReplCaseList.get(2);
													String cReplOrderLine =(String) tempReplCaseList.get(3);
													String cPReplOrder =(String) tempReplCaseList.get(4);
													String cPReplOrderLine =(String) tempReplCaseList.get(5);
													ArrayList tempReplCaseActList = getActiveCaseReplMap("Q",locInvStat,invPndReserve,invDeepReserve,invReserve, itemCode, siteCode, locCodeCase, lotNo, lotSl, quantity, conn);
													
													if(tempReplCaseActList.size() > 0)
													{
														System.out.println("Inside tempReplList.. Block quantity avilable in a case pick Location......");
														String locCodeCaseAct =(String) tempReplCaseActList.get(0);
														double avilableCaseActQty = (Double) tempReplCaseActList.get(1);
														String dReplOrder = (String) tempReplCaseActList.get(2);
														String dReplOrderLine = (String) tempReplCaseActList.get(3);
														String dPickReplOrder = (String) tempReplCaseActList.get(4);
														String dPickReplLineNo = (String) tempReplCaseActList.get(5);
														if(!isActivePickHdr)
														{
															pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"A-PICK","A",ptcn,conn);
															pickHdrCpy = pickRefId;
															isActivePickHdr = true;
															pstmt.setString(1,pickRefId);
															pstmt.executeUpdate();
														}
														else
														{
															pickRefId = pickHdrCpy;
															pickCtr++;
														}
														
														if(quantityToUpd >= avilableCaseActQty)
														{
															
															double pendActQty = quantityToUpd - avilableCaseActQty;
															//Changed by Rohan on 08-02-13 Quantity updated as 0.0
															//updateReplOrdDet("Q", itemCode, siteCode, locCodeCase, lotNo, lotSl,locCodeCaseAct, quantityToUpd,dReplOrder,dReplOrderLine, conn)
															updateReplOrdDet("Q", itemCode, siteCode, locCodeCase, lotNo, lotSl,locCodeCaseAct,0.0,dReplOrder,dReplOrderLine, conn);
															//Insert avilableQty into Pick Ord hdr and Det.stat
															pstmtDet.setString(1,pickRefId);
															pstmtDet.setInt(2,pickCtr);
															pstmtDet.setString(7,locCodeCaseAct);
															pstmtDet.setDouble(10,Double.parseDouble(noArt));
															pstmtDet.setDouble(11,quantityToUpd);
															pstmtDet.setString(14,dPickReplOrder);
															pstmtDet.setInt(15,Integer.parseInt(dPickReplLineNo));
															pstmtDet.executeUpdate();
															itemVolumeTotal = itemVolumeTotal +  quantityToUpd*itemVolume;
															itemWeightTotal =  itemWeightTotal + quantityToUpd*itemWeight;
															//updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"A-PICK", xtraParams, conn,itemWeightTotal,itemVolumeTotal,pickType);
															//Insert avilableQty into Pick Ord hdr and Det.end
															System.out.println("pendActQty"+pendActQty);
															if(pendActQty > 0)
															{
																if(!isReplHdr)
																{	
																	replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"R-CPA","E",ptcn,conn);
																	pstmtRplHdr.setString(1,replRefDeepId);
																	pstmtRplHdr.setString(9,"Q");
																	pstmtRplHdr.executeUpdate();
																	isReplHdr = true;
																	replOrdCpy = replRefDeepId;
																}
																else
																{
																	 replRefDeepId = replOrdCpy ;
																	 replCnt++;
																}
																
																
																															
																pstmtRplDet.setString(1,replRefDeepId);
																pstmtRplDet.setInt(2,replCnt);
																pstmtRplDet.setString(7,locCodeCase);
																//Changed by Rohan on 08-02-13 to insert 1 case into Quantity block
																//pstmtRplDet.setDouble(11, pendActQty);
																pstmtRplDet.setDouble(11, packSizeCase);
																System.out.println("packSizeCase--->>"+packSizeCase);
																pstmtRplDet.setString(12,acPrvReplOrder);
																pstmtRplDet.setInt(13,Integer.parseInt(acPrvLineNo));
																pstmtRplDet.setString(15,locCodeCaseAct);
																pstmtRplDet.executeUpdate();
																//Changed by Rohan 26/08/12 to add pick.start
																if(!isActivePickHdr)
																{
																	pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"A-PICK","A",ptcn,conn);
																	pickHdrCpy = pickRefId;
																	isActivePickHdr = true;
																	pstmt.setString(1,pickRefId);
																	pstmt.executeUpdate();
																}
																else
																{
																	pickRefId = pickHdrCpy;
																	pickCtr++;
																}
																
																pstmtDet.setString(1,pickRefId);
																pstmtDet.setInt(2,pickCtr);
																pstmtDet.setString(7,locCodeAct);
																pstmtDet.setDouble(10,Double.parseDouble(noArt));
																pstmtDet.setDouble(11,avilableQty);
																pstmtDet.setString(14,replRefDeepId);
																//Changed by Rohan on 13-09-12 to generate only one Repalnishmement
																pstmtDet.setInt(15,replCnt);
																pstmtDet.executeUpdate();
																//Changed by Rohan on 07-02-13 to reduce one case from actual quantity
																//updateReplOrdDet( "",itemCode, siteCode, locCode, lotNo, lotSl,actPkDeepLoc, (avilableCaseQty - packSizeCase - quantityToUpd) ,cReplOrder,cReplOrderLine, conn);//3
																System.out.println("3avilableCaseQty"+avilableCaseQty+"3packSizeCase"+packSizeCase+"3quantityToUpd"+quantityToUpd+"cPReplOrder"+cPReplOrder+"replRefDeepId"+replRefDeepId);
																//updateReplOrdDet( "",itemCode, siteCode, locCode, lotNo, lotSl,actPkDeepLoc, (avilableCaseQty - packSizeCase - quantityToUpd) ,cReplOrder,cReplOrderLine, conn);
																updateReplOrdDet( "",itemCode, siteCode, locCode, lotNo, lotSl,actPkDeepLoc, (avilableCaseQty - packSizeCase) ,cPReplOrder,cPReplOrderLine, conn);//test
																//Chnaged by Rohan on 08-02-13 for updating cupdating current Repl order
																//updateReplOrdDet( "Q",itemCode, siteCode, locCodeCase, lotNo, lotSl,locCodeCaseAct, (packSizeCase - pendActQty) ,dReplOrder,dReplOrderLine, conn);
																updateReplOrdDet( "Q",itemCode, siteCode, locCodeCase, lotNo, lotSl,locCodeCaseAct, (packSizeCase - pendActQty) ,replRefDeepId,String.valueOf(replCnt), conn);//test
																itemVolumeTotal = itemVolumeTotal +  pendActQty*itemVolume;
																itemWeightTotal = itemWeightTotal + pendActQty*itemWeight;
																//updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"A-PICK", xtraParams, conn,itemWeightTotal,itemVolumeTotal,pickType);
															}
															
														}
														else
														{
															
															updateReplOrdDet( "Q",itemCode, siteCode, locCodeCase, lotNo, lotSl,locCodeCaseAct, quantityToUpd,dReplOrder,dReplOrderLine, conn);
															pstmtDet.setString(1,pickRefId);
															pstmtDet.setInt(2,pickCtr);
															pstmtDet.setString(7,locCodeCaseAct);
															pstmtDet.setDouble(10,Double.parseDouble(noArt));
															pstmtDet.setDouble(11,quantityToUpd);
															pstmtDet.setString(14,acPrvReplOrder);
															pstmtDet.setInt(15,Integer.parseInt(acPrvLineNo));
															pstmtDet.executeUpdate();
															itemVolumeTotal = itemVolumeTotal + quantityToUpd*itemVolume;
															itemWeightTotal = itemWeightTotal + quantityToUpd*itemWeight;
															//updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"A-PICK", xtraParams, conn,itemWeightTotal,itemVolumeTotal,pickType);
														}
													}
													else
													{		
														
														System.out.println("Inside tempReplList.. Block quantity avilable in suggested case pick Location...");
														pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"A-PICK","A",ptcn,conn);
														if(!isReplHdr)
														{
															replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"R-CPA","E",ptcn,conn);
															pstmtRplHdr.setString(1,replRefDeepId);
															pstmtRplHdr.setString(9,"Q");
															pstmtRplHdr.executeUpdate();
															isReplHdr = true;
															replOrdCpy = replRefDeepId;
														}
														else
														{
															 replRefDeepId = replOrdCpy ;
															 replCnt++;
														}
														pstmtRplDet.setString(1,replRefDeepId);
														pstmtRplDet.setInt(2,replCnt);
														
														pstmtRplDet.setString(7,locCodeCase);
														pstmtRplDet.setDouble(11, casePackSize);
														//pstmtRplDet.setString(12,cPReplOrder);
														pstmtRplDet.setString(12,cReplOrder);
														pstmtRplDet.setInt(13,Integer.parseInt(cReplOrderLine));
														pstmtRplDet.setString(15,actPkDeepLoc);
														
														actPkDeepLoc = getAvilablePickLocation(pickType, conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
														if(actPkDeepLoc != null && actPkDeepLoc.length() > 0)
						                                {
						                                	pstmtRplDet.setString(15,actPkDeepLoc);
						                                }
						                                else
						                                {
						                                	pstmtRplDet.setString(15,"");
						                                	errString = getError(saleOrder,"INVAPKLOC",conn);
						    	                			return errString;
						                                }
														pstmtRplDet.executeUpdate();
														
														if(!isActivePickHdr)
														{
															pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"A-PICK","A",ptcn,conn);
															pickHdrCpy = pickRefId;
															isActivePickHdr = true;
															pstmt.setString(1,pickRefId);
															pstmt.executeUpdate();
														}
														else
														{
															pickRefId = pickHdrCpy;
															pickCtr++;
														}
														
														pstmtDet.setString(1,pickRefId);
														pstmtDet.setInt(2,pickCtr);
														pstmtDet.setString(7,actPkDeepLoc);
														pstmtDet.setDouble(10,Double.parseDouble(noArt));
														pstmtDet.setDouble(11,quantityToUpd);
														//pstmtRplDet.setDouble(11, casePackSize);
														pstmtDet.setString(14,replRefDeepId);
														pstmtDet.setInt(15,replCnt);
														pstmtDet.executeUpdate();
														
														updateReplOrdDet( "Q",itemCode, siteCode, locCodeCase, lotNo, lotSl,actPkDeepLoc, (packSizeCase - quantityToUpd) ,replRefDeepId,String.valueOf(replCnt), conn);
														System.out.println("Changing update****"+(avilableCaseQty - packSizeCase - quantityToUpd));
														System.out.println("Changing update*###***"+(avilableCaseQty - packSizeCase));
														
														System.out.println("cReplOrder"+cReplOrder+"acReplOrder"+acReplOrder+"cPReplOrder"+cPReplOrder+"cPReplOrderLine"+cPReplOrderLine);
														//Changed by Rohan on 07-02-13 to reduce one case from actual quantity
														
														//updateReplOrdDet( "",itemCode, siteCode, locCode, lotNo, lotSl,actPkDeepLoc, (avilableCaseQty - packSizeCase - quantityToUpd) ,cReplOrder,cReplOrderLine, conn);
														updateReplOrdDet( "",itemCode, siteCode, locCode, lotNo, lotSl,actPkDeepLoc, (avilableCaseQty - packSizeCase) ,cPReplOrder,cPReplOrderLine, conn);
														
														itemVolumeTotal = itemVolumeTotal + quantityToUpd*itemVolume;
														itemWeightTotal = itemWeightTotal + quantityToUpd*itemWeight;
														//updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"A-PICK", xtraParams, conn,itemWeightTotal,itemVolumeTotal,pickType);
														
													}
												
												}
												else
												{			
													System.out.println("Inside tempReplList.. Block Unknown avilable in suggested case pick Location...");
													//Changed By Pragyan 07/03/13 to check Direct pick location
													//if(!locInvStat.equalsIgnoreCase(activePickInv))
													if(!locInvStat.equalsIgnoreCase(activePickInv) && !(directPickLoc != null && directPickLoc.length() > 0))
													{
														
														if(locInvStat.equalsIgnoreCase(casePickInv))
														{
															if(!isReplHdr)
															{	
																replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"R-CPA","E",ptcn,conn);
																pstmtRplHdr.setString(1,replRefDeepId);
																pstmtRplHdr.setString(9,"Q");
																pstmtRplHdr.executeUpdate();
																isReplHdr = true;
																replOrdCpy = replRefDeepId;
															}
															else
															{
																 replRefDeepId = replOrdCpy ;
																 replCnt++;
																 refCtr = replCnt;
															}
														}
														
														
														if(locInvStat.equalsIgnoreCase(invDeepReserve))
														{
															if(!isReplHdrDSO)
															{	
																replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"RD-DSA","E",ptcn,conn);
																pstmtRplHdr.setString(1,replRefDeepId);
																pstmtRplHdr.setString(9,"E");
																pstmtRplHdr.executeUpdate();
																isReplHdrDSO = true;
																replOrdDSOCpy = replRefDeepId;
															}
															else
															{
																 replRefDeepId = replOrdDSOCpy ;
																 //replCnt++;
																 rplCntDSO++;
																 System.out.println("Current DSO Line No ["+rplCntDSO+"]");
																 refCtr = rplCntDSO;
																 System.out.println("Current DSO Line No refCtr ["+refCtr+"]");
															}
														}
														
														if(locInvStat.equalsIgnoreCase(invReserve))
														{
															if(!isReplHdrPSO)
															{	
																replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"RR-DSA","E",ptcn,conn);
																pstmtRplHdr.setString(1,replRefDeepId);
																//pstmtRplHdr.setString(9,"Q");
																pstmtRplHdr.setString(9,"P");
																pstmtRplHdr.executeUpdate();
																isReplHdrPSO = true;
																replOrdPSOCpy = replRefDeepId;
															}
															else
															{
																 replRefDeepId = replOrdPSOCpy ;
																 //replCnt++;
																 rplCntPSO++;
																 refCtr = rplCntPSO;
															}
														}
														
														if(locInvStat.equalsIgnoreCase(partialResrvLoc))
														{
															if(!isReplHdrRSV)
															{	
																replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"RP-ACT","E",ptcn,conn);
																pstmtRplHdr.setString(1,replRefDeepId);
																pstmtRplHdr.setString(9,"T");
																pstmtRplHdr.executeUpdate();
																isReplHdrRSV = true;
																replOrdRSVCpy = replRefDeepId;
															}
															else
															{
																 replRefDeepId = replOrdRSVCpy ;
																 //replCnt++;
																 rplCntRSV++;
																 refCtr = rplCntRSV;
															}
														}
														
																							
														pstmtRplDet.setString(1,replRefDeepId);
														pstmtRplDet.setInt(2,refCtr);
														pstmtRplDet.setString(12,"");
														//replCnt++;
														pstmtRplDet.setInt(13,0);
														
														/*if(locInvStat.equalsIgnoreCase(partialResrvLoc))
														{
															packSizeCase = stkQty;
															pstmtRplDet.setDouble(11, stkQty);
															
														}*/
														
														if(locInvStat.equalsIgnoreCase(invDeepReserve))
														{
															pndLoc = getAvilablePickLocation("N", conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
															if(pndLoc != null && pndLoc.length() > 0)
							                                {
							                                	pstmtRplDet.setString(15,pndLoc);
							                                }
							                                else
							                                {
							                                	pstmtRplDet.setString(15,"");
							                                	errString = getError(saleOrder,"INVPNDLOC",conn);
							    	                			return errString;
							                                }
														}
														else
														{
															
															
															actPkDeepLoc = getAvilablePickLocation(pickType, conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
															if(actPkDeepLoc != null && actPkDeepLoc.length() > 0)
							                                {
							                                	pstmtRplDet.setString(15,actPkDeepLoc);
							                                }
							                                else
							                                {
							                                	pstmtRplDet.setString(15,"");
							                                	errString = getError(saleOrder,"INVAPKLOC",conn);
							    	                			return errString;
							                                }
														}
														
														pstmtRplDet.executeUpdate();
													}
													
													
													if(locInvStat.equalsIgnoreCase(invDeepReserve))
													{
														
														if(!isReplHdrPND)
														{	
															replRefPndId = updateWaveTaskDet(waveID,1,saleOrder,"RN-DSA","E",ptcn,conn);
															pstmtRplHdr.setString(1,replRefPndId);
															pstmtRplHdr.setString(9,"I");
															pstmtRplHdr.executeUpdate();
															isReplHdrPND = true;
															replPNDCpy = replRefPndId;
														}
														else
														{
															replRefPndId = replPNDCpy ;
															//replCnt++;
															rplCntPND++;
														}
														
														actPkDeepLoc = getAvilablePickLocation(pickType, conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
														pstmtRplDet.setString(1,replRefPndId);
														
														pstmtRplDet.setInt(2,rplCntPND);
														pstmtRplDet.setString(12,replRefDeepId);
														pstmtRplDet.setInt(13,rplCntDSO);
														
														pstmtRplDet.setString(7,pndLoc);
														
														if(actPkDeepLoc != null && actPkDeepLoc.length() > 0)
						                                {
						                                	pstmtRplDet.setString(15,actPkDeepLoc);
						                                }
						                                else
						                                {
						                                	pstmtRplDet.setString(15,"");
						                                	errString = getError(saleOrder,"INVAPKLOC",conn);
						    	                			return errString;
						                                }									
														pstmtRplDet.executeUpdate();
													}
													

													if(!isActivePickHdr)
													{
														pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"A-PICK","A",ptcn,conn);
														pickHdrCpy = pickRefId;
														isActivePickHdr = true;
														pstmt.setString(1,pickRefId);
														pstmt.executeUpdate();
													}
													else
													{
														pickRefId = pickHdrCpy;
														pickCtr++;
													}
													
													
													pstmtDet.setString(1,pickRefId);
													pstmtDet.setInt(2,pickCtr);
													if(locInvStat.equalsIgnoreCase(invDeepReserve) || locInvStat.equalsIgnoreCase(invReserve) ||  locInvStat.equalsIgnoreCase(casePickInv) || locInvStat.equalsIgnoreCase(partialResrvLoc))
													{
														pstmtDet.setString(7,actPkDeepLoc);
													}
													else
													{
														pstmtDet.setString(7,locCode);
													}
													pstmtDet.setDouble(11,quantityToUpd);	
													if(locInvStat.equalsIgnoreCase(invDeepReserve))
													{
														pstmtDet.setString(14,replRefPndId);
														pstmtDet.setInt(15,rplCntPND);
													}
													else
													{
														pstmtDet.setString(14,replRefDeepId);
														pstmtDet.setInt(15,refCtr);
													}
													
													pstmtDet.executeUpdate();
													
													updateReplOrdDet("I", itemCode, siteCode, locCode, lotNo, lotSl,actPkDeepLoc,(packSizeCase - quantityToUpd),replRefDeepId,String.valueOf(refCtr), conn);
													itemVolumeTotal = itemVolumeTotal + quantityToUpd*itemVolume;
													itemWeightTotal = itemWeightTotal +  quantityToUpd*itemWeight;
													//updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"A-PICK", xtraParams, conn,itemWeightTotal,itemVolumeTotal,pickType);
												}
												
											}
											
									}	 	
									else
									{
										System.out.println("Inside tempReplList.. Quantity..less then avilabel quantity..");
										if(!isActivePickHdr)
										{
											pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"A-PICK","A",ptcn,conn);
											pickHdrCpy = pickRefId;
											isActivePickHdr = true;
											pstmt.setString(1,pickRefId);
											pstmt.executeUpdate();
										}
										else
										{
											pickRefId = pickHdrCpy;
											pickCtr++;
										}
										pstmtDet.setString(1,pickRefId);
										pstmtDet.setInt(2,pickCtr);
										pstmtDet.setString(7,locCodeAct);
										pstmtDet.setDouble(10,Double.parseDouble(noArt));
										pstmtDet.setDouble(11,quantity);
										pstmtDet.setString(14,acReplOrder);
										//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header
										pstmtDet.setString(15,replLineNo);
										
										pstmtDet.executeUpdate();
										//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header
										//updateReplOrdDet("I", itemCode, siteCode, locCode, lotNo, lotSl,locCodeAct, avilableQty - quantity,acReplOrder, conn);
										if(locInvStat.equalsIgnoreCase(invDeepReserve))
										{
											updateReplOrdDet("I", itemCode, siteCode, locCode, lotNo, lotSl,locCodeAct, avilableQty - quantity,acPrvReplOrder,acPrvLineNo, conn);
										}
										else
										{
											updateReplOrdDet("I", itemCode, siteCode, locCode, lotNo, lotSl,locCodeAct, avilableQty - quantity,acReplOrder,replLineNo, conn);
										}
										itemVolumeTotal = itemVolumeTotal +  quantity*itemVolume;
										itemWeightTotal = itemWeightTotal +  quantity*itemWeight;
										//updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"A-PICK", xtraParams, conn,itemWeightTotal,itemVolumeTotal,pickType);
									}
								}
								else if(tempCaseReplList.size() > 0)
								{
									
										System.out.println("tempCaseReplList..");
										String locCodeCase =(String) tempCaseReplList.get(0);
										double avilableCaseQty = (Double) tempCaseReplList.get(1);
										String lloReplOrder =(String) tempCaseReplList.get(2);
										//Chnaged by Rohan on to pick order from list.start
										String replLineNo =(String) tempCaseReplList.get(3);
										String prvpickOrder = (String) tempCaseReplList.get(4);
										String pickLineNo = (String) tempCaseReplList.get(5);
										//Chnaged by Rohan on to pick order from list.end
										
										ArrayList tempReplCaseActList = getActiveCaseReplMap("Q",locInvStat,invPndReserve,invDeepReserve,invReserve, itemCode, siteCode, locCodeCase, lotNo, lotSl, quantity, conn);
										System.out.println("Current size activity repl exist ["+tempReplCaseActList.size()+"]");
										if(tempReplCaseActList.size() > 0)
										{
											
											System.out.println("tempCaseReplList..tempReplCaseActList");
											String locCodeCaseAct =(String) tempReplCaseActList.get(0);
											double avilableCaseActQty = (Double) tempReplCaseActList.get(1);
											String sReplOrder =(String) tempReplCaseActList.get(2);
											//Changed by Rohan on 12-09-12 to add pick order as reference of depended Replanishment.start
											//Changed by Rohan on 26-10-12 for bug fixing.start
											/*
											String replLineNoDsa =(String) tempCaseReplList.get(3);
											String prvpickOrderDsa = (String) tempCaseReplList.get(4);
											String pickLineNoDsa = (String) tempCaseReplList.get(5);
											*/
											
											String replLineNoDsa =(String) tempReplCaseActList.get(3);
											String prvpickOrderDsa = (String) tempReplCaseActList.get(4);
											String pickLineNoDsa = (String) tempReplCaseActList.get(5);
											//Changed by Rohan on 26-10-12 for bug fixing.end
											
											//Changed by Rohan on 12-09-12 to add pick order as reference of depended Replanishment.end
											//String pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"A-PICK","A",ptcn,conn);
																						
											if(quantity >= avilableCaseActQty)
											{	
												double pendActQty = quantity - avilableCaseActQty;
												System.out.println("pendActQty%%%%%"+pendActQty);
												if(!isActivePickHdr)
												{
													pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"A-PICK","A",ptcn,conn);
													pickHdrCpy = pickRefId;
													isActivePickHdr = true;
													pstmt.setString(1,pickRefId);
													pstmt.executeUpdate();
												}
												else
												{
													pickRefId = pickHdrCpy;
													pickCtr++;
												}
												pstmtDet.setString(1,pickRefId);
												pstmtDet.setInt(2,pickCtr);
												pstmtDet.setString(7,locCodeCaseAct);
												pstmtDet.setDouble(10,Double.parseDouble(noArt));
												pstmtDet.setDouble(11,avilableCaseActQty);
												pstmtDet.setString(14,sReplOrder);
												//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header
												pstmtDet.setInt(15,Integer.parseInt(replLineNoDsa));
												pstmtDet.executeUpdate();
												
												updateReplOrdDet( "Q",itemCode, siteCode, locCodeCase, lotNo, lotSl,locCodeCaseAct, 0.0,sReplOrder,replLineNoDsa, conn);
												//updateReplOrdDet( "",itemCode, siteCode, locCode, lotNo, lotSl,actPkDeepLoc, (avilableCaseQty - avilableCaseActQty) ,lloReplOrder,replLineNo, conn);
												//Changed by Rohan on 07-02-13 to reduce one case from actual quantity
												//updateReplenishmentRecord(itemCode, siteCode, lotNo, lotSl, locCode, avilableCaseActQty, lloReplOrder,"",9999, 2,casePackSize,false, conn);
												System.out.println("6avilableCaseActQty::::NOT Requried"+avilableCaseActQty+"casePackSize"+casePackSize);
												//Changed by Rohan on 13-02-13 for not reduce one case if qty allocated from Q repanishment
												//updateReplenishmentRecord(itemCode, siteCode, lotNo, lotSl, locCode, casePackSize, lloReplOrder,"",9999, 2,casePackSize,false, conn);//testdone
												itemVolumeTotal = itemVolumeTotal + avilableCaseActQty*itemVolume;
												itemWeightTotal = itemWeightTotal + avilableCaseActQty*itemWeight;
												//updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"A-PICK", xtraParams, conn,itemWeightTotal,itemVolumeTotal,pickType);
												//Insert avilableQty into Pick Ord hdr and Det.end
												
												if(pendActQty > 0)
												{
													if(!isReplHdr)
													{	
														replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"R-CPA","C",ptcn,conn);
														pstmtRplHdr.setString(1,replRefDeepId);
														pstmtRplHdr.setString(9,"Q");
														pstmtRplHdr.executeUpdate();
														isReplHdr = true;
														replOrdCpy = replRefDeepId;
													}
													else
													{
														 replRefDeepId = replOrdCpy ;
														 replCnt++;
													}
													
												
													pstmtRplDet.setString(1,replRefDeepId);
													//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header
													pstmtRplDet.setInt(2,replCnt);
													pstmtRplDet.setString(7,locCodeCase);
													//Changed by Rohan on 12-09-12 to add pick order as reference of depended Replanishment
													//pstmtRplDet.setString(12,pickRefId);
													/*pstmtRplDet.setString(12,sReplOrder);
													pstmtRplDet.setInt(13,Integer.parseInt(replLineNoDsa));*/
													pstmtRplDet.setString(12,lloReplOrder);
													pstmtRplDet.setInt(13,Integer.parseInt(replLineNo));
													actPkDeepLoc = getAvilablePickLocation(pickType, conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
													if(actPkDeepLoc != null && actPkDeepLoc.length() > 0)
					                                {
					                                	pstmtRplDet.setString(15,actPkDeepLoc);
					                                }
					                                else
					                                {
					                                	pstmtRplDet.setString(15,"");
					                                	errString = getError(saleOrder,"INVAPKLOC",conn);
					    	                			return errString;
					                                }
													
													pstmtRplDet.executeUpdate();
													
													if(!isActivePickHdr)
													{
														pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"A-PICK","A",ptcn,conn);
														pickHdrCpy = pickRefId;
														isActivePickHdr = true;
														pstmt.setString(1,pickRefId);
														pstmt.executeUpdate();
													}
													else
													{
														pickRefId = pickHdrCpy;
														pickCtr++;
													}
												
													pstmtDet.setString(1,pickRefId);
													pstmtDet.setInt(2,pickCtr);
													pstmtDet.setString(7,actPkDeepLoc);
													pstmtDet.setDouble(11,pendActQty);
													pstmtDet.setString(14,replRefDeepId);
													//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header
													pstmtDet.setInt(15,replCnt);
													pstmtDet.executeUpdate();
													
													updateReplOrdDet( "Q",itemCode, siteCode, locCodeCase, lotNo, lotSl,actPkDeepLoc, (packSizeCase - pendActQty) ,replRefDeepId,String.valueOf(replCnt), conn);
													//updateReplOrdDet( "",itemCode, siteCode, locCode, lotNo, lotSl,actPkDeepLoc, (avilableCaseQty - pendActQty - avilableCaseActQty) ,lloReplOrder,replLineNo, conn);
													//Changed by Rohan on 07-02-13 to reduce one case from actual quantity
													//updateReplenishmentRecord(itemCode, siteCode, lotNo, lotSl, locCode, pendActQty, lloReplOrder,"",9999, 2,casePackSize,false, conn);
													System.out.println("5pendActQty"+pendActQty+"casePackSize"+casePackSize+"not ***** ***** requried");
													updateReplenishmentRecord(itemCode, siteCode, lotNo, lotSl, locCode, casePackSize, lloReplOrder,"",9999, 2,casePackSize,false, conn);//not requried
													
													//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header.end
													itemVolumeTotal = itemVolumeTotal +  pendActQty*itemVolume;
													itemWeightTotal = itemWeightTotal +  pendActQty*itemWeight;
													//updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"A-PICK", xtraParams, conn,itemWeightTotal,itemVolumeTotal,pickType);
												}
												
											}
											else
											{
												double pendActQty = avilableCaseActQty -  quantity;
												if(!isActivePickHdr)
												{
													pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"A-PICK","A",ptcn,conn);
													pickHdrCpy = pickRefId;
													isActivePickHdr = true;
													pstmt.setString(1,pickRefId);
													pstmt.executeUpdate();
												}
												else
												{
													pickRefId = pickHdrCpy;
													pickCtr++;
												}
												pstmtDet.setString(1,pickRefId);
												pstmtDet.setInt(2,pickCtr);
												pstmtDet.setString(7,locCodeCaseAct);
												pstmtDet.setDouble(10,Double.parseDouble(noArt));
												pstmtDet.setDouble(11,quantity);
												pstmtDet.setString(14,sReplOrder);
												//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header
												pstmtDet.setInt(15,Integer.parseInt(replLineNoDsa));
												pstmtDet.executeUpdate();
								
												updateReplOrdDet( "Q",itemCode, siteCode, locCodeCase, lotNo, lotSl,locCodeCaseAct,pendActQty,sReplOrder,replLineNoDsa, conn);
												//updateReplOrdDet( "",itemCode, siteCode, locCode, lotNo, lotSl,actPkDeepLoc, (avilableCaseQty - quantity) ,lloReplOrder,replLineNo, conn);
												//Changed by Rohan on 07-02-13 to reduce one case from actual quantity
												//updateReplenishmentRecord(itemCode, siteCode, lotNo, lotSl, locCode, quantity, lloReplOrder,"",9999, 2,casePackSize,false, conn);
												System.out.println("4quantity"+quantity+"casePackSize"+casePackSize);
												//Changed by rohan on 13-02-13 for bug fixing not requried to update case actual qty because stock allocate from active location
												//updateReplenishmentRecord(itemCode, siteCode, lotNo, lotSl, locCode, casePackSize, lloReplOrder,"",9999, 2,casePackSize,false, conn);//done
												itemVolumeTotal =itemVolumeTotal +  quantity*itemVolume;
												itemWeightTotal = itemWeightTotal + quantity*itemWeight;
												//updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"A-PICK", xtraParams, conn,itemWeightTotal,itemVolumeTotal,pickType);
											}
										}
										else
										{
											System.out.println("tempCaseReplList..replenishment");
											System.out.println("in replenishment block");
											
											if(!isReplHdr)
											{	
												replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"R-CPA","C",ptcn,conn);
												pstmtRplHdr.setString(1,replRefDeepId);
												pstmtRplHdr.setString(9,"Q");
												pstmtRplHdr.executeUpdate();
												isReplHdr = true;
												replOrdCpy = replRefDeepId;
											}
											else
											{
												 replRefDeepId = replOrdCpy ;
												 replCnt++;
												
											}
											
											
											System.out.println("replRefDeepId"+replRefDeepId+"replCtr"+replCnt);
											pstmtRplDet.setString(1,replRefDeepId);
											//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header
											pstmtRplDet.setInt(2,replCnt);
											
											pstmtRplDet.setString(7,locCodeCase);
											//Changed by Rohan on 11-09-12 to add pick order reference
											//pstmtRplDet.setString(12,pickRefId);	
											/*if(locInvStat.equalsIgnoreCase(invDeepReserve))
											{
												pstmtRplDet.setString(12,lloReplOrder);
												pstmtRplDet.setInt(13,Integer.parseInt(replLineNo));
											}
											else
											{
												pstmtRplDet.setString(12,prvpickOrder);
												pstmtRplDet.setInt(13,Integer.parseInt(pickLineNo));
											}*/
											pstmtRplDet.setString(12,lloReplOrder);
											pstmtRplDet.setInt(13,Integer.parseInt(replLineNo));
											
											
											actPkDeepLoc = getAvilablePickLocation(pickType, conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
											if(actPkDeepLoc != null && actPkDeepLoc.length() > 0)
			                                {
			                                	pstmtRplDet.setString(15,actPkDeepLoc);
			                                }
			                                else
			                                {
			                                	pstmtRplDet.setString(15,"");
			                                	errString = getError(saleOrder,"INVAPKLOC",conn);
			    	                			return errString;
			                                }
											
											pstmtRplDet.executeUpdate();
											if(!isActivePickHdr)
											{
												pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"A-PICK","A",ptcn,conn);
												pickHdrCpy = pickRefId;
												isActivePickHdr = true;
												pstmt.setString(1,pickRefId);
												pstmt.executeUpdate();
											}
											else
											{
												pickRefId = pickHdrCpy;
												pickCtr++;
											}
										
											pstmtDet.setString(1,pickRefId);
											pstmtDet.setInt(2,pickCtr);
											pstmtDet.setString(7,actPkDeepLoc);
											pstmtDet.setDouble(11,quantity);
											pstmtDet.setString(14,replRefDeepId);
											//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header
											pstmtDet.setInt(15,replCnt);
											pstmtDet.executeUpdate();
											
											updateReplOrdDet( "Q",itemCode, siteCode, locCodeCase, lotNo, lotSl,actPkDeepLoc, (packSizeCase - quantity) ,replRefDeepId,String.valueOf(replCnt), conn);
											//updateReplOrdDet( "",itemCode, siteCode, locCode, lotNo, lotSl,actPkDeepLoc, (avilableCaseQty - quantity) ,lloReplOrder,replLineNo, conn);
											System.out.println("updateReplenishmentRecord"+casePackSize+"quantity"+quantity);
											
											//Changed by Rohan on 07-02-13 to reduce one case from actual quantity
											//updateReplenishmentRecord(itemCode, siteCode, lotNo, lotSl, locCode,quantity , lloReplOrder,"",9999, 2,casePackSize,false, conn);
											updateReplenishmentRecord(itemCode, siteCode, lotNo, lotSl, locCode,casePackSize , lloReplOrder,"",9999, 2,casePackSize,false, conn);
											
											itemVolumeTotal = itemVolumeTotal +  quantity*itemVolume;
											itemWeightTotal = itemWeightTotal + quantity*itemWeight;
											//updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"A-PICK", xtraParams, conn,itemWeightTotal,itemVolumeTotal,pickType);
										}
										
									
								}
								else
								{
									
									System.out.println("Inside Normal Block...");
									
									double stkQty = getStockQty(itemCode, siteCode, lotNo, lotSl, locCode);
									
									System.out.println("Stock Quantity"+stkQty);
									//if(locInvStat.equalsIgnoreCase(invDeepReserve) || locInvStat.equalsIgnoreCase(invReserve) ||  locInvStat.equalsIgnoreCase(casePickInv))
									System.out.println("locInvStat::::::>>>>>>>>:::::"+locInvStat);
									//Changed By Pragyan 07/03/13 to check Direct pick location
									//if(!locInvStat.equalsIgnoreCase(activePickInv))
									if(!locInvStat.equalsIgnoreCase(activePickInv) && !(directPickLoc != null && directPickLoc.length() > 0))
									{
										
										if(locInvStat.equalsIgnoreCase(casePickInv))
										{
											if(!isReplHdr)
											{	
												replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"R-CPA","E",ptcn,conn);
												pstmtRplHdr.setString(1,replRefDeepId);
												pstmtRplHdr.setString(9,"Q");
												pstmtRplHdr.executeUpdate();
												isReplHdr = true;
												replOrdCpy = replRefDeepId;
											}
											else
											{
												 replRefDeepId = replOrdCpy ;
												 replCnt++;
												 refCtr = replCnt;
											}
										}
										
										
										if(locInvStat.equalsIgnoreCase(invDeepReserve))
										{
											if(!isReplHdrDSO)
											{	
												replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"RD-DSA","E",ptcn,conn);
												pstmtRplHdr.setString(1,replRefDeepId);
												pstmtRplHdr.setString(9,"E");
												pstmtRplHdr.executeUpdate();
												isReplHdrDSO = true;
												replOrdDSOCpy = replRefDeepId;
											}
											else
											{
												 replRefDeepId = replOrdDSOCpy ;
												 //replCnt++;
												 rplCntDSO++;
												 System.out.println("Current DSO Line No ["+rplCntDSO+"]");
												 refCtr = rplCntDSO;
												 System.out.println("Current DSO Line No refCtr ["+refCtr+"]");
											}
										}
										
										if(locInvStat.equalsIgnoreCase(invReserve))
										{
											if(!isReplHdrPSO)
											{	
												replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"RR-DSA","E",ptcn,conn);
												pstmtRplHdr.setString(1,replRefDeepId);
												//pstmtRplHdr.setString(9,"Q");
												pstmtRplHdr.setString(9,"P");
												pstmtRplHdr.executeUpdate();
												isReplHdrPSO = true;
												replOrdPSOCpy = replRefDeepId;
											}
											else
											{
												 replRefDeepId = replOrdPSOCpy ;
												 //replCnt++;
												 rplCntPSO++;
												 refCtr = rplCntPSO;
											}
										}
										
										if(locInvStat.equalsIgnoreCase(partialResrvLoc))
										{
											System.out.println("Inside loc_in_stat---->");
											if(!isReplHdrRSV)
											{	
												replRefDeepId = updateWaveTaskDet(waveID,1,saleOrder,"RP-ACT","E",ptcn,conn);
												pstmtRplHdr.setString(1,replRefDeepId);
												//pstmtRplHdr.setString(9,"Q");
												pstmtRplHdr.setString(9,"T");
												pstmtRplHdr.executeUpdate();
												isReplHdrRSV = true;
												replOrdRSVCpy = replRefDeepId;
											}
											else
											{
												 replRefDeepId = replOrdRSVCpy ;
												 //replCnt++;
												 rplCntRSV++;
												 refCtr = rplCntRSV;
											}
										}
										
																			
										pstmtRplDet.setString(1,replRefDeepId);
										pstmtRplDet.setInt(2,refCtr);
										pstmtRplDet.setString(12,"");
										//replCnt++;
										pstmtRplDet.setInt(13,0);
										
										if(locInvStat.equalsIgnoreCase(partialResrvLoc))
										{
											packSizeCase = stkQty;
											System.out.println("packSizeCase::::::::"+packSizeCase);
											pstmtRplDet.setDouble(11, stkQty);
											
										}
										
										if(locInvStat.equalsIgnoreCase(invDeepReserve))
										{
											pndLoc = getAvilablePickLocation("N", conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
											if(pndLoc != null && pndLoc.length() > 0)
			                                {
			                                	pstmtRplDet.setString(15,pndLoc);
			                                }
			                                else
			                                {
			                                	pstmtRplDet.setString(15,"");
			                                	errString = getError(saleOrder,"INVPNDLOC",conn);
			    	                			return errString;
			                                }
										}
										else
										{
											
											
											actPkDeepLoc = getAvilablePickLocation(pickType, conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
											if(actPkDeepLoc != null && actPkDeepLoc.length() > 0)
			                                {
			                                	pstmtRplDet.setString(15,actPkDeepLoc);
			                                }
			                                else
			                                {
			                                	pstmtRplDet.setString(15,"");
			                                	errString = getError(saleOrder,"INVAPKLOC",conn);
			    	                			return errString;
			                                }
										}
										
										pstmtRplDet.executeUpdate();
									}
									
									
									if(locInvStat.equalsIgnoreCase(invDeepReserve))
									{
										
										if(!isReplHdrPND)
										{	
											replRefPndId = updateWaveTaskDet(waveID,1,saleOrder,"RN-DSA","E",ptcn,conn);
											pstmtRplHdr.setString(1,replRefPndId);
											pstmtRplHdr.setString(9,"I");
											pstmtRplHdr.executeUpdate();
											isReplHdrPND = true;
											replPNDCpy = replRefPndId;
										}
										else
										{
											replRefPndId = replPNDCpy ;
											//replCnt++;
											rplCntPND++;
										}
										
										actPkDeepLoc = getAvilablePickLocation(pickType, conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
										pstmtRplDet.setString(1,replRefPndId);
										
										pstmtRplDet.setInt(2,rplCntPND);
										pstmtRplDet.setString(12,replRefDeepId);
										pstmtRplDet.setInt(13,rplCntDSO);
										
										pstmtRplDet.setString(7,pndLoc);
										
										if(actPkDeepLoc != null && actPkDeepLoc.length() > 0)
		                                {
		                                	pstmtRplDet.setString(15,actPkDeepLoc);
		                                }
		                                else
		                                {
		                                	pstmtRplDet.setString(15,"");
		                                	errString = getError(saleOrder,"INVAPKLOC",conn);
		    	                			return errString;
		                                }									
										pstmtRplDet.executeUpdate();
									}
									

									if(!isActivePickHdr)
									{
										pickRefId = updateWaveTaskDet(waveID,2,saleOrder,"A-PICK","A",ptcn,conn);
										pickHdrCpy = pickRefId;
										isActivePickHdr = true;
										pstmt.setString(1,pickRefId);
										pstmt.executeUpdate();
									}
									else
									{
										pickRefId = pickHdrCpy;
										pickCtr++;
									}
									
									
									pstmtDet.setString(1,pickRefId);
									pstmtDet.setInt(2,pickCtr);
									if(locInvStat.equalsIgnoreCase(invDeepReserve) || locInvStat.equalsIgnoreCase(invReserve) ||  locInvStat.equalsIgnoreCase(casePickInv) || locInvStat.equalsIgnoreCase(partialResrvLoc))
									{
										pstmtDet.setString(7,actPkDeepLoc);
									}
									else
									{
										pstmtDet.setString(7,locCode);
									}
									
									if(locInvStat.equalsIgnoreCase(invDeepReserve))
									{
										pstmtDet.setString(14,replRefPndId);
										pstmtDet.setInt(15,rplCntPND);
									}
									else
									{
																				
										if(locInvStat.equalsIgnoreCase(activePickInv))
										{
											System.out.println("Updating Repelenishment blank and ");
											pstmtDet.setString(14,"");
											pstmtDet.setInt(15,0);
										}
										else
										{
											System.out.println("Updating Repelenishment Normal case and ["+replRefDeepId+"]refctr["+refCtr+"]");
											pstmtDet.setString(14,replRefDeepId);
											pstmtDet.setInt(15,refCtr);
										}
									}
									
									pstmtDet.executeUpdate();
									
									if(!locInvStat.equalsIgnoreCase(activePickInv))
									{
										updateReplOrdDet("I", itemCode, siteCode, locCode, lotNo, lotSl,actPkDeepLoc,(packSizeCase - quantity),replRefDeepId,String.valueOf(refCtr), conn);
									}
									itemVolumeTotal = itemVolumeTotal +  quantity*itemVolume;
									itemWeightTotal = itemWeightTotal + quantity*itemWeight;
									//updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"A-PICK", xtraParams, conn,itemWeightTotal,itemVolumeTotal,pickType);
								}
								
						}
						
						//////////////////////To add Carton no generation for Actives Hear///////////////////////////////////////
						System.out.println("Finally ["+itemWeightTotal+"]Finally itemVolumeTotal["+itemVolumeTotal+"]");
						updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"A-PICK", xtraParams, conn,itemWeightTotal,itemVolumeTotal,pickType,"");
						//Changed by Rohan on 24/11/12 to spilt active pick depending upon cartons.start
						cartonCount++;
						System.out.println("cartonCount:::"+cartonCount+"Active pick case count::"+Integer.parseInt(actPkCnt));
						if(cartonCount == Integer.parseInt(actPkCnt))
						{
							System.out.println("Creating new pick header");
							isActivePickHdr = false;
							cartonCount = 0;
							pickCtr = 1;
						}
						//Changed by Rohan on 24/11/12 to spilt active pick depending upon cartons.end
					}
						
				}
				

				if( rSet != null )
				{
					rSet.close();
					rSet = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				
				if( pstmtDet != null )
				{
					pstmtDet.close();
					pstmtDet = null;
				}
				if( pstmtRplDet != null )
				{
					pstmtRplDet.close();
					pstmtRplDet = null;
				}
				if(pstmtRplHdr != null)
				{
					pstmtRplHdr.close();
					pstmtRplHdr = null;
				}
				
				if(pstmtRplStk != null)
				{
					pstmtRplStk.close();
					pstmtRplStk = null;
					
				}	
				if(pstmtUpdWave != null)
				{
					pstmtUpdWave.close();
					pstmtUpdWave = null;
				
				}
				if(pstmtPickHdr != null)
				{
					pstmtPickHdr.close();
					pstmtPickHdr = null;
				
				}
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		finally
		{			
			try
			{
				if(rSet != null)
				{
					rSet.close();
					rSet = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if(pstmtLoc != null)
				{
					pstmtLoc.close();
					pstmtLoc = null;
				}
				if(rsLoc != null)
				{
					rsLoc.close();
					rsLoc = null;
				}
				
				if(pstmtUpdWave != null)
				{
					pstmtUpdWave = null;
					pstmtUpdWave.close();
				}
				if(pstmtPickHdr != null)
				{
					pstmtPickHdr = null;
					pstmtPickHdr.close();
				}
			}
			catch(Exception e)
			{
				throw e;		
			}
		}
		
		return errString;	
	}	
	//Changed by sumit sarkar on 26/08/2011 [ WM1ESUN006 ] update pick_ord_hrd & pick_ord_det table end.
	
	//Changed By Pragyan 21/02/12 To add item code for case pick cartons
	//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$-PICKING LOGIC CHANGE
	//Added new method by Chandni on 06/06/12 -- To generate carton Master when pick order is generated
	//private String updateCartonMaster(String pickOrder,int lineNo,Double noArt,String ptcn,String refSeries,String xtraParams,String masterCartonNo,Connection conn)throws Exception
	private String updateCartonMaster(String pickOrder,int lineNo,Double noArt,String ptcn,String refSeries,String xtraParams,String masterCartonNo,String itemCode,Connection conn)throws Exception
	{
		String errString = "";		
		String sql = "",sqlInsert = "";
		PreparedStatement pstmt = null,pstmtInsert = null;
		ResultSet rs = null;
		String chgUser="",chgTerm="",windowName="",keyString="",tranIDCol="",refSer="";
		String xmlString="",tranIDSer="";
		int updCnt[] = null;
		String crtnType = "";
		String cartonNumber="";
		
		try
		{
			System.out.println("***********************Chandni:Inside  method****************************");
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId");
			System.out.println("Displaying input parameters::"+pickOrder+"::"+lineNo+"::"+noArt+"::");
			Timestamp currDate = new Timestamp(System.currentTimeMillis());
			
			windowName = "w_carton_no_gen";
			
			xmlString = "<?xml version=\"1.0\"?>\r\n<Root>\r\n<header>"+
            "\r\n</header><Detail1>"+
            "\r\n<carton_no></carton_no>"+
            "</Detail1></Root>";
			System.out.println("xmlString : : : : :"+xmlString);
			TransIDGenerator tg = new TransIDGenerator(xmlString,"BASE",CommonConstants.DB_NAME);
			
			sql = "SELECT KEY_STRING, TRAN_ID_COL,REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, windowName);
			rs = pstmt.executeQuery();
			if( rs.next() )
			{
				keyString = rs.getString( "KEY_STRING" );
				tranIDCol = rs.getString("TRAN_ID_COL");
				refSer = rs.getString("REF_SER");
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt =null;
			keyString = keyString.substring(keyString.indexOf(","));
			//Changed By Pragyan 21/02/12 To add item code for case pick cartons
			/*sqlInsert = "INSERT INTO CARTON_MASTER (CARTON_NO, STATUS, CHG_DATE, CHG_USER, CHG_TERM, " +
						"PICK_ORDER, LINE_NO__PICK ,PTCN,REF_SER,CARTON_TYPE,MASTER_CARTON) VALUES (?,?,?,?,?,?,?,?,?,?,?) ";*/
			sqlInsert = "INSERT INTO CARTON_MASTER (CARTON_NO, STATUS, CHG_DATE, CHG_USER, CHG_TERM, " +
			"PICK_ORDER, LINE_NO__PICK ,PTCN,REF_SER,CARTON_TYPE,MASTER_CARTON,ITEM_CODE) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) ";
			
			pstmtInsert = conn.prepareStatement(sqlInsert);
			if(refSeries.startsWith("C"))
			{
				//keyString = "CPK,"+keyString;
				crtnType = "C";
			}
			else if(refSeries.startsWith("A"))
			{
				//keyString = "APK,"+keyString;
				crtnType = "A";
			}
			else if(refSeries.startsWith("M-PICK"))
			{
				//keyString = "MPC,"+keyString;
				crtnType = "C";
			}
			else if(refSeries.startsWith("M-PACK"))
			{
				//keyString = "MPK,"+keyString;
				crtnType = "M";
			}
			else if(refSeries.startsWith("S-DOC"))
			{
				//keyString = "DOC,"+keyString;
				crtnType = "S";
			}
			else if(refSeries.startsWith("P-PICK"))
			{
				//keyString = "DOC,"+keyString;
				crtnType = "P";
			}
			
			for(int i=1; i<= noArt ;i++)
			{
				System.out.println("inside the for loopppp::::::::::");
				/*selectin Key_string, Ref_ser &trns_id_col from transetup Table*/
			
				/*xmlString = "<?xml version=\"1.0\"?>\r\n<Root>\r\n<header>"+
	            "\r\n</header><Detail1>"+
	            "\r\n<carton_no></carton_no>"+
	            "</Detail1></Root>";
				System.out.println("xmlString : : : : :"+xmlString);
				TransIDGenerator tg = new TransIDGenerator(xmlString,"BASE",CommonConstants.DB_NAME);*/
				
				
				tranIDSer = tg.generateTranSeqID(refSer, tranIDCol, keyString, conn);
				cartonNumber = getSSCC("", Integer.parseInt(tranIDSer), conn);
				System.out.println("Generated Key :: "+tranIDSer);
				if (tranIDSer.indexOf("ERROR") > -1 )
				{
					errString = itmDBAccessEJB.getErrorString("","VTTRANID","","",conn);
					return errString;
				}
			
				System.out.println(tranIDSer);
				//pstmtInsert.setString(1,tranIDSer);
				pstmtInsert.setString(1,cartonNumber);
				pstmtInsert.setString(2,"A");
				pstmtInsert.setTimestamp(3,currDate);
				pstmtInsert.setString(4,chgUser);
				pstmtInsert.setString(5,chgTerm);
				pstmtInsert.setString(6,pickOrder);
				pstmtInsert.setInt(7,lineNo);
				pstmtInsert.setString(8,ptcn);
				pstmtInsert.setString(9,refSeries);
				pstmtInsert.setString(10,crtnType);
				if(refSeries.startsWith("P-PICK"))
				{
					//Changed By Pragyan 05/03/13 to set blank for parcel pick master carton clients requirement
					//pstmtInsert.setString(11,cartonNumber);
					pstmtInsert.setString(11,"");
				}
				else
				{
					pstmtInsert.setString(11,masterCartonNo);
				}
				
				pstmtInsert.setString(12,itemCode);
				
				
				pstmtInsert.addBatch();
				pstmtInsert.clearParameters();
						
			}// end of for loop
			
			updCnt = pstmtInsert.executeBatch();
			pstmtInsert.clearBatch();
			System.out.println(":ROWS INSERTED:["+updCnt.length+"]");
			if(pstmtInsert != null)
			{
				pstmtInsert.close();
				pstmtInsert = null;
			}
			//CHANGED BY PRAGYAN 12-JUL-12 TO CHANGE COMMIT.start
			/*if ( updCnt.length > 0 )
			{
				conn.commit();
				AppConnectParm appConnect = new AppConnectParm();
				InitialContext ctx = null;
				ctx = new InitialContext(appConnect.getProperty());
				ITMDBAccessLocal itmDBAccessLocal = new ITMDBAccessEJB();
				errString = itmDBAccessLocal.getErrorString("","PRCSUCCESS","");
			}*/
			//CHANGED BY PRAGYAN 12-JUL-12 FOR TO CHANGE COMMIT.end
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		finally
		{			
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if(pstmtInsert != null)
				{
					pstmtInsert.close();
					pstmtInsert = null;
				}
			}
			catch(Exception e)
			{
				throw new Exception();		
			}
		}
		
		return errString;
	}
	//Changed by Ameya of 07/08/2012 updateCartonMaster 
	private String updateCartonMaster(String pickOrder,int lineNo,Double noArt,String ptcn,String refSeries,String xtraParams,Connection conn,double weight,double volume, String packType,String itemCode)throws Exception
	{
		String errString = "";		
		String sql = "",sqlInsert = "";
		PreparedStatement pstmt = null,pstmtInsert = null,pstmtPacking = null;
		ResultSet rs = null;
		String chgUser="",chgTerm="",windowName="",keyString="",tranIDCol="",refSer="";
		String xmlString="",tranIDSer="";
		int updCnt[] = null;
		String crtnType = "";
		double volumeItem=0.0;
		double weightItem=0.0;
		String packCode="";
		String cartonNumber="";
		
		
		try
		{
			System.out.println("***********************Ameya:Inside updateCartonMaster method****************************");
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId");
			System.out.println("Displaying input parameters::"+pickOrder+"::"+lineNo+"::"+noArt+"::");
			Timestamp currDate = new Timestamp(System.currentTimeMillis());
			
			windowName = "w_carton_no_gen";	
			xmlString = "<?xml version=\"1.0\"?>\r\n<Root>\r\n<header>"+
            "\r\n</header><Detail1>"+
            "\r\n<carton_no></carton_no>"+
            "</Detail1></Root>";
			System.out.println("xmlString : : : : :"+xmlString);
			TransIDGenerator tg = new TransIDGenerator(xmlString,"BASE",CommonConstants.DB_NAME);
			
			//Changed by Ameya on 14/08/2012 updateCartonMaster for changing the query [START]
			
			/*sql = "SELECT PACK_CODE,GROSS_WEIGHT,LENGTH*WIDTH*HEIGHT "+
		 	"FROM PACKING WHERE pack_code not in(select pack_code from carton_master where pack_code is not null) and " +
		 	"GROSS_WEIGHT= ( SELECT MIN(GROSS_WEIGHT) " +
		 	"FROM PACKING WHERE pack_code not in(select pack_code from carton_master where pack_code is not null) and " +
		 	"LENGTH*WIDTH*HEIGHT =(SELECT MIN(LENGTH*WIDTH*HEIGHT) "+ 
		 	"VOLUME FROM PACKING WHERE pack_code not in(select pack_code from carton_master where pack_code is not null) and " +
		 	"GROSS_WEIGHT>=? AND LENGTH*WIDTH*HEIGHT>=?) )";*/
			
			/*sql = "SELECT PACK_CODE,GROSS_WEIGHT,LENGTH*WIDTH*HEIGHT "+
		 	"FROM PACKING WHERE " +
		 	"GROSS_WEIGHT= ( SELECT MIN(GROSS_WEIGHT) " +
		 	"FROM PACKING WHERE " +
		 	"LENGTH*WIDTH*HEIGHT =(SELECT MIN(LENGTH*WIDTH*HEIGHT) "+ 
		 	"VOLUME FROM PACKING WHERE " +
		 	"GROSS_WEIGHT>=? AND LENGTH*WIDTH*HEIGHT>=? AND PACK_TYPE IN(?,'P') ) AND PACK_TYPE IN(?,'P')  ) AND PACK_TYPE IN(?,'P')";
		 	*/
			
			sql = "SELECT PACK_CODE,GROSS_WEIGHT,LENGTH*WIDTH*HEIGHT "+
		 	"FROM PACKING WHERE " +
		 	"LENGTH*WIDTH*HEIGHT>=? and "+
		 	"GROSS_WEIGHT= ( SELECT MIN(GROSS_WEIGHT) " +
		 	"FROM PACKING WHERE " +
		 	"LENGTH*WIDTH*HEIGHT =(SELECT MIN(LENGTH*WIDTH*HEIGHT) "+ 
		 	"VOLUME FROM PACKING WHERE " +
		 	"GROSS_WEIGHT>=? AND LENGTH*WIDTH*HEIGHT>=? AND PACK_TYPE IN(?,'B') ) AND PACK_TYPE IN(?,'B')  ) AND PACK_TYPE IN(?,'B') "+
		 	"ORDER BY LENGTH*WIDTH*HEIGHT";
			
			
			pstmtPacking = conn.prepareStatement(sql);
			
			/*
			pstmtPacking.setDouble(1, weight);
			pstmtPacking.setDouble(2, volume);
			pstmtPacking.setString(3, packType);
			pstmtPacking.setString(4, packType);
			pstmtPacking.setString(5, packType);
			*/
			
			pstmtPacking.setDouble(1, volume);
			pstmtPacking.setDouble(2, weight);
			pstmtPacking.setDouble(3, volume);
			pstmtPacking.setString(4, packType);
			pstmtPacking.setString(5, packType);
			pstmtPacking.setString(6, packType);
			
			//Changed by Ameya on 14/08/2012 updateCartonMaster for changing the query [END]
			
			rs = pstmtPacking.executeQuery();
			if(rs.next())
			{
				packCode = rs.getString(1);
				weightItem = rs.getDouble(2);
				volumeItem = rs.getDouble(3);
			}
			
			System.out.println("packCode="+packCode);
			System.out.println("weightItem="+weightItem);
			System.out.println("volumeItem="+volumeItem);
			
			if(pstmtPacking != null)
			{
				pstmtPacking.close();
				pstmtPacking =null;
			}
			
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			
			
			sql = "SELECT KEY_STRING, TRAN_ID_COL,REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, windowName);
			rs = pstmt.executeQuery();
			if( rs.next() )
			{
				keyString = rs.getString( "KEY_STRING" );
				tranIDCol = rs.getString("TRAN_ID_COL");
				refSer = rs.getString("REF_SER");
			}
			if(pstmt != null)
			{
				pstmt.close();
				pstmt =null;
			}
			
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			keyString = keyString.substring(keyString.indexOf(","));
			//Changed By Pragyan 21/02/12 To add item code for case pick cartons
			/*sqlInsert = "INSERT INTO CARTON_MASTER (CARTON_NO, STATUS, CHG_DATE, CHG_USER, CHG_TERM, " +
			"PICK_ORDER, LINE_NO__PICK ,PTCN,REF_SER,CARTON_TYPE,PACK_CODE,MASTER_CARTON) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) ";*/
			sqlInsert = "INSERT INTO CARTON_MASTER (CARTON_NO, STATUS, CHG_DATE, CHG_USER, CHG_TERM, " +
			"PICK_ORDER, LINE_NO__PICK ,PTCN,REF_SER,CARTON_TYPE,PACK_CODE,MASTER_CARTON,ITEM_CODE) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?) ";
			
			pstmtInsert = conn.prepareStatement(sqlInsert);
			if(refSeries.startsWith("C"))
			{
				//Changed by Ameya on 11/08/2012 for M-PACK Start.
				//keyString = "CPK,"+keyString;
				//Changed by Ameya of 11/08/2012 for M-PACK End.
				crtnType = "C";
			}
			else if(refSeries.startsWith("A"))
			{
				//Changed by Ameya on 11/08/2012 for M-PACK Start.
				//keyString = "APK,"+keyString;
				//Changed by Ameya of 11/08/2012 for M-PACK End.
				crtnType = "A";
			}
			else if(refSeries.startsWith("M-PICK"))
			{
				//Changed by Ameya on 11/08/2012 for M-PACK Start.
				//keyString = "MPC,"+keyString;
				//Changed by Ameya of 11/08/2012 for M-PACK End.
				crtnType = "C";
			}
			else if(refSeries.startsWith("M-PACK"))
			{
				//Changed by Ameya on 11/08/2012 for M-PACK Start.
				//keyString = "MPK,"+keyString;
				//Changed by Ameya of 11/08/2012 for M-PACK End.
				crtnType = "M";
			}
			else if(refSeries.startsWith("S-DOC"))
			{
				//Changed by Ameya on 11/08/2012 for M-PACK Start.
				//keyString = "DOC,"+keyString;
				//Changed by Ameya of 11/08/2012 for M-PACK End.
				crtnType = "S";
			}
			
			for(int i=1; i<= noArt ;i++)
			{
				System.out.println("inside the for loopppp::::::::::");
				/*selectin Key_string, Ref_ser &trns_id_col from transetup Table*/
			
				/*xmlString = "<?xml version=\"1.0\"?>\r\n<Root>\r\n<header>"+
	            "\r\n</header><Detail1>"+
	            "\r\n<carton_no></carton_no>"+
	            "</Detail1></Root>";
				System.out.println("xmlString : : : : :"+xmlString);
				TransIDGenerator tg = new TransIDGenerator(xmlString,"BASE",CommonConstants.DB_NAME);*/
				
				
				tranIDSer = tg.generateTranSeqID(refSer, tranIDCol, keyString, conn);
				System.out.println("tranIDSer="+tranIDSer);
				cartonNumber = getSSCC("", Integer.parseInt(tranIDSer), conn);
				System.out.println("Generated Key :: "+tranIDSer);
				if (tranIDSer.indexOf("ERROR") > -1 )
				{
					errString = itmDBAccessEJB.getErrorString("","VTTRANID","","",conn);
				}
			
				System.out.println(tranIDSer);
				//Changed by Ameya on 11/08/2012 for M-PACK Start.
				System.out.println(cartonNumber);
				pstmtInsert.setString(1,cartonNumber);
				//pstmtInsert.setString(1,tranIDSer);
				//Changed by Ameya on 11/08/2012 for M-PACK End.
				pstmtInsert.setString(2,"A");
				pstmtInsert.setTimestamp(3,currDate);
				pstmtInsert.setString(4,chgUser);
				pstmtInsert.setString(5,chgTerm);
				pstmtInsert.setString(6,pickOrder);
				pstmtInsert.setInt(7,lineNo);
				pstmtInsert.setString(8,ptcn);
				pstmtInsert.setString(9,refSeries);
				pstmtInsert.setString(10,crtnType);
				pstmtInsert.setString(11,packCode);
				if((refSeries.startsWith("M-PACK")))
				{
					pstmtInsert.setString(12,cartonNumber);
				}
				else
				{
					pstmtInsert.setString(12,"");
				}
				
				pstmtInsert.setString(13,itemCode);
				
				pstmtInsert.addBatch();
				pstmtInsert.clearParameters();
						
				System.out.println("packCode="+packCode);
				System.out.println("weightItem="+weightItem);
				System.out.println("volumeItem="+volumeItem);
				
			}// end of for loop
			
			updCnt = pstmtInsert.executeBatch();
			pstmtInsert.clearBatch();
			System.out.println(":ROWS INSERTED:["+updCnt.length+"]");
			
			if(pstmtInsert != null)
			{
				pstmtInsert.close();
				pstmtInsert = null;
			}
			
			if(errString == "" && errString.length() <= 0)
			{
				errString = cartonNumber;
				
				if("A".equalsIgnoreCase(crtnType))
				{
					updateActivePackingCarton(pickOrder, lineNo, cartonNumber, packCode, conn);
				}
			}
		
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		finally
		{			
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if(pstmtInsert != null)
				{
					pstmtInsert.close();
					pstmtInsert = null;
				}
				if(pstmtPacking != null)
				{
					pstmtPacking.close();
					pstmtPacking =null;
				}
				
				if(errString != null && errString.indexOf("ERROR") != -1)
				{
					throw new Exception();		
				}
				
			}
			catch(Exception e)
			{
				throw new Exception();		
			}
		}
		
		return errString;
	}
	//Changed by Ameya of 07/08/2012 updateCartonMaster
	//Changed by Ameya on 11/08/2012 to generate carton number [START].
	// 02/08/12 manoharan following method added to generate SSCC18 complaint number
	private String getSSCC(String mfgCode, int runNumber, Connection conn) throws Exception 
	{
		boolean isOdd = false;
		int sumOdd = 0, sumEven = 0;
		String inputStr = "", sscc18 = "",  runNumberStr =""; //mfgCode = "0351672",
		//ibase.utility.GenericUtility genUtility = ibase.utility.GenericUtility.getInstance();
		int ctr, curDigit = 0, chkDigit = 0, padLen = 0; // runNumber = 4967235
		try
		{
			if (mfgCode == null || mfgCode.length() <= 0) 
			{
				mfgCode = "04";
			}
			sumOdd = 0;
			sumEven = 0;
			padLen = 16 - mfgCode.length(); // total length should be 16 excluding extension digit and check digit
			
			runNumberStr = "0000000000000000" + String.valueOf(runNumber);
			
			runNumberStr = runNumberStr.substring(runNumberStr.length() - padLen ,runNumberStr.length()); 
			inputStr = mfgCode + runNumberStr;
			
			System.out.println(  " inputStr [" + inputStr + "] inputStr.length() [" +  inputStr.length() + "]" );
			for (int pos = inputStr.length() - 1; pos >= 0 ; pos--)
			{
				
				curDigit = Integer.parseInt(inputStr.substring(pos,pos+1));
				System.out.println(  " pos [" + pos +"] curDigit [" + curDigit + "]" );
				if  ( (pos % 2) == 0)
				{
					sumEven +=  curDigit;
				}
				else
				{
					sumOdd += curDigit;
				}
				
			}
			// step 1  - multiple odd sum with 3
			sumOdd = sumOdd * 3;
			chkDigit =  10 - ((sumEven + sumOdd) % 10) ;
			
			if(chkDigit > 9)
			{
				chkDigit = 0;
			}
			//System.out.println(  " Integer(chkDigit).toString() [" + String.valueOf(chkDigit) +"]" );
			//sscc18 = 
			sscc18 ="0" + inputStr + String.valueOf(chkDigit);
			System.out.println(" chkDigit [" + chkDigit + "] sumOdd [" + sumOdd + "] sumEven [" + sumEven + "] inputStr [" + inputStr + "] sscc18 [" + sscc18 +"]" );
			
				
		}
		catch(Exception e){
		throw e;
		}
		return sscc18;
	}
	//Changed by Ameya on 11/08/2012 to generate carton number [END].
	//Changed by Ameya on 11/08/2012 to calculate the total weight & total volume for cases [START].
	private HashMap getWeightVolumeMap(double totalWeight, int totalNoArt, double masterPackCount, double masterPackWeight, String itemCode, String lotNo, Connection conn ) throws Exception
	{
		double weightOfmasterPackCount = 0.0;
		double countCasesOfmasterPackWeight = 0.0;
		double caseWeightTotal = 0.0;
		double caseVolumeTotal = 0.0;
		double caseVolume = 0.0;
		
		//Changed by Ameya on 13/08/2012 for M-Pack
		int countCasesOfmasterPackWeightInt = 0;
		
		HashMap mapWeightVolume = null;
		try
		{
			mapWeightVolume = new HashMap();
			weightOfmasterPackCount = (int)Math.ceil((totalWeight/(double)totalNoArt)*masterPackCount);
			countCasesOfmasterPackWeight = (int)Math.ceil(((double)totalNoArt/totalWeight)*masterPackWeight);
			countCasesOfmasterPackWeightInt = (int)countCasesOfmasterPackWeight;
			System.out.println("weightOfmasterPackCount="+weightOfmasterPackCount);
			System.out.println("countCasesOfmasterPackWeight="+countCasesOfmasterPackWeight);
			if(totalWeight>masterPackWeight || totalNoArt>masterPackCount)
			{
				System.out.println("MasterPacks > 1");
				//totalWeight=totalWeight-masterPackWeight;
				if(weightOfmasterPackCount>masterPackWeight)
				{
					//Changed by Ameya on 13/08/2012 to calculate caseWeightTotal for M-Pack Start.
					//caseWeightTotal=masterPackWeight;									
					caseWeightTotal = ((double)(countCasesOfmasterPackWeightInt)/countCasesOfmasterPackWeight)*masterPackWeight;
					//Changed by Ameya on 13/08/2012 to calculate caseWeightTotal for M-Pack End.
					
					caseVolume = Math.floor((Double)getItemVoumeMap(itemCode, lotNo, conn).get("LOT_SIZE"));
					//Changed by Ameya on 13/08/2012 to calculate caseWeightTotal for M-Pack Start.
					//caseVolumeTotal = countCasesOfmasterPackWeight*caseVolume;	
					caseVolumeTotal = countCasesOfmasterPackWeightInt*caseVolume;	
					//totalWeight=totalWeight-masterPackWeight;
					totalWeight = totalWeight-caseWeightTotal;
					//Changed by Ameya on 13/08/2012 to calculate caseWeightTotal for M-Pack End.
					totalNoArt = totalNoArt-(int)countCasesOfmasterPackWeight;
				}
				else
				{
					caseWeightTotal = weightOfmasterPackCount;
					caseVolume = Math.floor((Double)getItemVoumeMap(itemCode, lotNo, conn).get("LOT_SIZE"));
					caseVolumeTotal = masterPackCount*caseVolume;
					totalNoArt = totalNoArt-(int)masterPackCount;
					totalWeight = totalWeight-weightOfmasterPackCount;
				}
			}
			else
			{
				System.out.println("Only 1 MasterPack");
				caseWeightTotal = totalWeight;
				caseVolume = Math.floor((Double)getItemVoumeMap(itemCode, lotNo, conn).get("LOT_SIZE"));
				caseVolumeTotal = totalNoArt*caseVolume;
			}
			System.out.println("caseWeightTotal="+caseWeightTotal);
			System.out.println("caseVolumeTotal="+caseVolumeTotal);
			
			mapWeightVolume.put("CASES_WEIGHT", caseWeightTotal);
			mapWeightVolume.put("CASES_VOLUME", caseVolumeTotal);
			//Changed by Ameya on 13/08/2012 to put in map for M-Pack Start.
			mapWeightVolume.put("TOTAL_WEIGHT", totalWeight);
			mapWeightVolume.put("TOTAL_ARTS", totalNoArt);
			//Changed by Ameya on 13/08/2012 to put in map for M-Pack End.
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		return mapWeightVolume;
		// changed by Ameya on 08-08-2012 for M-PACK End.		
	}
	//Changed by Ameya on 11/08/2012 to calculate the total weight & total volume for cases [END].
	//Changed by sumit sarkar on 28/08/2011 [ WM1ESUN006 ] update pack_hdr & pack_det table start.
	private String updatePacking(String waveID,String saleOrder,String refID,String pickOrder,String PTCN,String xtraParams, Connection conn)throws Exception
	{
		String errString = "";
		String sql = "";
		String confirm ="N", chgTerm = "", chgUser = "";
		java.sql.Date confDate = new java.sql.Date( System.currentTimeMillis());
		java.sql.Date tranDate = new java.sql.Date( System.currentTimeMillis());
		
		PreparedStatement pstmt = null;
		//ResultSet rSet = null ;	    
        
		try
		{			
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId");
	
			sql = "INSERT INTO PACK_HDR(TRAN_ID, TRAN_DATE, SITE_CODE, " +
					" SALE_ORDER, WAVE_ID, CONFIRMED, CONF_DATE, CHG_USER, CHG_DATE, CHG_TERM,PICK_ORDER,PTCN) " +
					" VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
			
			pstmt = conn.prepareStatement(sql);			
			pstmt.setString(1, refID);
			pstmt.setDate(2, tranDate );
			pstmt.setString(3, siteCode);
			pstmt.setString(4, saleOrder);
			pstmt.setString(5, waveID);
			pstmt.setString(6, confirm);
			pstmt.setDate(7, confDate );
			pstmt.setString(8,chgUser);
			pstmt.setDate(9,tranDate);
			pstmt.setString(10,chgTerm);
			pstmt.setString(11,pickOrder);
			pstmt.setString(12,PTCN);
			
			pstmt.executeUpdate();
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		finally
		{
			
			try
			{
				/*if(rSet != null)
				{
					rSet.close();
					rSet = null;
				}	*/
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}	
			}
			catch(Exception e)
			{
				e.printStackTrace();
				throw e;
			}
		}	
		return errString;
	}
	//Changed by sumit sarkar on 28/08/2011 [ WM1ESUN006 ] update pack_hdr & pack_det table end.
	
	//Changed by sumit sarkar on 8/18/2011 [ WM1ESUN006 ] update despatch table start.
	private String updateShipment(Document headerDom, Document detailDom,String waveID,String saleOrder,String refId,String tranCode,String transMode,String xtraParams,  Connection conn)throws Exception
	{
			String errString = "";			
			String insertSql = "";			
			java.sql.Timestamp sordDate = null;
			java.sql.Timestamp despDate = null;
			String custCode = "";
			String custCodeDlv = "";
			String dlvAdd1 = "";
			String dlvAdd2 = "";			
			//String transMode = "";
			String stanCode = "";
			String confirmed = "";
			java.sql.Timestamp confDate = null;
			String status = "";
			String dlvAdd3 = "";
			String stateCodeDlv = "", countCodeDlv = "";
			String exchRate = "";	
						
			PreparedStatement pstmt = null;
			ResultSet rSet = null ;
			
			String  chgUser = "", chgTerm = "";
			java.sql.Date currDate  = new java.sql.Date(System.currentTimeMillis());
			java.sql.Timestamp currDate1  = new java.sql.Timestamp(System.currentTimeMillis());
			
			//Changes made by gulzar on 12/28/2011
			String dbDateFormat = genericUtility.getDBDateFormat();
			String applDateFormat = genericUtility.getApplDateFormat();
			SimpleDateFormat sdf = new SimpleDateFormat(applDateFormat);
			
			String currDateStr = sdf.format(currDate);

			java.sql.Timestamp effDate = java.sql.Timestamp.valueOf(genericUtility.getValidDateString( currDateStr , applDateFormat, dbDateFormat ) + " 00:00:00.0") ;

			String dlvCity = "";
			String dlvPin = "";
			//String tranCode = "";
			String currCodeFrt = "";
			String currCodeIns = "";
			String currCode = "";

			double exchRateFrt = 0d;
			double frtAmt = 0d;
			double insAmt = 0d;
			double exchRateIns = 0d;

			//End changes by gulzar on 12/28/2011
						
			try
			{			
				
				chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");
				chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId");
				
				/*--Commented and changes below by gulzar on 12/28/2011
				String sql = " SELECT SORDER.PORD_DATE, SORDER.SITE_CODE, SORDER.SALE_ORDER, " +
						"SORDER.ORDER_DATE, SORDER.CUST_CODE,SORDER.CUST_CODE__DLV, " +
						"SORDER.DLV_ADD1,SORDER.DLV_ADD2,SORDER.COUNT_CODE__DLV, " +
						"SORDER.TRANS_MODE, SORDER.STAN_CODE, SORDER.CONFIRMED, " +
						"SORDER.CONF_DATE, SORDER.STATUS,SORDER.DLV_ADD3,SORDER.STATE_CODE__DLV, " +
						"SORDER.EXCH_RATE, WAVE_TASK_DET.WAVE_ID FROM SORDER, WAVE_TASK_DET " +
						"WHERE SORDER.SALE_ORDER = ? AND WAVE_TASK_DET.WAVE_ID = ?";
				
				*/
				//Changed By Rohan
				//String sql = "SELECT SORDER.PORD_DATE, SORDER.SITE_CODE, SORDER.SALE_ORDER, " +
				String sql = "SELECT SORDER.PORD_DATE, SORDER.SITE_CODE__SHIP, SORDER.SALE_ORDER, " +
							"SORDER.ORDER_DATE, SORDER.CUST_CODE,SORDER.CUST_CODE__DLV, " +
							"SORDER.DLV_ADD1,SORDER.DLV_ADD2,SORDER.COUNT_CODE__DLV, " +
							"SORDER.TRANS_MODE, SORDER.STAN_CODE, SORDER.CONFIRMED, " +
							"SORDER.CONF_DATE, SORDER.STATUS,SORDER.DLV_ADD3,SORDER.STATE_CODE__DLV, " +
							"SORDER.EXCH_RATE, WAVE_TASK_DET.WAVE_ID, SORDER.DLV_CITY, SORDER.DLV_PIN, SORDER.TRAN_CODE, "+
							"SORDER.CURR_CODE__FRT, SORDER.EXCH_RATE__FRT, SORDER.FRT_AMT, SORDER.CURR_CODE__INS, "+
							"SORDER.EXCH_RATE__INS, SORDER.INS_AMT, SORDER.CURR_CODE  " +
							"FROM SORDER, WAVE_TASK_DET " +
							"WHERE SORDER.SALE_ORDER = ? AND WAVE_TASK_DET.WAVE_ID = ?";

				//End changes by gulzar on 12/28/2011

				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,saleOrder);
				pstmt.setString(2,waveID);
				rSet = pstmt.executeQuery();
				
				if (rSet.next())
				{
					despDate = rSet.getTimestamp(1);
					siteCode = rSet.getString(2);
					sordDate = rSet.getTimestamp(4);
					custCode = rSet.getString(5);
					custCodeDlv = rSet.getString(6);
					dlvAdd1 = rSet.getString(7);
					dlvAdd2 = rSet.getString(8);
					countCodeDlv = rSet.getString(9);
					//transMode = rSet.getString(10);
					stanCode = rSet.getString(11);
					confirmed = rSet.getString(12);
					confDate = rSet.getTimestamp(13);
					status = rSet.getString(14);
					dlvAdd3 = rSet.getString(15);
					stateCodeDlv = rSet.getString(16);
					exchRate = rSet.getString(17);

					//Changes made by gulzar on 12/28/2011
					dlvCity = rSet.getString("DLV_CITY");
					dlvPin = rSet.getString("DLV_PIN");
					//tranCode = rSet.getString("TRAN_CODE");
					currCodeFrt = rSet.getString("CURR_CODE__FRT");
					exchRateFrt = rSet.getDouble("EXCH_RATE__FRT");
					frtAmt = rSet.getDouble("FRT_AMT");
					currCodeIns = rSet.getString("CURR_CODE__INS");
					exchRateIns = rSet.getDouble("EXCH_RATE__INS");
					insAmt = rSet.getDouble("INS_AMT");
					currCode = rSet.getString("CURR_CODE");
					//end changes by gulzar on 12/28/2011
				}
				if( rSet != null )
				{
					rSet.close();
					rSet = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				/*--Commented and changes below by gulzar on 12/28/2011
				insertSql="INSERT INTO DESPATCH(DESP_ID,DESP_DATE, SITE_CODE, SORD_NO, SORD_DATE,"
						+"CUST_CODE, CUST_CODE__DLV, DLV_ADD1, DLV_ADD2, COUNT_CODE__DLV, "
						+"TRANS_MODE, STAN_CODE, CONFIRMED, STATUS,CHG_USER, CHG_DATE, CHG_TERM,"
						+"DLV_ADD3, STATE_CODE__DLV, EXCH_RATE, WAVE_ID) VALUES "
						+"(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				
				*/
				insertSql="INSERT INTO DESPATCH(DESP_ID,DESP_DATE, SITE_CODE, SORD_NO, SORD_DATE,"
						+ " CUST_CODE, CUST_CODE__DLV, DLV_ADD1, DLV_ADD2, COUNT_CODE__DLV, "
						+ " TRANS_MODE, STAN_CODE, CONFIRMED, STATUS, CHG_USER, CHG_DATE, CHG_TERM,"
						+ " DLV_ADD3, STATE_CODE__DLV, EXCH_RATE, WAVE_ID, EFF_DATE, DLV_CITY, DLV_PIN, TRAN_CODE, "
						+ " CURR_CODE__FRT, EXCH_RATE__FRT, FREIGHT, CURR_CODE__INS, EXCH_RATE__INS, INSURANCE, CURR_CODE,GP_NO )"
						+ " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				//End changes by gulzar on 12/28/2011
				
				pstmt = conn.prepareStatement(insertSql);
				
				System.out.println("desp id "+refId);
				System.out.println("desp date "+despDate);
				System.out.println("site code "+siteCode);
				System.out.println("sord no "+saleOrder);
				System.out.println("sord date "+sordDate);
				System.out.println("cust code "+custCode);
				System.out.println("cust code dlv "+custCodeDlv);
				System.out.println("dlv add1 "+dlvAdd1);
				System.out.println("dlv add2 "+dlvAdd2);
				System.out.println("count code dlv "+countCodeDlv);
				System.out.println("trans mode "+transMode);
				System.out.println("stan code "+stanCode);
				//System.out.println("confirmed "+confirmed);//Gulzar on 12/28/2011
				//System.out.println("conf date "+confDate);//Gulzar on 12/28/2011

				status = " ";//Gulzar on 12/28/2011
				System.out.println("status "+status);
				
				System.out.println("dlv add3 "+dlvAdd3);
				System.out.println("state code dlv "+stateCodeDlv);
				System.out.println("exch rate "+exchRate);
				
				pstmt.setString(1,refId);
				pstmt.setTimestamp(2, currDate1);
				pstmt.setString(3,siteCode);
				pstmt.setString(4,saleOrder);
				pstmt.setTimestamp(5, sordDate );
				pstmt.setString(6,custCode);
				pstmt.setString(7,custCodeDlv);
				pstmt.setString(8,dlvAdd1);
				pstmt.setString(9,dlvAdd2);
				pstmt.setString(10,countCodeDlv);
				pstmt.setString(11,transMode);
				pstmt.setString(12,stanCode);
				//pstmt.setString(13,confirmed);//Commented by Gulzar on  12/27/2011
				pstmt.setString(13,"N");//Added changes by Gulzar on  12/27/2011
				//pstmt.setTimestamp(14, confDate);//Commented by gulzar on 12/27/2011
				pstmt.setString(14,status);
				pstmt.setString(15,chgUser);
				pstmt.setTimestamp(16,currDate1);
				pstmt.setString(17,chgTerm);
				pstmt.setString(18,dlvAdd3);
				pstmt.setString(19,stateCodeDlv);
				pstmt.setString(20,exchRate);
				pstmt.setString(21,waveID);

				//Changes made by gulzar on 12/28/2011
				pstmt.setTimestamp(22,effDate);
				pstmt.setString(23,dlvCity);
				pstmt.setString(24,dlvPin);
				pstmt.setString(25,tranCode);
				pstmt.setString(26,currCodeFrt);
				pstmt.setDouble(27,exchRateFrt);
				pstmt.setDouble(28,frtAmt);
				pstmt.setString(29,currCodeIns);
				pstmt.setDouble(30,exchRateIns);
				pstmt.setDouble(31,insAmt);
				pstmt.setString(32,currCode);
				//Changed By Pragyan according to manohran sir as in future it will change .
				pstmt.setString(33,"G");
				//End changes by gulzar on 12/28/2011
				
				pstmt.executeUpdate();
				pstmt.clearParameters();
				System.out.println("insertion of sql inside updateShipment is success ");				
				
				if(pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				System.out.println("Exception :updateShipment :"  + insertSql + "\n" +e.getMessage());
				e.printStackTrace();
				throw e;
			}
			finally
			{				
				try
				{
					if( rSet != null)
					{
						rSet.close();
						rSet = null;
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
				}
				catch(Exception e)
				{
					e.printStackTrace();	
					throw e;
				}	
			}		
			return errString;
	}
	//Changed by sumit sarkar on 18/08/2011 [ WM1ESUN006 ] update despatch table end.
	private String getRefSer(String winName, Connection conn) throws ITMException
	{
		String cRefSer = "";
		String sql = "";		
		ResultSet rSet = null ;
		PreparedStatement pstmt = null;
		try
		{	
			
			sql = "SELECT REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, winName);
			rSet = pstmt.executeQuery();
			
			if (rSet.next())
			{
				cRefSer = checkNull( rSet.getString("REF_SER"));
			}			
					
		}
		catch(Exception se)
		{
			System.out.println("SQLException :" + se);
			se.printStackTrace();
		}
		finally
		{
			try
			{	
				if(rSet != null)
				{
					rSet.close();
					rSet = null;
				}	
				if(pstmt != null)
				{
					pstmt.close();
					pstmt=null;
				}					
			}
			catch(Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return cRefSer;
	}
	//Changed by sumit sarkar on 28/08/2011 [ WM1ESUN006 ] for creating ref_id end.
	
	//Changed by sumit sarkar on 28/08/2011 [ WM1ESUN006 ] for creating tran id start.
	private String getTranId(String windowName, Connection conn) throws ITMException
	{
		String keyStringQuery = "";
		String xmlValues = "";
		String tranId = "";	
		ResultSet rSet = null ;
		PreparedStatement pstmt = null;
		CommonConstants commonConstants = new CommonConstants();

		java.sql.Timestamp currDate = null;

		try
		{
			
			keyStringQuery = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ?";
	    	System.out.println("keyStringQuery--------->>"+keyStringQuery);
	    	
	    	pstmt = conn.prepareStatement(keyStringQuery);
	    	pstmt.setString(1,windowName);
	    	rSet = pstmt.executeQuery();	    	
			String tranSer1 = "";
			String keyString = "";
			String keyCol = "";
			if (rSet.next())
			{
				keyString = rSet.getString("KEY_STRING");
				keyCol = rSet.getString("TRAN_ID_COL");
				tranSer1 = rSet.getString("REF_SER");
			}
			//Changed by Gulzar on 5/12/2012
			/*
			String tokenField = "tran_date";
			String keyStrArr[] = keyString.split(",");
			int keyStrLen = keyStrArr.length;
			if ( keyStrLen > 0 )
			{
				String keyToken = "";
				for (int i = 0; i < keyStrLen; i++)
				{
					keyToken = keyStrArr[i];
					if ( keyToken.indexOf("_pp") > 0 )
					{
						tokenField = keyToken.substring( keyToken.length()-3 );
						break;
					}
				}
			}
			
			System.out.println("tokenField = ["+tokenField+"]");
			*/

			SimpleDateFormat sdfAppl = new SimpleDateFormat(genericUtility.getApplDateFormat());

			currDate = new java.sql.Timestamp(System.currentTimeMillis());
			String currDateStr = sdfAppl.format(currDate);
			//End Changes by Gulzar on 5/12/2012
			
			System.out.println("keyString :"+keyString);
			System.out.println("keyCol :"+keyCol);
			System.out.println("tranSer1 :"+tranSer1);
			xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
			xmlValues = xmlValues + "<Header></Header>";
			xmlValues = xmlValues + "<Detail1>";
			xmlValues = xmlValues +		"<tran_id></tran_id>";
			xmlValues = xmlValues +		"<site_code>" + siteCode + "</site_code>";
			xmlValues = xmlValues +		"<desp_date>" + currDateStr + "</desp_date>"; 
			xmlValues = xmlValues +		"<tran_date>" + currDateStr + "</tran_date>"; 
			xmlValues = xmlValues + "</Detail1></Root>";
			System.out.println("xmlValues  :["+xmlValues+"]");
			TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
			// Creating wave_id 
			tranId = tg.generateTranSeqID(tranSer1, keyCol, keyString, conn);
			
			if(rSet != null)
			{
				rSet.close();
				rSet=null;
			}	
			if(pstmt != null)
			{
				pstmt.close();
				pstmt=null;
			}			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{	
				if(rSet != null)
				{
					rSet.close();
					rSet=null;
				}	
				if(pstmt != null)
				{
					pstmt.close();
					pstmt=null;
				}				
			}
			catch(Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return checkNull( tranId);
	}	
	
	private String checkNull( String input )
	{
		if( input == null )
		{
			input = "";
		}
		return input;
	}
	//Changed by sumit sarkar on 28/08/2011 [ WM1ESUN006 ] for creating tran_id end.
	
	void cleanup()
	{
		itemCodeMap.clear();
	}
	
		
	private HashMap getItemVoumeMap(String itemCode,String lotNo,Connection con)throws Exception
	{
		double packSize = 0,itemSize = 0,lotSize = 0;
		PreparedStatement pstmt = null;
		//Changed By Pragyan 12/03/13 To set hazardous item check
		String sql="",hazardous = "";
		ResultSet rs = null;
		double itmLen = 0,itmWidth = 0,itmHeight = 0,itemWeight = 0,lotLen = 0 ,lotHeight = 0,lotWidth = 0,lotWeight = 0;
		HashMap dataVolumeMap = new HashMap();
		
		try {
			
			//Changed By Pragyan 12/03/13 To set hazardous item check
			//sql = "SELECT I.LENGTH ITEM_LEN,I.WIDTH ITEM_WID,I.HEIGHT ITEM_HEIGHT,I.GROSS_WEIGHT ITEM_WEIGHT,"
			sql = "SELECT I.LENGTH ITEM_LEN,I.WIDTH ITEM_WID,I.HEIGHT ITEM_HEIGHT,I.GROSS_WEIGHT ITEM_WEIGHT,I.HAZARDOUS HAZARD, "
				  +" L.LENGTH LITEM_LEN,L.WIDTH LITEM_WID,L.HEIGHT LITEM_HEIGHT,L.SHIPPER_SIZE SHIPSIZE,L.GROSS_WEIGHT LOT_WEIGHT FROM"
				  +" ITEM I,ITEM_LOT_PACKSIZE L"
				  +" WHERE I.ITEM_CODE = L.ITEM_CODE"
				  +" AND L.LOT_NO__FROM <= ? AND L.LOT_NO__TO >= ?"
				  +" AND  I.ITEM_CODE = ?";
				  
			
			pstmt = con.prepareStatement(sql);
			if(lotNo != null && lotNo.length() > 0)
			{
				pstmt.setString(1, lotNo);
				pstmt.setString(2, lotNo);
			}
			else
			{
				pstmt.setString(1, "00");
				pstmt.setString(2, "ZZ");
			}
			pstmt.setString(3, itemCode);
			rs = pstmt.executeQuery();
			
			if(rs.next())
			{
				itmLen = rs.getDouble("ITEM_LEN");
				itmWidth = rs.getDouble("ITEM_WID");
				itmHeight = rs.getDouble("ITEM_HEIGHT");
				itemWeight = rs.getDouble("ITEM_WEIGHT");
				//Changed By Pragyan 12/03/13 To set hazardous item check
				hazardous = rs.getString("HAZARD");
				lotLen = rs.getDouble("LITEM_LEN");
				lotWidth = rs.getDouble("LITEM_WID");
				lotHeight = rs.getDouble("LITEM_HEIGHT");				
				packSize = rs.getDouble("SHIPSIZE");				
				lotWeight = rs.getDouble("LOT_WEIGHT");				
			}
			
			//packSize = (lotHeight * lotWidth * lotLen)/(itmLen * itmWidth * itmHeight);
			/*itemSize = Math.floor(itmLen * itmWidth * itmHeight);
			lotSize = Math.floor((lotHeight * lotWidth * lotLen));*/
			itemSize = itmLen * itmWidth * itmHeight;
			lotSize = lotHeight * lotWidth * lotLen;
			
			dataVolumeMap.put("PACK_SIZE", packSize);
			dataVolumeMap.put("ITEM_SIZE", itemSize);
			dataVolumeMap.put("LOT_SIZE", lotSize);
			//Changed By Pragyan 12/03/13 To set hazardous item check
			dataVolumeMap.put("HAZARDOUS", hazardous);
			dataVolumeMap.put("ITEM_WEIGHT", itemWeight);
			dataVolumeMap.put("PACK_WEIGHT", lotWeight);
			
			
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
		
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
		
			}
			
			
			
		} catch (Exception e) {
			// TODO: handle exception

			throw e;
		}
		finally
		{
			try
			{
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
			
				}
				if(rs != null)
				{
					rs.close();
					rs = null;
			
				}
			}
			catch(Exception e)
			{
				throw e;
			}
		}
		
		return dataVolumeMap;
	}
	
	
	private int getWaveTaskDetLineNo(String waveID,Connection con)throws Exception
	{
		int lastLineNo = 0;
		PreparedStatement pstmt = null;
		String sql="";
		ResultSet rs = null;
		
		try {
			sql = "SELECT MAX(LINE_NO) FROM WAVE_TASK_DET WHERE WAVE_ID=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, waveID);
			rs = pstmt.executeQuery();
			
			if(rs.next())
			{
				lastLineNo = rs.getInt(1);
			}
			/*for(;;)
			{	
			break;
			}	*/		
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
		
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
		
			}
		} catch (Exception e){
			// TODO: handle exception
			throw e;
		}
		finally
		{
			try
			{
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
			
				}
				if(rs != null)
				{
					rs.close();
					rs = null;
			
				}
			}
			catch (Exception e)
			{
				throw e;
			}

		}
		
		return lastLineNo;
	}
		
	//Changed by Rohan on 3-12-11 [WM1ESUN006] To Check master Pack allow.start
	private boolean isMasterPackAllow(String saleOrder,String customerCode ,String tranCode,Connection conn) throws ITMException
	{
		
		//String sql = "";
		String sqlCustTran = "";
		ResultSet rSet = null;
		//Connection conn = null;
		PreparedStatement pstmt = null;
		/*String tranCode = "";
		String customerCode = "";*/
		String custMasterPack = "";
		String tranMasterPack = "";
		boolean masterPack = false;
		
		try
		{
			/*sql = "SELECT TRAN_CODE,CUST_CODE FROM SORDER WHERE SALE_ORDER= ?" ;
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,saleOrder);
			rSet = pstmt.executeQuery();
			if( rSet.next())
			{
				tranCode = checkNull(rSet.getString("TRAN_CODE"));
				customerCode = checkNull(rSet.getString("CUST_CODE"));		
			}
			
			rSet.close();
			rSet = null;
			
			pstmt.close();
			pstmt = null;
			*/
			sqlCustTran = "SELECT C.MASTER_PACK AS CUST_MASTER_PACK,T.MASTER_PACK AS TRAN_MASTER_PACK  FROM CUSTOMER C,TRANSPORTER T "+
		              " WHERE C.CUST_CODE = ? AND T.TRAN_CODE= ?";
			
			pstmt = conn.prepareStatement(sqlCustTran);
			
			pstmt.setString(1,customerCode);
			pstmt.setString(2,tranCode);
			
			rSet = pstmt.executeQuery();
			if( rSet.next())
			{
				custMasterPack = checkNull(rSet.getString("CUST_MASTER_PACK"));
				tranMasterPack = checkNull(rSet.getString("TRAN_MASTER_PACK"));		
			}
			System.out.println("Master Pack Allow Customer Master Master_Pack Flag["+custMasterPack+"]Transporter Master Master_Pack Flag["+tranMasterPack+"]");
			if((custMasterPack != null && custMasterPack.equalsIgnoreCase("Y")) && (tranMasterPack != null && tranMasterPack.equalsIgnoreCase("Y")))
			{
				//return true;
				masterPack = true;
			}			
			
		}
		catch(Exception e)
		{
			System.out.println("Exception in  == >"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if( rSet != null )
				{
					rSet.close();
					rSet = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch (Exception e1)
			{
				throw new ITMException(e1);
			}
		}
	 System.out.println("Returing Result==============>>>"+masterPack);	
	 return masterPack;	
	}
	//Changed by Rohan on 3-12-11 [WM1ESUN006] To Check master Pack allow.end
	
	//private String getAvilablePickLocation(String pickType,Connection conn,String itemLocType) throws ITMException
	private String getAvilablePickLocation(String pickType,Connection conn,String itemLocType,int locPrefZone, String locCode,String itemCode,String siteCode,String lotNo,String lpnNo) throws ITMException
	{
		String sql = "";
		String stockSql = "";
		ResultSet rs = null;
		ResultSet rs1 = null;
		ResultSet rs2 = null;
		ResultSet rsStock = null;
		ResultSet rsOrder = null;
		PreparedStatement pstmt = null;
		PreparedStatement pstmtStock = null;
		PreparedStatement pstmtOrder = null;
		PreparedStatement pstmtItemLotOpt0 = null;
		PreparedStatement pstmtItemLotOpt1 = null;
		double stockQty = 0d;
		String suggLocCode = "";
		String singleLotSl = "";
		String itemLotOpt = "";
		ArrayList sugstLocList = new ArrayList();
		String orderSql = "";
		String sqlItemLotOpt0 = "";
		String sqlItemLotOpt1 = "";
		String invStat = "";
		String invStatDisparmVar = "";
		double quantity = 0;
		int count = 0;
		
		try
		{
			
			sql ="SELECT A.LOC_CODE AS LOC_CODE,A.SINGLE_LOT_SL AS  SINGLE_LOT_SL,A.ITEM_LOT_OPT AS ITEM_LOT_OPT"
				+ " FROM LOCATION A, INVSTAT B  WHERE A.INV_STAT = B.INV_STAT AND B.AVAILABLE = 'Y' "
				+ " AND (CASE WHEN B.STAT_TYPE IS NULL THEN ' ' ELSE B.STAT_TYPE END) <> 'S' "
				//Changed By Sankara 08/04/12 To pass the argument items Location Type.
				//+ " AND A.INV_STAT = ? ORDER BY LOC_CODE ";
				//Changed by Sankara on 08/11/12 To get absolute value of suggested Location
				//+ " AND A.INV_STAT = ? AND A.LOC_TYPE = ? ORDER BY LOC_CODE ";
				//+ " AND A.INV_STAT = ? AND A.LOC_TYPE = ? ORDER BY ABS( A.LOC_ZONE - ?), A.LOC_CODE ";
				+ " AND A.INV_STAT = ? AND A.LOC_TYPE = ? ORDER BY ABS( A.LOC_ZONE - ?), A.LOC_CODE ";
		
			
			//stockSql = "SELECT SUM(CASE WHEN QUANTITY IS NULL THEN 0 ELSE QUANTITY END) AS STOCK_QTY "
				//	+  " FROM STOCK WHERE LOC_CODE = ? ";
			//Changed By Pragyan 30/01/13 To get proper quantity grater then zero
			//stockSql =  "SELECT QUANTITY FROM STOCK WHERE LOC_CODE = ? " ;
			stockSql =  "SELECT QUANTITY FROM STOCK WHERE LOC_CODE = ?  AND QUANTITY > 0" ;
			//Changed By Pragyan To change the sql
			//sqlItemLotOpt0 = "SELECT COUNT(*) AS COUNT FROM STOCK WHERE ITEM_CODE <> ? AND SITE_CODE = ? AND LOC_CODE = ? AND LOT_NO <> ?";
			sqlItemLotOpt0 = "SELECT COUNT(*) AS COUNT FROM STOCK WHERE (ITEM_CODE <> ? OR LOT_NO <> ?) AND SITE_CODE = ? AND LOC_CODE = ? AND QUANTITY > 0"; //AND LOT_NO <> ?"
			//sqlItemLotOpt1 = "SELECT COUNT(*) AS COUNT FROM STOCK WHERE  ITEM_CODE <> ? AND SITE_CODE = ? AND LOC_CODE = ? AND LOT_NO = ? ";
			sqlItemLotOpt1 = "SELECT COUNT(*) AS COUNT FROM STOCK WHERE  ITEM_CODE <> ? AND SITE_CODE = ? AND LOC_CODE = ? AND QUANTITY > 0";

			//orderSql = "SELECT COUNT(*) AS COUNT FROM REPL_ORD_DET  WHERE LOC_CODE__TO = ?";
			//Changed by Rohan on 19-02-13  free location form cancle Repanishment
			//orderSql = "SELECT COUNT(*) AS COUNT FROM REPL_ORD_DET O  WHERE O.LOC_CODE__TO = ? AND NOT EXISTS (SELECT 1 FROM REPL_ISS_HDR I WHERE I.REPL_ORDER = O.REPL_ORDER AND I.CONFIRMED = 'Y') "; //changes done by Ashish Sonawane on 10-jul-12
			
			orderSql = "SELECT COUNT(*) AS COUNT FROM REPL_ORD_DET O  WHERE O.LOC_CODE__TO = ? " 
					  +" AND CASE WHEN CANCEL_MODE IS NULL THEN 'N' ELSE CANCEL_MODE END <> 'Y' " 
					  +" AND NOT EXISTS (SELECT 1 FROM REPL_ISS_HDR I WHERE I.REPL_ORDER = O.REPL_ORDER AND I.CONFIRMED = 'Y') ";
			
			if ( "A".equalsIgnoreCase(pickType.trim()) )//Active pick
			{
				invStatDisparmVar = "ACTIVE_PICK_INVSTAT";
			}
			else if ( "C".equalsIgnoreCase(pickType.trim()) || "M".equalsIgnoreCase(pickType.trim()) )//Case pick & master pick
			{
				invStatDisparmVar = "CASE_PICK_INVSTAT";
			}
			else if ( "N".equalsIgnoreCase(pickType.trim()))//Case pick & master pick
			{
				invStatDisparmVar = "PND_INVSTAT";
				//Changed by sumit on 06/08/12 getting pnd location of loc_code from location start.
				sql = 	"SELECT A.LOC_CODE AS LOC_CODE,A.SINGLE_LOT_SL AS  SINGLE_LOT_SL,A.ITEM_LOT_OPT AS ITEM_LOT_OPT"
						+ " FROM LOCATION A, INVSTAT B  WHERE A.INV_STAT = B.INV_STAT AND B.AVAILABLE = 'Y' "
						+ " AND (CASE WHEN B.STAT_TYPE IS NULL THEN ' ' ELSE B.STAT_TYPE END) <> 'S' "
						//Changed By Sankara 08/04/12 To pass the argument items Location Type.
						//+ " AND A.INV_STAT = ? ORDER BY LOC_CODE ";
						//+ " AND A.INV_STAT = ? AND A.LOC_TYPE = ? AND A.LOC_GROUP = (SELECT DROP_GROUP FROM LOCATION WHERE LOC_CODE = ? )"
						+ " AND A.INV_STAT = ? AND A.LOC_TYPE = ?  AND A.LOC_GROUP = (SELECT DROP_GROUP FROM LOCATION WHERE LOC_CODE = ? )"
						+ " ORDER BY ABS( A.LOC_ZONE - ?) ,A.LOC_CODE ";
				
				System.out.println(" pnd sql -> ["+sql+"]");
				//Changed by sumit on 06/08/12 getting pnd location of loc_code from location end.
			}
			
			invStat = discommon.getDisparams("999999",invStatDisparmVar,conn);
			pstmtStock =  conn.prepareStatement(stockSql);
			pstmt =  conn.prepareStatement(sql);
			pstmtOrder = conn.prepareStatement(orderSql);
			pstmtItemLotOpt0 = conn.prepareStatement( sqlItemLotOpt0 );
			pstmtItemLotOpt1 = conn.prepareStatement( sqlItemLotOpt1);
			//Changed by sumit on 06/08/12 commented bellow setString and apply 3 parameter in case of pnd location start. 
			/*pstmt.setString(1, invStat);
			//Changed By Sankara 08/04/12 To pass the argument items Location Type.
			pstmt.setString(2, itemLocType);*/
			if("N".equalsIgnoreCase(pickType.trim()))
			{
				pstmt.setString(1, invStat);
				//Changed By Sankara 08/04/12 To pass the argument items Location Type.
				pstmt.setString(2, itemLocType);
				pstmt.setString(3, locCode);
				pstmt.setInt(4, locPrefZone);
				
			}
			else
			{
				pstmt.setString(1, invStat);
				//Changed By Sankara 08/04/12 To pass the argument items Location Type.
				pstmt.setString(2, itemLocType);
				pstmt.setInt(3, locPrefZone);
				
			}
			//Changed by sumit on 06/08/12 apply 3 parameter in case of pnd location end. 
			
			rs = pstmt.executeQuery();

			while (rs.next())
			{
				suggLocCode = checkNull(rs.getString("LOC_CODE") );
				singleLotSl = checkNull(rs.getString("SINGLE_LOT_SL") );
				itemLotOpt = checkNull(rs.getString("ITEM_LOT_OPT") );
				
				quantity = 0;
				count = 0;
				/*pstmtOrder.setString(1, suggLocCode);
				rsOrder = pstmtOrder.executeQuery();
				
				if(rsOrder.next())
				{
					int count = rsOrder.getInt("COUNT");
					
					if(count > 0)
					{
						continue;
					}
				}
				
				pstmtStock.setString( 1, suggLocCode );
				rsStock = pstmtStock.executeQuery();
				if ( rsStock.next() )
				{
					stockQty = rsStock.getDouble("STOCK_QTY");

					if ( stockQty == 0 )
					{
						//sugstLocList.add(suggLocCode);
						return suggLocCode;
					}
				}
				else
				{
					//sugstLocList.add(suggLocCode);
					return suggLocCode;
				}
				pstmtStock.clearParameters();
				rsStock.close(); rsStock = null;*/
				
				
				if( singleLotSl.trim().equalsIgnoreCase("Y") )
				{
					//sql = "SELECT QUANTITY FROM STOCK WHERE LOC_CODE = ? " ;
							//" AND SITE_CODE = ?"
							 // + " AND LOC_CODE = ? AND lOT_NO = ? AND LOT_SL = ?";
					//pstmt = conn.prepareStatement( sql );
					//pstmt.setString( 1, itemCode );
					//pstmt.setString( 2, siteCode );
					pstmtStock.setString( 1, suggLocCode );
					//pstmt.setString( 4, lotNo );
					//pstmt.setString( 5, lpnNo );
					rs1 = pstmtStock.executeQuery();	
					if( rs1.next() )
					{
						quantity = rs1.getDouble("QUANTITY");
					}
					rs1.close();
					rs1 = null;
					/*pstmt.close();
					pstmt = null;*/
					
					//pstmtOrder = conn.prepareStatement(orderSql);
					pstmtOrder.setString(1, suggLocCode);
					rsOrder = pstmtOrder.executeQuery();
					
					
					
					if( quantity != 0 )
					{
						suggLocCode = "";
						/*errList.add( "VTLOCCODE1" );
						errFields.add( childNodeName.toLowerCase() );*/
						continue;
					}
					
					
					
					if(rsOrder.next())
					{
						count = rsOrder.getInt("COUNT");
					}
					
					System.out.println("Current Count From Repl Order Location Exist Count["+count+"]");
					pstmtOrder.clearParameters();
					if(rsOrder != null)
					{
						rsOrder.close();
						rsOrder = null;
					}
					/*if(pstmtOrder != null)
					{
						pstmtOrder.close();
						pstmtOrder = null;
					}*/
					if(count > 0)
					{
						suggLocCode = "";
						continue;
					}
					else
					{
						return suggLocCode;
					}				
				}
				else
				{
					if( itemLotOpt.trim().equals("0") )  
					{
						/*sql = "SELECT COUNT(*) AS COUNT FROM STOCK WHERE (ITEM_CODE <> ? OR LOT_NO <> ?) AND SITE_CODE = ? AND LOC_CODE = ? and Quantity > 0 //AND LOT_NO <> ?";
						pstmtItemLotOpt1 = conn.prepareStatement( sql );*/
						pstmtItemLotOpt0.setString( 1, itemCode );
						//pstmtItemLotOpt0.setString( 2, siteCode );
						pstmtItemLotOpt0.setString( 2, lotNo );
						pstmtItemLotOpt0.setString( 3, siteCode );
						pstmtItemLotOpt0.setString( 4, suggLocCode );
						//pstmtItemLotOpt0.setString( 4, lotNo );
						rs2 = pstmtItemLotOpt0.executeQuery();
						if( rs2.next() )
						{
							count = rs2.getInt("COUNT");
						}
						rs2.close();
						rs2 = null;
						

						if( count > 0 )
						{
							suggLocCode = "";
							continue;
						}
						
						pstmtOrder.setString(1, suggLocCode);
						rsOrder = pstmtOrder.executeQuery();
						
						if(rsOrder.next())
						{
							count = rsOrder.getInt("COUNT");
						}
						if(rsOrder != null)
						{
							rsOrder.close();
							rsOrder = null;
						}
						if(count > 0)
						{
							suggLocCode = "";
							continue;
						}
						else
						{
							//Changed by sumit on 11/12/12 suggesting  active pick location start
							//return suggLocCode;
							//Changed by sumit on 19/02/13 on adding condition for pickType "T"
							//if("A".equalsIgnoreCase(pickType.trim()))
							if("A".equalsIgnoreCase(pickType.trim()) || "T".equalsIgnoreCase(pickType.trim()))
							{
								//Changed by sumit on 09/02/13 changing parameter as per method
								//return getPickLocForSameItemLotNo(invStat,pickType.trim(),itemCode,lotNo, lpnNo, suggLocCode, conn);
								return getPickLocForSameItemLotNo(invStat,pickType.trim(),itemCode,lotNo, lpnNo, suggLocCode,siteCode, conn);
							}
							else
							{
								return suggLocCode;
							}
							//Changed by sumit on 11/12/12 suggesting  active pick location end
						}				
					}
					else if( itemLotOpt.trim().equals("1") )  //Validation for single item_code multiple lot_no
					{
						/*sql = "SELECT COUNT(*) AS COUNT FROM STOCK WHERE  ITEM_CODE <> ? AND SITE_CODE = ? AND LOC_CODE = ?// AND LOT_NO = ? ";
						pstmt = conn.prepareStatement( sql );*/
						pstmtItemLotOpt1.setString( 1, itemCode );
						pstmtItemLotOpt1.setString( 2, siteCode );
						pstmtItemLotOpt1.setString( 3, suggLocCode );
						//pstmtItemLotOpt1.setString( 4, lotNo );
						rs2 = pstmtItemLotOpt1.executeQuery();
						if( rs2.next() )
						{
							count = rs2.getInt("COUNT");
						}
						rs2.close();
						rs2 = null;
						/*pstmt.close();
						pstmt = null;*/
						if( count > 0 )
						{
							continue;
						}
						
						pstmtOrder.setString(1, suggLocCode);
						rsOrder = pstmtOrder.executeQuery();
						
						if(rsOrder.next())
						{
							count = rsOrder.getInt("COUNT");
						}
						if(rsOrder != null)
						{
							rsOrder.close();
							rsOrder = null;
						}
						if(count > 0)
						{
							suggLocCode = "";
							continue;
							
						}
						else
						{
							//Changed by sumit on 11/12/12 suggesting  active pick location start
							//return suggLocCode;
							//Changed by sumit on 19/02/13 on adding condition for pickType "T"
							//if("A".equalsIgnoreCase(pickType.trim()))
							if("A".equalsIgnoreCase(pickType.trim()) || "T".equalsIgnoreCase(pickType.trim()))
							{								
								//Changed by sumit on 09/02/13 changing parameter as per method
								//return getPickLocForSameItemLotNo(invStat,pickType.trim(),itemCode,lotNo, lpnNo, suggLocCode, conn);
								return getPickLocForSameItemLotNo(invStat,pickType.trim(),itemCode,lotNo, lpnNo, suggLocCode,siteCode, conn);
							}
							else
							{
								return suggLocCode;
							}
							//Changed by sumit on 11/12/12 suggesting  active pick location end
						}
					}
					else
					{
						//Changed by sumit on 11/12/12 suggesting  active pick location start
						//return suggLocCode;
						//Changed by sumit on 19/02/13 on adding condition for pickType "T"
						//if("A".equalsIgnoreCase(pickType.trim()))
						if("A".equalsIgnoreCase(pickType.trim()) || "T".equalsIgnoreCase(pickType.trim()))
						{								
							//Changed by sumit on 09/02/13 changing parameter as per method
							//return getPickLocForSameItemLotNo(invStat,pickType.trim(),itemCode,lotNo, lpnNo, suggLocCode, conn);
							return getPickLocForSameItemLotNo(invStat,pickType.trim(),itemCode,lotNo, lpnNo, suggLocCode,siteCode, conn);
						}
						else
						{
							return suggLocCode;
						}
						//Changed by sumit on 11/12/12 suggesting  active pick location end
					}
				}
				
				
			}
			
			if( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( rs1 != null )
			{
				rs1.close();
				rs1 = null;
			}
			if( rs2 != null )
			{
				rs2.close();
				rs2 = null;
			}
			if( rsStock != null )
			{
				rsStock.close();
				rsStock = null;
			}
			if( rsOrder != null )
			{
				rsOrder.close();
				rsOrder = null;
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			if( pstmtStock != null )
			{
				pstmtStock.close();
				pstmtStock = null;
			}
			if( pstmtOrder != null )
			{
				pstmtOrder.close();
				pstmtOrder = null;
			}
			
			if(pstmtItemLotOpt0 != null)
			{
				pstmtItemLotOpt0.close();
				pstmtItemLotOpt0 = null;
			}
			
			if(pstmtItemLotOpt1 != null)
			{
				pstmtItemLotOpt1.close();
				pstmtItemLotOpt1 = null;
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception in  == >"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( rs1 != null )
				{
					rs1.close();
					rs1 = null;
				}
				if( rs2 != null )
				{
					rs2.close();
					rs2 = null;
				}
				if( rsStock != null )
				{
					rsStock.close();
					rsStock = null;
				}
				if( rsOrder != null )
				{
					rsOrder.close();
					rsOrder = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				if( pstmtStock != null )
				{
					pstmtStock.close();
					pstmtStock = null;
				}
				if( pstmtOrder != null )
				{
					pstmtOrder.close();
					pstmtOrder = null;
				}
				if(pstmtItemLotOpt0 != null)
				{
					pstmtItemLotOpt0.close();
					pstmtItemLotOpt0 = null;
				}
				
				if(pstmtItemLotOpt1 != null)
				{
					pstmtItemLotOpt1.close();
					pstmtItemLotOpt1 = null;
				}
			}
			catch (Exception e1)
			{
				throw new ITMException(e1);
			}
		}
		
	  System.out.println("Return Suggested Location will throw error  == >["+suggLocCode+"]");
	 return suggLocCode;	
	}
	
	//Changed by sumit on 06/08/12 changing method parameter 
	//private String getAvilablePickLocation(String pickType,Connection conn,String itemLocType) throws ITMException
	private ArrayList getAvilableCasePickLocationList(String pickType,Connection conn,String itemLocType,int locPrefZone, String locCode,String itemCode,String siteCode,String lotNo,String lpnNo) throws ITMException
	{
		String sql = "";
		String stockSql = "";
		ResultSet rs = null;
		ResultSet rs1 = null;
		ResultSet rs2 = null;
		ResultSet rsStock = null;
		ResultSet rsOrder = null;
		PreparedStatement pstmt = null;
		PreparedStatement pstmtStock = null;
		PreparedStatement pstmtOrder = null;
		PreparedStatement pstmtItemLotOpt0 = null;
		PreparedStatement pstmtItemLotOpt1 = null;
		double stockQty = 0d;
		String suggLocCode = "";
		String singleLotSl = "";
		String itemLotOpt = "";
		ArrayList sugstLocList = new ArrayList();
		String orderSql = "";
		String sqlItemLotOpt0 = "";
		String sqlItemLotOpt1 = "";
		String invStat = "";
		String invStatDisparmVar = "";
		double quantity = 0;
		int count = 0;
		
		ArrayList suggestedLocList = new ArrayList();
		
		
		try
		{
			
			sql ="SELECT A.LOC_CODE AS LOC_CODE,A.SINGLE_LOT_SL AS  SINGLE_LOT_SL,A.ITEM_LOT_OPT AS ITEM_LOT_OPT"
				+ " FROM LOCATION A, INVSTAT B  WHERE A.INV_STAT = B.INV_STAT AND B.AVAILABLE = 'Y' "
				+ " AND (CASE WHEN B.STAT_TYPE IS NULL THEN ' ' ELSE B.STAT_TYPE END) <> 'S' "
				+ " AND A.INV_STAT = ? AND A.LOC_TYPE = ? ORDER BY ABS( A.LOC_ZONE - ?), A.LOC_CODE ";
		
	
			//stockSql =  "SELECT QUANTITY FROM STOCK WHERE LOC_CODE = ? " ;
			stockSql =  "SELECT QUANTITY FROM STOCK WHERE LOC_CODE = ? AND QUANTITY > 0" ;
			
			sqlItemLotOpt0 = "SELECT COUNT(*) AS COUNT FROM STOCK WHERE (ITEM_CODE <> ? OR LOT_NO <> ?) AND SITE_CODE = ? AND LOC_CODE = ? AND QUANTITY > 0"; //AND LOT_NO <> ?"
			
			sqlItemLotOpt1 = "SELECT COUNT(*) AS COUNT FROM STOCK WHERE  ITEM_CODE <> ? AND SITE_CODE = ? AND LOC_CODE = ? AND QUANTITY > 0";
			//Changed by Rohan on 19-02-13  free location form cancle Repanishment
			//orderSql = "SELECT COUNT(*) AS COUNT FROM REPL_ORD_DET O  WHERE O.LOC_CODE__TO = ? AND NOT EXISTS (SELECT 1 FROM REPL_ISS_HDR I WHERE I.REPL_ORDER = O.REPL_ORDER AND I.CONFIRMED = 'Y') "; //changes done by Ashish Sonawane on 10-jul-12
			orderSql = "SELECT COUNT(*) AS COUNT FROM REPL_ORD_DET O  WHERE O.LOC_CODE__TO = ? " 
					  +" AND CASE WHEN CANCEL_MODE IS NULL THEN 'N' ELSE CANCEL_MODE END <> 'Y' " 
					  +" AND NOT EXISTS (SELECT 1 FROM REPL_ISS_HDR I WHERE I.REPL_ORDER = O.REPL_ORDER AND I.CONFIRMED = 'Y') ";
			
			if ( "A".equalsIgnoreCase(pickType.trim()) )
			{
				invStatDisparmVar = "ACTIVE_PICK_INVSTAT";
			}
			else if ( "C".equalsIgnoreCase(pickType.trim()) || "M".equalsIgnoreCase(pickType.trim()) )
			{
				invStatDisparmVar = "CASE_PICK_INVSTAT";
			}
			else if ( "N".equalsIgnoreCase(pickType.trim()))
			{
				invStatDisparmVar = "PND_INVSTAT";
	
				sql = 	"SELECT A.LOC_CODE AS LOC_CODE,A.SINGLE_LOT_SL AS  SINGLE_LOT_SL,A.ITEM_LOT_OPT AS ITEM_LOT_OPT"
						+ " FROM LOCATION A, INVSTAT B  WHERE A.INV_STAT = B.INV_STAT AND B.AVAILABLE = 'Y' "
						+ " AND (CASE WHEN B.STAT_TYPE IS NULL THEN ' ' ELSE B.STAT_TYPE END) <> 'S' "					
						+ " AND A.INV_STAT = ? AND A.LOC_TYPE = ? AND A.LOC_GROUP = (SELECT DROP_GROUP FROM LOCATION WHERE LOC_CODE = ? )"
						+ " ORDER BY ABS( A.LOC_ZONE - ?) ,A.LOC_CODE ";
				
				System.out.println(" pnd sql -> ["+sql+"]");
				
			}
			
			invStat = discommon.getDisparams("999999",invStatDisparmVar,conn);
			pstmtStock =  conn.prepareStatement(stockSql);
			pstmt =  conn.prepareStatement(sql);
			pstmtOrder = conn.prepareStatement(orderSql);
			pstmtItemLotOpt0 = conn.prepareStatement( sqlItemLotOpt0 );
			pstmtItemLotOpt1 = conn.prepareStatement( sqlItemLotOpt1);
		
			if("N".equalsIgnoreCase(pickType.trim()))
			{
				pstmt.setString(1, invStat);
				pstmt.setString(2, itemLocType);
				pstmt.setString(3, locCode);
				pstmt.setInt(4, locPrefZone);
				
			}
			else
			{
				pstmt.setString(1, invStat);
				pstmt.setString(2, itemLocType);
				pstmt.setInt(3, locPrefZone);
				
			}
			
			rs = pstmt.executeQuery();

			while (rs.next())
			{
				suggLocCode = checkNull(rs.getString("LOC_CODE") );
				singleLotSl = checkNull(rs.getString("SINGLE_LOT_SL") );
				itemLotOpt = checkNull(rs.getString("ITEM_LOT_OPT") );
				
				quantity = 0;
				count = 0;
				
				
				if( singleLotSl.trim().equalsIgnoreCase("Y") )
				{
					
					pstmtStock.setString( 1, suggLocCode );
					rs1 = pstmtStock.executeQuery();	
					if( rs1.next() )
					{
						quantity = rs1.getDouble("QUANTITY");
					}
					rs1.close();
					rs1 = null;
					pstmtOrder.setString(1, suggLocCode);
					rsOrder = pstmtOrder.executeQuery();
					
					
					
					if( quantity != 0 )
					{
						suggLocCode = "";
						continue;
					}
					
					
					
					if(rsOrder.next())
					{
						count = rsOrder.getInt("COUNT");
					}
					
					System.out.println("Current Count From Repl Order Location Exist Count["+count+"]");
					pstmtOrder.clearParameters();
					if(rsOrder != null)
					{
						rsOrder.close();
						rsOrder = null;
					}
					if(count > 0)
					{
						suggLocCode = "";
						continue;
					}
					else
					{
						suggestedLocList.add(suggLocCode) ;
					}				
				}
				else
				{
					if( itemLotOpt.trim().equals("0") )  
					{
						pstmtItemLotOpt0.setString( 1, itemCode );
						pstmtItemLotOpt0.setString( 2, lotNo );
						pstmtItemLotOpt0.setString( 3, siteCode );
						pstmtItemLotOpt0.setString( 4, suggLocCode );
						rs2 = pstmtItemLotOpt0.executeQuery();
						
						if( rs2.next() )
						{
							count = rs2.getInt("COUNT");
						}
						rs2.close();
						rs2 = null;
						

						if( count > 0 )
						{
							suggLocCode = "";
							continue;
						}
						
						pstmtOrder.setString(1, suggLocCode);
						rsOrder = pstmtOrder.executeQuery();
						
						if(rsOrder.next())
						{
							count = rsOrder.getInt("COUNT");
						}
						if(rsOrder != null)
						{
							rsOrder.close();
							rsOrder = null;
						}
						if(count > 0)
						{
							suggLocCode = "";
							continue;
						}
						else
						{

							//Changed by sumit on 19/02/13 on adding condition for pickType "T"
							//if("A".equalsIgnoreCase(pickType.trim()))
							if("A".equalsIgnoreCase(pickType.trim()) || "T".equalsIgnoreCase(pickType.trim()))
							{
								//Changed by sumit on 09/02/13 change as per method
								//suggLocCode =  getPickLocForSameItemLotNo(invStat,pickType.trim(),itemCode,lotNo, lpnNo, suggLocCode, conn);
								suggLocCode =  getPickLocForSameItemLotNo(invStat,pickType.trim(),itemCode,lotNo, lpnNo, suggLocCode,siteCode, conn);
								suggestedLocList.add(suggLocCode) ;
							}
							else
							{
								suggestedLocList.add(suggLocCode) ;
							}
						}				
					}
					else if( itemLotOpt.trim().equals("1") )  
					{
						
						pstmtItemLotOpt1.setString( 1, itemCode );
						pstmtItemLotOpt1.setString( 2, siteCode );
						pstmtItemLotOpt1.setString( 3, suggLocCode );
						rs2 = pstmtItemLotOpt1.executeQuery();
						if( rs2.next() )
						{
							count = rs2.getInt("COUNT");
						}
						rs2.close();
						rs2 = null;
						if( count > 0 )
						{
							continue;
						}
						
						pstmtOrder.setString(1, suggLocCode);
						rsOrder = pstmtOrder.executeQuery();
						
						if(rsOrder.next())
						{
							count = rsOrder.getInt("COUNT");
						}
						if(rsOrder != null)
						{
							rsOrder.close();
							rsOrder = null;
						}
						if(count > 0)
						{
							suggLocCode = "";
							continue;
							
						}
						else
						{
							//Changed by sumit on 19/02/13 on adding condition for pickType "T"
							//if("A".equalsIgnoreCase(pickType.trim()))
							if("A".equalsIgnoreCase(pickType.trim()) || "T".equalsIgnoreCase(pickType.trim()))
							{	
								//Changed by sumit on 09/02/13 change as per method
								//suggLocCode = getPickLocForSameItemLotNo(invStat,pickType.trim(),itemCode,lotNo, lpnNo, suggLocCode, conn);
								suggLocCode = getPickLocForSameItemLotNo(invStat,pickType.trim(),itemCode,lotNo, lpnNo, suggLocCode,siteCode, conn);
								suggestedLocList.add(suggLocCode) ;
							}
							else
							{
								suggestedLocList.add(suggLocCode) ;
							}
						}
					}
					else
					{
						//Changed by sumit on 19/02/13 on adding condition for pickType "T"
						//if("A".equalsIgnoreCase(pickType.trim()))
						if("A".equalsIgnoreCase(pickType.trim()) || "T".equalsIgnoreCase(pickType.trim()))
						{
							//Changed by sumit on 09/02/13 change as per method
							//suggLocCode =  getPickLocForSameItemLotNo(invStat,pickType.trim(),itemCode,lotNo, lpnNo, suggLocCode, conn);
							suggLocCode =  getPickLocForSameItemLotNo(invStat,pickType.trim(),itemCode,lotNo, lpnNo, suggLocCode,siteCode, conn);
							suggestedLocList.add(suggLocCode) ;
						}
						else
						{
							suggestedLocList.add(suggLocCode) ;
						}
					}
				}
				
				
			}
			
			if( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( rs1 != null )
			{
				rs1.close();
				rs1 = null;
			}
			if( rs2 != null )
			{
				rs2.close();
				rs2 = null;
			}
			if( rsStock != null )
			{
				rsStock.close();
				rsStock = null;
			}
			if( rsOrder != null )
			{
				rsOrder.close();
				rsOrder = null;
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			if( pstmtStock != null )
			{
				pstmtStock.close();
				pstmtStock = null;
			}
			if( pstmtOrder != null )
			{
				pstmtOrder.close();
				pstmtOrder = null;
			}
			
			if(pstmtItemLotOpt0 != null)
			{
				pstmtItemLotOpt0.close();
				pstmtItemLotOpt0 = null;
			}
			
			if(pstmtItemLotOpt1 != null)
			{
				pstmtItemLotOpt1.close();
				pstmtItemLotOpt1 = null;
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception in  == >"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( rs1 != null )
				{
					rs1.close();
					rs1 = null;
				}
				if( rs2 != null )
				{
					rs2.close();
					rs2 = null;
				}
				if( rsStock != null )
				{
					rsStock.close();
					rsStock = null;
				}
				if( rsOrder != null )
				{
					rsOrder.close();
					rsOrder = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				if( pstmtStock != null )
				{
					pstmtStock.close();
					pstmtStock = null;
				}
				if( pstmtOrder != null )
				{
					pstmtOrder.close();
					pstmtOrder = null;
				}
				if(pstmtItemLotOpt0 != null)
				{
					pstmtItemLotOpt0.close();
					pstmtItemLotOpt0 = null;
				}
				
				if(pstmtItemLotOpt1 != null)
				{
					pstmtItemLotOpt1.close();
					pstmtItemLotOpt1 = null;
				}
			}
			catch (Exception e1)
			{
				throw new ITMException(e1);
			}
		}
		
	  System.out.println("Return Suggested Location will throw error  == >["+suggLocCode+"]");
	 return suggestedLocList;	
	}
	private HashMap getTransportInfo(String saleOrder,double perShipWeight ,double noArt,Connection conn) throws ITMException
	{
		String sql = "";
		String sql1 = "";
		String sqlShipStanCode = "";
		//Changed by Rohan on 30/06/12
		String sqlCust = "";
		ResultSet rs = null;
		ResultSet rs1 = null;
		PreparedStatement pstmt = null;
		HashMap transInfoMap = new HashMap();
		String stanCodeFrm = "",stateCodeFrm = "",siteCodeShip = "",stanCodeCust= "",custCodeDlv = "",stateCodeCust ="";
		String tranCode = "",transMod= "",maxWeight= "",locType= "";
		String pinTo = "",pinFrm = "";
		HashMap stationInfoMap = null;

		try
		{
			HashMap sordMap = getSordInfo(saleOrder,conn);
			siteCodeShip = (String)sordMap.get("SHIP_CODE");
			stanCodeCust = (String)sordMap.get("STAN_CODE");
			custCodeDlv = (String)sordMap.get("CUST_CODE");
			stateCodeCust = (String)sordMap.get("STATE_DLV");
			stationInfoMap = getStanCodeInfo(siteCodeShip, conn);
			stanCodeFrm = (String)stationInfoMap.get("STAN_CODE");
			stateCodeFrm = (String)stationInfoMap.get("STATE_CODE");
			pinFrm = getPinSite(siteCodeShip,conn); 
			pinTo = getPinCust(custCodeDlv,conn);
			//Changed by Rohan on 30/06/12.start
			/*
			sql = "SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE FROM DISTROUTEDET A,DISTROUTE B "
				+ " WHERE A.STAN_CODE__FR = ? AND A.STAN_CODE__TO = ? AND A.STATE_CODE__FR = ? AND A.STATE_CODE__TO = ?"
				+ " AND A.DIST_ROUTE = B.DIST_ROUTE AND B.CUST_CODE = ? ";
			 */

			/*
			 sql = "SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE FROM DISTROUTEDET A,DISTROUTE B "
					+ " WHERE A.STATE_CODE__FR = ? AND A.STATE_CODE__TO = ?"
					+ " AND A.DIST_ROUTE = B.DIST_ROUTE AND B.CUST_CODE = ? ";
			 */
			//Changed by Rohan on 30/06/12.end
			//pstmt = conn.prepareStatement(sql);
			//Changed by Rohan on 30/06/12.start
			/*
			pstmt.setString(1,stanCodeFrm);
			pstmt.setString(2,stanCodeCust);
			pstmt.setString(3,stateCodeFrm);
			pstmt.setString(4,stateCodeCust);
			pstmt.setString(5,custCodeDlv);
			rs = pstmt.executeQuery();
			 */
			/*
			pstmt.setString(1,stateCodeFrm);
			pstmt.setString(2,stateCodeCust);
			pstmt.setString(3,custCodeDlv);
			rs = pstmt.executeQuery();
			//Changed by Rohan on 30/06/12.end

			if(rs.next())
			{
				tranCode = rs.getString("TRAN_CODE");
				System.out.println("tranCode===>"+tranCode);
				transMod = rs.getString("TRANS_MODE");
				maxWeight = rs.getString("MAX_WEIGHT");
				locType = rs.getString("LOC_TYPE");
			}
			 */
			//Changed by Rohan on 30/06/12.start
			/*
			if("null".equalsIgnoreCase(tranCode) || (tranCode.trim().length()) == 0)
			{
				pstmt.setString(3," ");
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					tranCode = rs.getString("TRAN_CODE");
					transMod = rs.getString("TRANS_MODE");
					maxWeight = rs.getString("MAX_WEIGHT");
					locType = rs.getString("LOC_TYPE");
				}
			}
			 */
			/*else
			{
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				sqlCust = "SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE FROM DISTROUTEDET A,DISTROUTE B "
					+ " WHERE A.DIST_ROUTE = B.DIST_ROUTE AND B.CUST_CODE = ? ";
				pstmt = conn.prepareStatement(sqlCust);	
				pstmt.setString(1,custCodeDlv);
				rs = pstmt.executeQuery();
				//Changed by Rohan on 30/06/12.end
				if(rs.next())
				{
					tranCode = rs.getString("TRAN_CODE");
					System.out.println("tranCode===>"+tranCode);
					transMod = rs.getString("TRANS_MODE");
					maxWeight = rs.getString("MAX_WEIGHT");
					locType = rs.getString("LOC_TYPE");
				}

			}*/
			
			//change by Kunal Mandhre on 04/07/12 as per S Manoharan Sir instruction 
			
			//change by Kunal Mandhre on 07/08/12 as per S Manoharan Sir instruction 
			//sql = "SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE FROM DISTROUTEDET A,DISTROUTE B " 
				//	+" WHERE  A.PIN__FR = ? AND A.PIN__TO = ? AND A.STAN_CODE__FR  = ? AND A.STAN_CODE__TO = ? "
					//+" AND  A.STATE_CODE__FR  = ? AND A.STATE_CODE__TO = ?  AND A.DIST_ROUTE = B.DIST_ROUTE AND B.CUST_CODE = ? ";
			sql =  " SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE FROM DISTROUTEDET A,DISTROUTE B "  
				  + " WHERE ( A.PIN__FR =  ?  OR A.PIN__FR = ' ' ) AND (A.PIN__TO = ?  OR   A.PIN__TO = ' ') AND (A.STAN_CODE__FR  =?  OR A.STAN_CODE__FR  = ' ' ) " 
				  + " AND ( A.STAN_CODE__TO =?   OR A.STAN_CODE__TO = ' ')  AND ( A.STATE_CODE__FR  = ?   OR A.STATE_CODE__FR  = ' ') "
				  //Change By Pragyan 02/01/12 to check max & min case
				 // + "AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' ) AND A.DIST_ROUTE = B.DIST_ROUTE AND B.CUST_CODE = ? ";
				 // + "AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' )  AND A.DIST_ROUTE = B.DIST_ROUTE AND B.CUST_CODE = ?  AND MIN_WEIGHT <= ? AND MAX_WEIGHT >= ?";
				  + "AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' )  AND A.DIST_ROUTE = B.DIST_ROUTE AND B.CUST_CODE = ?  AND MIN_WEIGHT <= ? AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ?";
					
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,pinFrm);
			pstmt.setString(2,pinTo);
			pstmt.setString(3,stanCodeFrm);
			pstmt.setString(4,stanCodeCust);
			pstmt.setString(5,stateCodeFrm);
			pstmt.setString(6,stateCodeCust);
			pstmt.setString(7,custCodeDlv);
			pstmt.setDouble(8,perShipWeight);
			pstmt.setDouble(9,perShipWeight);
			pstmt.setDouble(10,noArt);
			pstmt.setDouble(11,noArt);
			rs = pstmt.executeQuery();

			if(rs.next())
			{
				tranCode = rs.getString("TRAN_CODE");
				System.out.println("tranCode===>"+tranCode);
				transMod = rs.getString("TRANS_MODE");
				maxWeight = rs.getString("MAX_WEIGHT");
				locType = rs.getString("LOC_TYPE");
			}
			else
			{
				pstmt.close();
				pstmt = null;
				rs.close();
				rs = null;

				//sql = "SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE FROM DISTROUTEDET A,DISTROUTE B " 
					//	+" WHERE  A.PIN__FR = ? AND A.PIN__TO = ? AND A.STAN_CODE__FR  = ? AND A.STAN_CODE__TO = ? "
						//+" AND  A.STATE_CODE__FR  = ? AND A.STATE_CODE__TO = ?  AND A.DIST_ROUTE = B.DIST_ROUTE  ";
				//change by Kunal Mandhre on 07/08/12 as per S Manoharan Sir instruction
				sql =  " SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE FROM DISTROUTEDET A,DISTROUTE B "  
						  + " WHERE ( A.PIN__FR =  ?  OR A.PIN__FR = ' ' ) AND (A.PIN__TO = ?  OR   A.PIN__TO = ' ') AND (A.STAN_CODE__FR  =?  OR A.STAN_CODE__FR  = ' ' ) " 
						  + " AND ( A.STAN_CODE__TO =?   OR A.STAN_CODE__TO = ' ')  AND ( A.STATE_CODE__FR  = ?   OR A.STATE_CODE__FR  = ' ') "
						  //Change By Pragyan 02/01/12 to check max & min case
						 // + "AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' ) AND A.DIST_ROUTE = B.DIST_ROUTE  ";
						 // + "AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' ) AND A.DIST_ROUTE = B.DIST_ROUTE AND MIN_WEIGHT <= ? AND MAX_WEIGHT >= ? ";
						  + "AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' ) AND A.DIST_ROUTE = B.DIST_ROUTE AND MIN_WEIGHT <= ? AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ?";
				
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,pinFrm);
				pstmt.setString(2,pinTo);
				pstmt.setString(3,stanCodeFrm);
				pstmt.setString(4,stanCodeCust);
				pstmt.setString(5,stateCodeFrm);
				pstmt.setString(6,stateCodeCust);
				pstmt.setDouble(7,perShipWeight);
				pstmt.setDouble(8,perShipWeight);
				pstmt.setDouble(9,noArt);
				pstmt.setDouble(10,noArt);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					tranCode = rs.getString("TRAN_CODE");
					System.out.println("tranCode===>"+tranCode);
					transMod = rs.getString("TRANS_MODE");
					maxWeight = rs.getString("MAX_WEIGHT");
					locType = rs.getString("LOC_TYPE");
				}
				/*
				else
				{
					if( rs != null )
					{
						rs.close();
						rs = null;
					}
					if( pstmt != null )
					{
						pstmt.close();
						pstmt = null;
					}
					sql = "SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE FROM DISTROUTEDET A,DISTROUTE B "
							+" WHERE A.PIN__FR = ? AND A.PIN__TO = ? AND  A.STAN_CODE__FR = ' ' AND A.STAN_CODE__TO  = ' '	AND  A.STATE_CODE__FR = ' ' AND A.STATE_CODE__TO = ' ' AND A.DIST_ROUTE = B.DIST_ROUTE  AND B.CUST_CODE = ? ";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1,pinFrm);
					pstmt.setString(2,pinTo);
					pstmt.setString(3,custCodeDlv);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						tranCode = rs.getString("TRAN_CODE");
						System.out.println("tranCode===>"+tranCode);
						transMod = rs.getString("TRANS_MODE");
						maxWeight = rs.getString("MAX_WEIGHT");
						locType = rs.getString("LOC_TYPE");
					}
					else
					{
						if( rs != null )
						{
							rs.close();
							rs = null;
						}
						if( pstmt != null )
						{
							pstmt.close();
							pstmt = null;
						}
						sql = "SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE FROM DISTROUTEDET A,DISTROUTE B "
								+" WHERE A.PIN__FR = ? AND A.PIN__TO = ? AND  A.STAN_CODE__FR = ' ' AND A.STAN_CODE__TO  = ' '	AND  A.STATE_CODE__FR = ' ' AND A.STATE_CODE__TO = ' ' AND A.DIST_ROUTE = B.DIST_ROUTE  ";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1,pinFrm);
						pstmt.setString(2,pinTo);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							tranCode = rs.getString("TRAN_CODE");
							System.out.println("tranCode===>"+tranCode);
							transMod = rs.getString("TRANS_MODE");
							maxWeight = rs.getString("MAX_WEIGHT");
							locType = rs.getString("LOC_TYPE");
						}
						else
						{
							if( rs != null )
							{
								rs.close();
								rs = null;
							}
							if( pstmt != null )
							{
								pstmt.close();
								pstmt = null;
							}
							sql = "SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE FROM DISTROUTEDET A,DISTROUTE B "
									+" WHERE A.STAN_CODE__FR = ? AND A.STAN_CODE__TO = ? AND A.PIN__FR = ' ' AND A.PIN__TO = ' ' AND  A.STATE_CODE__FR = ' ' AND A.STATE_CODE__TO = ' ' AND A.DIST_ROUTE = B.DIST_ROUTE  AND B.CUST_CODE = ? ";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1,stanCodeFrm);
							pstmt.setString(2,stanCodeCust);
							pstmt.setString(3,custCodeDlv);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								tranCode = rs.getString("TRAN_CODE");
								System.out.println("tranCode===>"+tranCode);
								transMod = rs.getString("TRANS_MODE");
								maxWeight = rs.getString("MAX_WEIGHT");
								locType = rs.getString("LOC_TYPE");
							}
							else
							{
								if( rs != null )
								{
									rs.close();
									rs = null;
								}
								if( pstmt != null )
								{
									pstmt.close();
									pstmt = null;
								}
								sql = "SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE FROM DISTROUTEDET A,DISTROUTE B "
										+" WHERE A.STAN_CODE__FR = ? AND A.STAN_CODE__TO = ? AND A.PIN__FR = ' ' AND A.PIN__TO = ' ' AND  A.STATE_CODE__FR = ' ' AND A.STATE_CODE__TO = ' ' AND A.DIST_ROUTE = B.DIST_ROUTE  ";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1,stanCodeFrm);
								pstmt.setString(2,stanCodeCust);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									tranCode = rs.getString("TRAN_CODE");
									System.out.println("tranCode===>"+tranCode);
									transMod = rs.getString("TRANS_MODE");
									maxWeight = rs.getString("MAX_WEIGHT");
									locType = rs.getString("LOC_TYPE");
								}
								else
								{
									if( rs != null )
									{
										rs.close();
										rs = null;
									}
									if( pstmt != null )
									{
										pstmt.close();
										pstmt = null;
									}
									sql = "SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE FROM DISTROUTEDET A,DISTROUTE B "
											+" WHERE A.STATE_CODE__FR = ? AND A.STATE_CODE__TO = ? AND  A.STAN_CODE__FR = ' ' AND A.STAN_CODE__TO  = ' '	 AND A.PIN__FR = ' ' AND A.PIN__TO = ' '  AND A.DIST_ROUTE = B.DIST_ROUTE  AND B.CUST_CODE = ? ";
									pstmt = conn.prepareStatement(sql);
									pstmt.setString(1,stateCodeFrm);
									pstmt.setString(2,stateCodeCust);
									pstmt.setString(3,custCodeDlv);
									rs = pstmt.executeQuery();
									if(rs.next())
									{
										tranCode = rs.getString("TRAN_CODE");
										System.out.println("tranCode===>"+tranCode);
										transMod = rs.getString("TRANS_MODE");
										maxWeight = rs.getString("MAX_WEIGHT");
										locType = rs.getString("LOC_TYPE");
									}
									else
									{
										if( rs != null )
										{
											rs.close();
											rs = null;
										}
										if( pstmt != null )
										{
											pstmt.close();
											pstmt = null;
										}
										sql = "SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE FROM DISTROUTEDET A,DISTROUTE B "
												+" WHERE A.STATE_CODE__FR = ? AND A.STATE_CODE__TO = ? AND  A.STAN_CODE__FR = ' ' AND A.STAN_CODE__TO  = ' '	 AND A.PIN__FR = ' ' AND A.PIN__TO = ' '  AND A.DIST_ROUTE = B.DIST_ROUTE  ";
										pstmt = conn.prepareStatement(sql);
										pstmt.setString(1,stateCodeFrm);
										pstmt.setString(2,stateCodeCust);
										rs = pstmt.executeQuery();
										if(rs.next())
										{
											tranCode = rs.getString("TRAN_CODE");
											System.out.println("tranCode===>"+tranCode);
											transMod = rs.getString("TRANS_MODE");
											maxWeight = rs.getString("MAX_WEIGHT");
											locType = rs.getString("LOC_TYPE");
										}
										if( rs != null )
										{
											rs.close();
											rs = null;
										}
										if( pstmt != null )
										{
											pstmt.close();
											pstmt = null;
										}


									}
									if( rs != null )
									{
										rs.close();
										rs = null;
									}
									if( pstmt != null )
									{
										pstmt.close();
										pstmt = null;
									}

								}
								if( rs != null )
								{
									rs.close();
									rs = null;
								}
								if( pstmt != null )
								{
									pstmt.close();
									pstmt = null;
								}

							}
							if( rs != null )
							{
								rs.close();
								rs = null;
							}
							if( pstmt != null )
							{
								pstmt.close();
								pstmt = null;
							}

						}
						if( rs != null )
						{
							rs.close();
							rs = null;
						}
						if( pstmt != null )
						{
							pstmt.close();
							pstmt = null;
						}

					}
				}
				*/
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}



			}
			//Changed by Rohan on 30/06/12.end
			transInfoMap.put("TRAN_CODE", tranCode);
			transInfoMap.put("TRANS_MODE", transMod);
			transInfoMap.put("MAX_WEIGHT", maxWeight);
			transInfoMap.put("LOC_TYPE", locType);
			transInfoMap.put("CUST_CODE_DLV", custCodeDlv);

			if( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}

		}
		catch(Exception e)
		{
			System.out.println("Exception in  == >"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch (Exception e1)
			{
				throw new ITMException(e1);
			}
		}
		return transInfoMap;	
	}
	
	//Changed By Pragyan 25/02/12 To implement changed parcel picking logic.start
	private HashMap getTransporterInfoMap(String saleOrder,double perShipWeight ,double noArt,String pickType , String shipType ,Connection conn) throws ITMException
	{
		String sql = "";
		String sql1 = "";
		String sqlShipStanCode = "";
		//Changed by Rohan on 30/06/12
		String sqlCust = "";
		ResultSet rs = null;
		ResultSet rs1 = null;
		PreparedStatement pstmt = null;
		HashMap transInfoMap = new HashMap();
		String stanCodeFrm = "",stateCodeFrm = "",siteCodeShip = "",stanCodeCust= "",custCodeDlv = "",stateCodeCust ="";
		String tranCode = "",transMod= "",maxWeight= "",locType= "";
		String pinTo = "",pinFrm = "";
		HashMap stationInfoMap = null;
		String dbShipType = "";

		try
		{
			HashMap sordMap = getSordInfo(saleOrder,conn);
			siteCodeShip = (String)sordMap.get("SHIP_CODE");
			stanCodeCust = (String)sordMap.get("STAN_CODE");
			custCodeDlv = (String)sordMap.get("CUST_CODE");
			stateCodeCust = (String)sordMap.get("STATE_DLV");
			stationInfoMap = getStanCodeInfo(siteCodeShip, conn);
			stanCodeFrm = (String)stationInfoMap.get("STAN_CODE");
			stateCodeFrm = (String)stationInfoMap.get("STATE_CODE");
			pinFrm = getPinSite(siteCodeShip,conn); 
			pinTo = getPinCust(custCodeDlv,conn);
			
			if(("P".equalsIgnoreCase(pickType) && "P".equalsIgnoreCase(shipType)) || ("M".equalsIgnoreCase(pickType) && "M".equalsIgnoreCase(shipType)) )//|| "".equalsIgnoreCase(shipType) || "L".equalsIgnoreCase(shipType))
			{
				System.out.println("Sql Check 1 .............pickType["+pickType+"]shipType["+shipType+"]");
				sql =  " SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE,A.SHIP_TYPE FROM DISTROUTEDET A,DISTROUTE B "  
					  + " WHERE ( A.PIN__FR =  ?  OR A.PIN__FR = ' ' ) AND (A.PIN__TO = ?  OR   A.PIN__TO = ' ') AND (A.STAN_CODE__FR  =?  OR A.STAN_CODE__FR  = ' ' ) " 
					  + " AND ( A.STAN_CODE__TO =?   OR A.STAN_CODE__TO = ' ')  AND ( A.STATE_CODE__FR  = ?   OR A.STATE_CODE__FR  = ' ') "
					  + " AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' )  AND A.DIST_ROUTE = B.DIST_ROUTE AND B.CUST_CODE = ? AND SHIP_TYPE = ? ";
					  //+	" AND MIN_WEIGHT <= ? AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ?  AND SHIP_TYPE = ?";
			}
			else if(("P".equalsIgnoreCase(pickType) && "A".equalsIgnoreCase(shipType)) || ("M".equalsIgnoreCase(pickType) && "A".equalsIgnoreCase(shipType)) ||  "".equalsIgnoreCase(shipType) || "L".equalsIgnoreCase(shipType))
			{
				System.out.println("Sql Check 2 .............pickType["+pickType+"]shipType["+shipType+"]");
				sql =  " SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE,A.SHIP_TYPE FROM DISTROUTEDET A,DISTROUTE B "
					  + " WHERE ( A.PIN__FR =  ?  OR A.PIN__FR = ' ' ) AND (A.PIN__TO = ?  OR   A.PIN__TO = ' ') AND (A.STAN_CODE__FR  =?  OR A.STAN_CODE__FR  = ' ' ) " 
					  + " AND ( A.STAN_CODE__TO =?   OR A.STAN_CODE__TO = ' ')  AND ( A.STATE_CODE__FR  = ?   OR A.STATE_CODE__FR  = ' ') "
					  + " AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' )  AND A.DIST_ROUTE = B.DIST_ROUTE AND B.CUST_CODE = ?"
					  +	" AND MIN_WEIGHT <= ? AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ?  AND SHIP_TYPE = ?";
			}
			else
			{
				System.out.println("Sql Check 3 .............pickType["+pickType+"]shipType["+shipType+"]");
			
				sql =  " SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE,A.SHIP_TYPE FROM DISTROUTEDET A,DISTROUTE B "
					  + " WHERE ( A.PIN__FR =  ?  OR A.PIN__FR = ' ' ) AND (A.PIN__TO = ?  OR   A.PIN__TO = ' ') AND (A.STAN_CODE__FR  =?  OR A.STAN_CODE__FR  = ' ' ) " 
					  + " AND ( A.STAN_CODE__TO =?   OR A.STAN_CODE__TO = ' ')  AND ( A.STATE_CODE__FR  = ?   OR A.STATE_CODE__FR  = ' ') "
					  + " AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' )  AND A.DIST_ROUTE = B.DIST_ROUTE AND B.CUST_CODE = ?  "
					  +	" AND MIN_WEIGHT <= ? AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE NOT IN ('M','P')";
			}
					
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,pinFrm);
			pstmt.setString(2,pinTo);
			pstmt.setString(3,stanCodeFrm);
			pstmt.setString(4,stanCodeCust);
			pstmt.setString(5,stateCodeFrm);
			pstmt.setString(6,stateCodeCust);
			pstmt.setString(7,custCodeDlv);
			/*pstmt.setDouble(8,perShipWeight);
			pstmt.setDouble(9,perShipWeight);
			pstmt.setDouble(10,noArt);
			pstmt.setDouble(11,noArt);*/
			
			if(("P".equalsIgnoreCase(pickType) && "P".equalsIgnoreCase(shipType)) || ("M".equalsIgnoreCase(pickType) && "M".equalsIgnoreCase(shipType)))
			{
				System.out.println("Start Check 1 .............pickType["+pickType+"]shipType["+shipType+"]");
				pstmt.setString(8,shipType);
			}
			else if(("P".equalsIgnoreCase(pickType) && "A".equalsIgnoreCase(shipType)) || ("M".equalsIgnoreCase(pickType) && "A".equalsIgnoreCase(shipType)))
			{
				System.out.println("Start Check 2 .............pickType["+pickType+"]shipType["+shipType+"]");
				pstmt.setDouble(8,perShipWeight);
				pstmt.setDouble(9,perShipWeight);
				pstmt.setDouble(10,noArt);
				pstmt.setDouble(11,noArt);
				pstmt.setString(12,pickType);
			}
			else if ("".equalsIgnoreCase(shipType) || "L".equalsIgnoreCase(shipType))
			{
				System.out.println("Start Check 3 .............pickType["+pickType+"]shipType["+shipType+"]");
				pstmt.setDouble(8,perShipWeight);
				pstmt.setDouble(9,perShipWeight);
				pstmt.setDouble(10,noArt);
				pstmt.setDouble(11,noArt);
				pstmt.setString(12,"L");
			}	
			else
			{
				System.out.println("Start Check 4 .............pickType["+pickType+"]shipType["+shipType+"]");
				pstmt.setDouble(8,perShipWeight);
				pstmt.setDouble(9,perShipWeight);
				pstmt.setDouble(10,noArt);
				pstmt.setDouble(11,noArt);
			}
			
			rs = pstmt.executeQuery();

			if(rs.next())
			{
				
				System.out.println("Block In If Rs.............");
				tranCode = rs.getString("TRAN_CODE");
				System.out.println("tranCode===>"+tranCode);
				transMod = rs.getString("TRANS_MODE");
				maxWeight = rs.getString("MAX_WEIGHT");
				locType = rs.getString("LOC_TYPE");
				dbShipType = checkNull(rs.getString("SHIP_TYPE"));
			}
			else if(("P".equalsIgnoreCase(pickType) && "A".equalsIgnoreCase(shipType)) || ("M".equalsIgnoreCase(pickType) && "A".equalsIgnoreCase(shipType)))
			{
				System.out.println("Block In else If .............");
				pstmt.close();
				pstmt = null;
				rs.close();
				rs = null;
				
				sql =  " SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE,A.SHIP_TYPE FROM DISTROUTEDET A,DISTROUTE B "
					  + " WHERE ( A.PIN__FR =  ?  OR A.PIN__FR = ' ' ) AND (A.PIN__TO = ?  OR   A.PIN__TO = ' ') AND (A.STAN_CODE__FR  =?  OR A.STAN_CODE__FR  = ' ' ) " 
					  + " AND ( A.STAN_CODE__TO =?   OR A.STAN_CODE__TO = ' ')  AND ( A.STATE_CODE__FR  = ?   OR A.STATE_CODE__FR  = ' ') "
					  + " AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' ) AND A.DIST_ROUTE = B.DIST_ROUTE AND MIN_WEIGHT <= ? "
					  +	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE= ? ";
				
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,pinFrm);
				pstmt.setString(2,pinTo);
				pstmt.setString(3,stanCodeFrm);
				pstmt.setString(4,stanCodeCust);
				pstmt.setString(5,stateCodeFrm);
				pstmt.setString(6,stateCodeCust);
				pstmt.setDouble(7,perShipWeight);
				pstmt.setDouble(8,perShipWeight);
				pstmt.setDouble(9,noArt);
				pstmt.setDouble(10,noArt);
				pstmt.setString(11,pickType);
				
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					System.out.println("Block In else If found rs.............");
					
					tranCode = rs.getString("TRAN_CODE");
					System.out.println("tranCode===>"+tranCode);
					transMod = rs.getString("TRANS_MODE");
					maxWeight = rs.getString("MAX_WEIGHT");
					locType = rs.getString("LOC_TYPE");
					dbShipType = checkNull(rs.getString("SHIP_TYPE"));
				}
				else
				{
					System.out.println("Block In else If found else .............");
					
					pstmt.close();
					pstmt = null;
					rs.close();
					rs = null;
					
					sql =  " SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE,A.SHIP_TYPE FROM DISTROUTEDET A,DISTROUTE B "
						  + " WHERE ( A.PIN__FR =  ?  OR A.PIN__FR = ' ' ) AND (A.PIN__TO = ?  OR   A.PIN__TO = ' ') AND (A.STAN_CODE__FR  =?  OR A.STAN_CODE__FR  = ' ' ) " 
						  + " AND ( A.STAN_CODE__TO =?   OR A.STAN_CODE__TO = ' ')  AND ( A.STATE_CODE__FR  = ?   OR A.STATE_CODE__FR  = ' ') "
						  + " AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' )  AND A.DIST_ROUTE = B.DIST_ROUTE AND B.CUST_CODE = ?  "
						  +	" AND MIN_WEIGHT <= ? AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE NOT IN ('M','P')";
					
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1,pinFrm);
					pstmt.setString(2,pinTo);
					pstmt.setString(3,stanCodeFrm);
					pstmt.setString(4,stanCodeCust);
					pstmt.setString(5,stateCodeFrm);
					pstmt.setString(6,stateCodeCust);
					pstmt.setString(7,custCodeDlv);
					pstmt.setDouble(8,perShipWeight);
					pstmt.setDouble(9,perShipWeight);
					pstmt.setDouble(10,noArt);
					pstmt.setDouble(11,noArt);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						System.out.println("Block In else If found else rs.............");
						tranCode = rs.getString("TRAN_CODE");
						System.out.println("tranCode===>"+tranCode);
						transMod = rs.getString("TRANS_MODE");
						maxWeight = rs.getString("MAX_WEIGHT");
						locType = rs.getString("LOC_TYPE");
						dbShipType = checkNull(rs.getString("SHIP_TYPE"));
					}
					else
					{
						System.out.println("Block In else If found else rs else.............");
						pstmt.close();
						pstmt = null;
						rs.close();
						rs = null;
						
						sql =  " SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE,A.SHIP_TYPE FROM DISTROUTEDET A,DISTROUTE B "
							  + " WHERE ( A.PIN__FR =  ?  OR A.PIN__FR = ' ' ) AND (A.PIN__TO = ?  OR   A.PIN__TO = ' ') AND (A.STAN_CODE__FR  =?  OR A.STAN_CODE__FR  = ' ' ) " 
							  + " AND ( A.STAN_CODE__TO =?   OR A.STAN_CODE__TO = ' ')  AND ( A.STATE_CODE__FR  = ?   OR A.STATE_CODE__FR  = ' ') "
							  + " AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' ) AND A.DIST_ROUTE = B.DIST_ROUTE AND MIN_WEIGHT <= ? "
							  +	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE NOT IN ('M','P')";
						
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1,pinFrm);
						pstmt.setString(2,pinTo);
						pstmt.setString(3,stanCodeFrm);
						pstmt.setString(4,stanCodeCust);
						pstmt.setString(5,stateCodeFrm);
						pstmt.setString(6,stateCodeCust);
						pstmt.setDouble(7,perShipWeight);
						pstmt.setDouble(8,perShipWeight);
						pstmt.setDouble(9,noArt);
						pstmt.setDouble(10,noArt);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							tranCode = rs.getString("TRAN_CODE");
							System.out.println("tranCode===>"+tranCode);
							transMod = rs.getString("TRANS_MODE");
							maxWeight = rs.getString("MAX_WEIGHT");
							locType = rs.getString("LOC_TYPE");
							dbShipType = checkNull(rs.getString("SHIP_TYPE"));
						}
						
						pstmt.close();
						pstmt = null;
						rs.close();
						rs = null;
						
					}

				}

			}	
			else
			{
				
				System.out.println("Block In else .............");
				pstmt.close();
				pstmt = null;
				rs.close();
				rs = null;
				
				if(("P".equalsIgnoreCase(pickType) && "P".equalsIgnoreCase(shipType)) || ("M".equalsIgnoreCase(pickType) && "M".equalsIgnoreCase(shipType)) || "".equalsIgnoreCase(shipType) || "L".equalsIgnoreCase(shipType))
				{

					sql =  " SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE,A.SHIP_TYPE FROM DISTROUTEDET A,DISTROUTE B "
							  + " WHERE ( A.PIN__FR =  ?  OR A.PIN__FR = ' ' ) AND (A.PIN__TO = ?  OR   A.PIN__TO = ' ') AND (A.STAN_CODE__FR  =?  OR A.STAN_CODE__FR  = ' ' ) " 
							  + " AND ( A.STAN_CODE__TO =?   OR A.STAN_CODE__TO = ' ')  AND ( A.STATE_CODE__FR  = ?   OR A.STATE_CODE__FR  = ' ') "
							  + " AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' ) AND A.DIST_ROUTE = B.DIST_ROUTE AND SHIP_TYPE = ? ";
				}
				else if ("".equalsIgnoreCase(shipType) || "L".equalsIgnoreCase(shipType))
				{
					sql =  " SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE,A.SHIP_TYPE FROM DISTROUTEDET A,DISTROUTE B "
						  + " WHERE ( A.PIN__FR =  ?  OR A.PIN__FR = ' ' ) AND (A.PIN__TO = ?  OR   A.PIN__TO = ' ') AND (A.STAN_CODE__FR  =?  OR A.STAN_CODE__FR  = ' ' ) " 
						  + " WHERE ( A.PIN__FR >=  ?  OR A.PIN__FR = ' ' ) AND (A.PIN__TO <= ?  OR   A.PIN__TO = ' ') AND (A.STAN_CODE__FR  =?  OR A.STAN_CODE__FR  = ' ' ) "
						  + " AND ( A.STAN_CODE__TO =?   OR A.STAN_CODE__TO = ' ')  AND ( A.STATE_CODE__FR  = ?   OR A.STATE_CODE__FR  = ' ') "
						  + " AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' ) AND A.DIST_ROUTE = B.DIST_ROUTE AND MIN_WEIGHT <= ? "
						  +	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE = ?";
				}
				else
				{
					sql =  " SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE,A.SHIP_TYPE FROM DISTROUTEDET A,DISTROUTE B "
						  + " WHERE ( A.PIN__FR =  ?  OR A.PIN__FR = ' ' ) AND (A.PIN__TO = ?  OR   A.PIN__TO = ' ') AND (A.STAN_CODE__FR  =?  OR A.STAN_CODE__FR  = ' ' ) " 
						  + " AND ( A.STAN_CODE__TO =?   OR A.STAN_CODE__TO = ' ')  AND ( A.STATE_CODE__FR  = ?   OR A.STATE_CODE__FR  = ' ') "
						  + " AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' ) AND A.DIST_ROUTE = B.DIST_ROUTE AND MIN_WEIGHT <= ? "
						  //+	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ?";
						  +	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE NOT IN ('M','P')";
				}
				
				
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,pinFrm);
				pstmt.setString(2,pinTo);
				pstmt.setString(3,stanCodeFrm);
				pstmt.setString(4,stanCodeCust);
				pstmt.setString(5,stateCodeFrm);
				pstmt.setString(6,stateCodeCust);
				/*pstmt.setDouble(7,perShipWeight);
				pstmt.setDouble(8,perShipWeight);
				pstmt.setDouble(9,noArt);
				pstmt.setDouble(10,noArt);*/
				
				if(("P".equalsIgnoreCase(pickType) && "P".equalsIgnoreCase(shipType)) || ("M".equalsIgnoreCase(pickType) && "M".equalsIgnoreCase(shipType)) || "".equalsIgnoreCase(shipType) || "L".equalsIgnoreCase(shipType))
				{
					pstmt.setString(7,shipType);
				}
				else if ("".equalsIgnoreCase(shipType) || "L".equalsIgnoreCase(shipType))
				{
					pstmt.setDouble(7,perShipWeight);
					pstmt.setDouble(8,perShipWeight);
					pstmt.setDouble(9,noArt);
					pstmt.setDouble(10,noArt);
					pstmt.setString(11,"L");
				}
				else
				{
				
					pstmt.setDouble(7,perShipWeight);
					pstmt.setDouble(8,perShipWeight);
					pstmt.setDouble(9,noArt);
					pstmt.setDouble(10,noArt);
					
				}
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					System.out.println("Block In else rs.............");
					tranCode = rs.getString("TRAN_CODE");
					System.out.println("tranCode===>"+tranCode);
					transMod = rs.getString("TRANS_MODE");
					maxWeight = rs.getString("MAX_WEIGHT");
					locType = rs.getString("LOC_TYPE");
					dbShipType = checkNull(rs.getString("SHIP_TYPE"));
				}
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			//Changed by Rohan on 30/06/12.end
			transInfoMap.put("TRAN_CODE", tranCode);
			transInfoMap.put("TRANS_MODE", transMod);
			transInfoMap.put("MAX_WEIGHT", maxWeight);
			transInfoMap.put("LOC_TYPE", locType);
			transInfoMap.put("CUST_CODE_DLV", custCodeDlv);
			transInfoMap.put("SHIP_TYPE", dbShipType);

			if( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}

		}
		catch(Exception e)
		{
			System.out.println("Exception in  == >"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch (Exception e1)
			{
				throw new ITMException(e1);
			}
		}
		return transInfoMap;	
	}
	//Changed By Pragyan 25/02/12 To implement changed parcel picking logic.end	
	
	private HashMap getSordInfo(String saleOrder,Connection conn) throws ITMException
	{
		String sql = "";
		ResultSet rs = null;

		PreparedStatement pstmt = null;
		HashMap sordInfoMap = new HashMap();
		String custCode = "",stanCode = "",siteCodeShip = "",stateCodeDlv = "",shipConsGrp = "";
		
		try
		{
									
			//Changed By Pragyan To get customer ship consigee group
			/*sql = "SELECT C.CUST_CODE AS CUST_CODE,C.STAN_CODE AS STAN_CODE,S.SITE_CODE__SHIP AS SHIP_CODE,C.STATE_CODE AS STATE_DLV  FROM SORDER S,CUSTOMER C "
				+ " WHERE S.CUST_CODE__DLV = C.CUST_CODE "
				+ " AND S.SALE_ORDER = ? ";*/
			sql = "SELECT C.CUST_CODE AS CUST_CODE,C.STAN_CODE AS STAN_CODE,S.SITE_CODE__SHIP AS SHIP_CODE,C.STATE_CODE AS STATE_DLV,C.SHIP_CONS_GRP AS  SHIP_CONS_GRP FROM SORDER S,CUSTOMER C "
				+ " WHERE S.CUST_CODE__DLV = C.CUST_CODE "
				+ " AND S.SALE_ORDER = ? ";
	
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,saleOrder);
			rs = pstmt.executeQuery();
			
			if(rs.next())
			{
				custCode = rs.getString("CUST_CODE");
				stanCode = rs.getString("STAN_CODE");
				siteCodeShip = rs.getString("SHIP_CODE");
				stateCodeDlv = rs.getString("STATE_DLV");
				shipConsGrp = rs.getString("SHIP_CONS_GRP");
			}
			
			sordInfoMap.put("CUST_CODE", custCode);
			sordInfoMap.put("STAN_CODE", stanCode);
			sordInfoMap.put("SHIP_CODE", siteCodeShip);
			sordInfoMap.put("STATE_DLV", stateCodeDlv);
			
			if(shipConsGrp != null && shipConsGrp.length() > 0 )
			{
				sordInfoMap.put("SHIP_CONS_GRP", shipConsGrp);
			}
			else
			{
				sordInfoMap.put("SHIP_CONS_GRP", custCode);
			}
		
			
			if( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
		
		}
		catch(Exception e)
		{
			System.out.println("Exception in  == >"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch (Exception e1)
			{
				throw new ITMException(e1);
			}
		}
	 return sordInfoMap;	
	}
	
	
	private String getDocLoc(String tranCode,Connection conn) throws ITMException
	{
		String sql = "";
		String sqlShipStanCode = "";
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		String docLoc = "";
				
		try
		{
										
			
			sql = "SELECT A.LOC_CODE__DOCK AS DOC_LOC FROM TRANSPORTER A "
				+ " WHERE A.TRAN_CODE = ? ";
				
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranCode);
			rs = pstmt.executeQuery();

			while (rs.next())
			{
				docLoc  = rs.getString("DOC_LOC");
			}
			
			if( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
		
		}
		catch(Exception e)
		{
			System.out.println("Exception in  == >"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch (Exception e1)
			{
				throw new ITMException(e1);
			}
		}
	 return docLoc;	
	}
	
	private HashMap getStanCodeInfo(String siteCodeShip,Connection conn) throws ITMException
	{
		String sql = "";
		String sqlShipStanCode = "";
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		String strShipStanCode = "",strStateCodeShip = "";
		HashMap stationMap = new HashMap();
		try
		{
										
			
			sql = "SELECT A.STAN_CODE AS STAN_CODE,A.STATE_CODE AS STATE_CODE  FROM SITE A,STATION B "
				+ " WHERE A.STAN_CODE = B.STAN_CODE "
				+ " AND A.SITE_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, siteCodeShip);
			rs = pstmt.executeQuery();

			while (rs.next())
			{
				strShipStanCode  = rs.getString("STAN_CODE");
				strStateCodeShip = rs.getString("STATE_CODE");
			}
			
			if( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			stationMap.put("STAN_CODE",strShipStanCode);
			stationMap.put("STATE_CODE",strStateCodeShip);
			
		
		}
		catch(Exception e)
		{
			System.out.println("Exception in  == >"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch (Exception e1)
			{
				throw new ITMException(e1);
			}
		}
	 return stationMap;	
	}
	//Changed By Pragyan Demo4.End
	
	private String getPartQuantityAllowed(String sorderNo,Connection conn) throws ITMException
	{
		String sql = "";
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		String partQty = "";
		
		try
		{
										
			
			sql = "SELECT PART_QTY FROM SORDER"
				+ " WHERE SALE_ORDER = ?";
				
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, sorderNo);
			rs = pstmt.executeQuery();

			while (rs.next())
			{
				partQty  = rs.getString("PART_QTY");
			}
			
			if( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
		
		}
		catch(Exception e)
		{
			System.out.println("Exception in  == >"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch (Exception e1)
			{
				throw new ITMException(e1);
			}
		}
	 return partQty;	
	}
	//Changed By Sakara to add Reason Description
	//private String updateSorderItemReasonDet(String sorderNo,String lineNo,String partQty,Connection conn) throws ITMException
	private String updateSorderItemReasonDet(String sorderNo,String lineNo,String partQty,String reaseDescr,Connection conn) throws ITMException
	{
		String sql = "";
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		String reasonDetail = "";
		try
		{
			
			//if("1".equalsIgnoreCase(partQty))
			if("0".equalsIgnoreCase(partQty))
			{
				reasonDetail = "Partial Order/Partial qty Not Allowed Part Qty(1)";
			}
			//else if("2".equalsIgnoreCase(partQty))
			else if("1".equalsIgnoreCase(partQty))
			{
				reasonDetail = "Partial qty Not Allowed Part Qty(2)";
			}
			else
			{
				reasonDetail  = reaseDescr;
			}						
			
			sql = "UPDATE SORDITEM SET REAS_DETAIL =  ? "
				+ " WHERE SALE_ORDER = ? AND LINE_NO = ?";
				
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, reasonDetail);
			pstmt.setString(2, sorderNo);
			pstmt.setString(3, lineNo);
			pstmt.executeUpdate();

			if( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			
			//Changed by sumit on 23/08/12 inserting into sorditem_temp for error start.
			sql = "INSERT INTO SORDITEM_TEMP(SALE_ORDER, LINE_NO, REAS_DETAIL, PART_QTY ) VALUES (?,?,?,?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, sorderNo);
			pstmt.setString(2, lineNo);
			pstmt.setString(3, reasonDetail);
			pstmt.setString(4, partQty);
			pstmt.executeUpdate();			
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			//Changed by sumit on 23/08/12 inserting into sorditem_temp for error end.	
		
		}
		catch(Exception e)
		{
			System.out.println("Exception in  == >"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch (Exception e1)
			{
				throw new ITMException(e1);
			}
		}
	 return partQty;	
	}
	//Added by channdi 7-06-2012
	//private String updateShipment(Document headerDom, Document detailDom,String waveID,String saleOrder,String refId,String xtraParams,  Connection conn)throws Exception
	private String validateSorder(Document detailDom,Connection conn) throws ITMException
	{
		String errString="";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		PreparedStatement pstmtSord = null;
		ResultSet rsSord = null;

		int parentNodeListLength = 0;
		NodeList parentNodeList = null;
		Node parentNode = null;
		int childNodeListLength = 0;
		NodeList childNodeList = null;
		Node childNode = null;
		String childNodeName = "";
		
		String saleOrder="",lineNo="",itemCode ="";
		HashMap<String,ArrayList> hMap = new HashMap<String,ArrayList>();
		ArrayList tempList =null;
		ArrayList saleOrderList = new ArrayList();
		String partQty = "",sorder="";
		int ctr =0;
		Integer maxLine=0;
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		HashMap sordItemMap = new HashMap();
		HashMap tempMap = null;
		double allocQty = 0.0;
		double quantity = 0.0;
		double manualAllocQty = 0.0;
		
		String allocFlag = "";
		String sqlSorAlloc = "";
		
		try
		{
			
			sql = "SELECT MAX(LINE_NO) AS MAX FROM SORDITEM WHERE SALE_ORDER = ? " ;
			pstmt = conn.prepareStatement(sql);
			
			sqlSorAlloc = "SELECT QUANTITY FROM SORD_ALLOC_DET WHERE SALE_ORDER = ? AND LINE_NO__SORD = ? ";
			
			
			
			parentNodeList = detailDom.getElementsByTagName("Detail2");
			parentNodeListLength = parentNodeList.getLength(); 
			for (int selectedRow = 0; selectedRow < parentNodeListLength; selectedRow++)
			{
				int count = 0;
				manualAllocQty = 0.0;
				parentNode = parentNodeList.item(selectedRow);
				
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				for (int childRow = 0; childRow < childNodeListLength; childRow++)
				{
					childNode = childNodeList.item(childRow);
					childNodeName = childNode.getNodeName();
							
					if (childNodeName.equals("sale_order"))
					{
						saleOrder = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("line_no"))
					{
						lineNo = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("item_code"))
					{
						itemCode = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("quantity"))
					{
						quantity = Double.parseDouble(childNode.getFirstChild().getNodeValue());
					}
					if (childNodeName.equals("qty_alloc"))
					{
						allocQty = Double.parseDouble(childNode.getFirstChild().getNodeValue());
					}
					if (childNodeName.equals("alloc_flag"))
					{
						if(childNode.getFirstChild() != null)
						{
							allocFlag = checkNull(childNode.getFirstChild().getNodeValue());
						}
						else
						{
							allocFlag = "";
						}
					}
				
					
				} // end of for childNodeListLength
				
				
				if("M".equalsIgnoreCase(allocFlag))
				{
					pstmtSord = conn.prepareStatement(sqlSorAlloc);
					pstmtSord.setString(1, saleOrder);
					pstmtSord.setString(2, lineNo);
					rsSord = pstmtSord.executeQuery();
					
					while(rsSord.next())
					{
						manualAllocQty = manualAllocQty + rsSord.getDouble(1);
					}
					
					allocQty = allocQty + manualAllocQty;
					
					if(pstmtSord != null)
					{
						pstmtSord.close();
						pstmtSord = null;
					}
					
					if(rsSord != null)
					{
						rsSord.close();
						rsSord = null;
					}
					
				}			
				
				System.out.println("*****saleOrder--->"+saleOrder);
				System.out.println("*****lineNo--->"+lineNo);
				System.out.println("*****itemCode--->"+itemCode);
				if(sordItemMap.containsKey(saleOrder))
                {
                   // tempList = (ArrayList)saleOrderWiseMap.get(saleOrder);
					//tempList = (ArrayList)saleOrderWiseMap.get(saleOrder+":"+locType);
					tempList = (ArrayList)sordItemMap.get(saleOrder); //Changes done by chandni 08-06-12(instead of loc_type, loc_type__parent should be selected)
                }
                else
                {
                    tempList  = new ArrayList();
                }
                // populate the map with the stock keys
                tempMap = new HashMap();
                tempMap.put("site_code", siteCode);
                tempMap.put("item_code", itemCode);
                tempMap.put("quantity", quantity);
                tempMap.put("alloc_qty", allocQty);
                tempMap.put("sord_lineNo", lineNo);
                tempList.add(tempMap);
                sordItemMap.put(saleOrder, tempList);
			} 
			
			Set<Map.Entry<String, ArrayList>> set = sordItemMap.entrySet();
		    for (Map.Entry<String, ArrayList> me : set)
		    {
		     	System.out.print("id is:"+me.getKey() + ": ");
		     	System.out.println("value is:"+me.getValue());
				sorder = me.getKey();
				ArrayList finList = me.getValue();
				ctr = finList.size();
				partQty = getPartQuantityAllowed(sorder,conn);
				
				pstmt.setString(1, sorder);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					maxLine  = rs.getInt(1);
				}
				
				System.out.println("partQty::"+partQty);
				/*
				 * if( "2".equalsIgnoreCase(partQty))
						{
							partQtyValue = "Ship Available";
						}
						//Changed 16/01/13 as the Sales Order Value changes 
						//else if ("1".equalsIgnoreCase(partQty))
						else if ("0".equalsIgnoreCase(partQty))
						{
							partQtyValue = "Ship Complete";
						}
						//Changed 16/01/13 as the Sales Order Value changes 
						else if("1".equalsIgnoreCase(partQty))
						//else if("2".equalsIgnoreCase(partQty))
						{
							partQtyValue = "Ship Complete Lines";
						}
				 */
				
				
				//if("1".equalsIgnoreCase(partQty))
				if("0".equalsIgnoreCase(partQty))
				{
					System.out.println("partQty==== ONE ====>");
					System.out.println("maxLine==>"+maxLine+"ctr====>"+ctr);
					if(maxLine != ctr)
					{
						System.out.println("Adding to saleOrderWiseNotAllowList===>"+sorder);
						saleOrderWiseNotAllowList.add(sorder);
					}
					else
					{
						for(int itemCtr = 0;itemCtr <ctr;itemCtr++)
						{
							HashMap map =(HashMap) finList.get(itemCtr);
							String itemMCode = (String)map.get("item_code");
							double itmQty = (Double)map.get("quantity");
							double itmAllocQty = (Double)map.get("alloc_qty");
							String linNoSord = (String)map.get("sord_lineNo");
							System.out.println("itmQty******"+itmQty+"itmAllocQty************"+itmAllocQty);
							if(itmQty != itmAllocQty)
							{
								saleOrderWiseNotAllowList.add(sorder);
								System.out.println("Adding to saleOrderWiseNotAllowList=**********==>"+sorder);
								break;
							}
							
						}
					}
					
				}
				else if("1".equalsIgnoreCase(partQty))
				//else if("2".equalsIgnoreCase(partQty))
				{
					    System.out.println("Value of cctr===>"+ ctr);
					    //Changed by Rohan on 7/6/12 for bug fixing
						//for(int itemCtr = 0;itemCtr <= ctr;itemCtr++)
					    for(int itemCtr = 0;itemCtr < ctr;itemCtr++)
						{
							HashMap map =(HashMap) finList.get(itemCtr);
							String itemMCode = (String)map.get("item_code");
							double itmQty = (Double)map.get("quantity");
							double itmAllocQty = (Double)map.get("alloc_qty");
							String linNoSord = (String)map.get("sord_lineNo");
							System.out.println("itmQty****$$$$**"+itmQty+"itmAllocQty*******$$$$$*****"+itmAllocQty);
							if(itmQty != itmAllocQty)
							{
								//Full Quantity Required sord line item
								saleOrderWisePartialAllowList.add(sorder+":"+linNoSord);
							}

						}
					
				 }
	        }
		    
		    if( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			
			if(pstmtSord != null)
			{
				pstmtSord.close();
				pstmtSord = null;
			}
			
			if(rsSord != null)
			{
				rsSord.close();
				rsSord = null;
			}
		    // end of for map
			//end of for parentNodeListLength 
			/*System.out.println("final maxLine::"+maxLine+"final ctr::"+ctr);
			if (!(maxLine.equals(ctr)))
			{
				errString = itmDBAccessEJB.getErrorString("","VTSOITM","","",conn);
				return errString;
				errString = getError(sorder,"VTSOITM",conn);
				return errString;
			}*/
			
		}//try end
		catch(Exception e)
		{
			System.out.println("Exception in  == >"+e);
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				
				if(pstmtSord != null)
				{
					pstmtSord.close();
					pstmtSord = null;
				}
				
				if(rsSord != null)
				{
					rsSord.close();
					rsSord = null;
				}
			}
			catch (Exception e1)
			{
				errString = e1.getMessage();
				e1.printStackTrace();
				throw new ITMException(e1);
			}
		}
		System.out.println("errString last:::"+errString);
	 return errString;	
	}	
	private  String getError(String saleOrder,String Code,Connection conn)  throws ITMException, Exception
    {
        String mainStr ="";
        
        try
        {
        	String errString = "";
        	errString =  new ITMDBAccessEJB().getErrorString("",Code,"","",conn);
			String begPart = errString.substring(0,errString.indexOf("<message>")+9);
			String endDesc = errString.substring(errString.indexOf("</description>"));
			mainStr= begPart+"Invalid Data"+"</message><description>";
			mainStr= mainStr+"Sale Order ="+saleOrder+""+endDesc;
			System.out.println("mainStr:::::::::::::::::: "+mainStr);
			begPart = null;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            throw new ITMException(e);
        }
        return mainStr;
    }
	private String getPinCust(String custCode,Connection conn) throws ITMException  //method add by Kunal Mandhre on 04/07/12 for get pin as per S Manoharan instruction 
	{
		String sql = "";
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		String pin = "";
		try
		{


			sql = "select pin from customer where cust_code = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,custCode);
			rs = pstmt.executeQuery();

			while (rs.next())
			{
				pin = rs.getString("pin") == null ?"":rs.getString("pin");
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}

		}
		catch(Exception e)
		{
			System.out.println("Exception in  == >"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				throw new ITMException(e);
			}
		}
		return pin;	
	}
	private String getPinSite(String siteCode,Connection conn) throws ITMException  //method add by Kunal Mandhre on 04/07/12 for get pin as per S Manoharan instruction 
	{
		String sql = "";
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		String pin = "";
		try
		{


			sql = "select pin from site where site_code = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,siteCode);
			rs = pstmt.executeQuery();

			while (rs.next())
			{
				pin = rs.getString("pin") == null ?"":rs.getString("pin");
			}
			
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}

		}
		catch(Exception e)
		{
			System.out.println("Exception in  == >"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return pin;	
	}
	//Changed by Rohan on 06-02-13 for not considering sSQL in case of  checkForReplenishment
	private String checkForReplenishment(String itemCode,String siteCode,String lotNo,String lotSl,String locCode,Double quantity,int flag,Connection conn) throws ITMException
	{
		String returnString="Y";
		ArrayList tempItemInfoList =new ArrayList();
		System.out.println("@@@@ checkForReplenishment for item code :[ "+itemCode+" ] site code :[ "+siteCode+" ] loc code :[ "+locCode+" lot no :[ "+lotNo+" ] lot sl :[ "+lotSl+" ] quantity :[ "+quantity+" ] flag:[ "+flag+" ]");
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		String sSQL = "SELECT REPL_ORDER , LINE_NO ,LOC_CODE__TO FROM REPL_ORD_DET WHERE PICK_ORDER  = ? AND LINE_NO__PICK = ? ";
		//Changed by Rohan on 06-02-13 for checking location instat.start
		String sqlInv = "SELECT INV_STAT FROM LOCATION WHERE LOC_CODE = ? ";
		String invStat = "";
		String invReserve  = discommon.getDisparams("999999","RESERV_LOCATION",conn);
		//Changed by Rohan on 06-02-13 for checking location instat.end
		try {
			if(itemInfoMapForRepl !=null || itemInfoMapForRepl.size() > 0)
			{
				System.out.println("@@@@ itemInfoMapForRepl inside checkForReplenishment :[ "+itemInfoMapForRepl.toString()+" ]" );
				switch (flag) 
				{
					case 1:
					{	
						System.out.println("@@@@ inside case 1");
						if(itemInfoMapForRepl.containsKey(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode))
						{
							tempItemInfoList = (ArrayList) itemInfoMapForRepl.get(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode);
							
							Iterator itemIterator= tempItemInfoList.iterator();
							
							while(itemIterator.hasNext())
							{
			
							    HashMap itemSitemap = (HashMap)itemIterator.next(); 
							    System.out.print( "itemSitemap:["+itemSitemap.toString()+"]");
							    double availQty = 0.0;
							    double actulaQty = 0.0;
							    if(itemSitemap.containsKey("QTY_AVAIL"))
							    {
							    	availQty= (Double)itemSitemap.get("QTY_AVAIL");
							    }
							    
							    if(itemSitemap.containsKey("QTY_ACTUAL"))
							    {
							    	actulaQty= (Double)itemSitemap.get("QTY_ACTUAL");
							    }
							    
							    System.out.println("availQty:[ "+availQty+" ] actulaQty:[ "+actulaQty+" ] quantity :[ "+quantity+" ]");
							    if(actulaQty >= quantity)
							    {
							        returnString ="N";
								}
							    else	
							    {
							    	returnString="Y";
								}
							}
						}
						else
						{
							returnString="Y";
						}
					}
					break;
					
					case 2:
					{
						System.out.println("@@@@ inside case 2*****************");
						
						if(itemInfoMapForRepl.containsKey(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode))
						{
							tempItemInfoList = (ArrayList) itemInfoMapForRepl.get(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode);
							
							Iterator itemIterator= tempItemInfoList.iterator();
							
							while(itemIterator.hasNext())
							{
			
							    HashMap itemSitemap = (HashMap)itemIterator.next(); 
							    //System.out.print( "element:["+element+"]");
							    double availQty = 0.0;
							    double actulaQty = 0.0;
							    //Chnged by Rohan on 8/7/12
							    double stockQuantity = 0.0;
							    String replID="",replLocTo="",pickOrd = "";
							    int replLineNo=0,pickLineNo = 0;
							    if(itemSitemap.containsKey("QTY_AVAIL"))
							    {
							    	availQty= (Double)itemSitemap.get("QTY_AVAIL");
							    }
							    
							    if(itemSitemap.containsKey("QTY_ACTUAL"))
							    {
							    	actulaQty= (Double)itemSitemap.get("QTY_ACTUAL");
							    }
							    if(itemSitemap.containsKey("LAST_REPL_ID"))
							    {
							    	replID= (String)itemSitemap.get("LAST_REPL_ID");
							    	System.out.println("LAST_REPL_ID&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"+replID);
							    }
							    if(itemSitemap.containsKey("REPL_LOC_TO"))
							    {
							    	replLocTo= (String)itemSitemap.get("REPL_LOC_TO");
							    	System.out.println("replLocTo&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"+replLocTo);
							    }
							    if(itemSitemap.containsKey("REPL_LINE_NO")){
							    	replLineNo=(Integer)itemSitemap.get("REPL_LINE_NO");
							    }
							    if(itemSitemap.containsKey("STOCK_QTY"))
							    {
							    	stockQuantity =(Double)itemSitemap.get("STOCK_QTY");
							    }
							    if(itemSitemap.containsKey("PICK_ORD"))
							    {
							    	pickOrd =(String)itemSitemap.get("PICK_ORD");
							    	
							    } 
							    if(itemSitemap.containsKey("LINE_NO_PICK"))
							    {
							    	pickLineNo =(Integer)itemSitemap.get("LINE_NO_PICK");
							    }
							    
							    //Changed by Rohan on 06-02-13 for checking location instat.start
							    pstmt = conn.prepareStatement(sqlInv);
								pstmt.setString(1,locCode);
								rs = pstmt.executeQuery();
								if(rs.next())
								{
									invStat = rs.getString("INV_STAT");
								}
								if(pstmt != null)
								{
									pstmt.close();
									pstmt = null;
								}
								if(rs != null)
								{
									rs.close();
									rs =null;
								}
								pickOrd = pickOrd !=null && pickOrd.length() > 0?pickOrd:"0";
								System.out.println("Pick Order"+pickOrd);
								if(!invStat.trim().equalsIgnoreCase(invReserve))
								{
								//Changed by Rohan on 06-02-13 for checking location instat.start 
									//Change by Rohna on 11-02-13 for bug fixing
									//pickOrd = pickOrd !=null && pickOrd.length() > 0?pickOrd:"0";
								    if(pickOrd.equalsIgnoreCase("0") && replID != null && replID.length() > 0)
								    {
								    	pstmt = conn.prepareStatement(sSQL);
										pstmt.setString(1,replID);
										pstmt.setInt(2,replLineNo);
										rs = pstmt.executeQuery();
	
										while (rs.next())
										{
											pickOrd = rs.getString(1); 
											pickOrd = pickOrd !=null && pickOrd.length() > 0?pickOrd:"0";
											pickLineNo = rs.getInt(2); 
											replLocTo = rs.getString(3); 
										}
										
										if(rs != null)
										{
											rs.close();
											rs = null;
										}
										if(pstmt != null)
										{
											pstmt.close();
											pstmt = null;
										}
								    }
								//Changed by Rohan on 06-02-13 for checking location instat   
								}
							    System.out.println("availQty*****:[ "+availQty+" ] actulaQty:[ "+actulaQty+" ] quantity :[ "+quantity+" ]"+"stockQuantity"+stockQuantity+"Pick Ord"+pickOrd+"Pick Line No"+pickLineNo);
							    if(actulaQty >= quantity)
							    {
							    	/*actulaQty -= quantity;
								    itemSitemap.remove("QTY_ATUAL");
								    itemSitemap.put("QTY_ATUAL", actulaQty);*/
							    	returnString ="N:"+replID+":"+replLocTo+":"+String.valueOf(replLineNo)+":"+pickOrd+":"+String.valueOf(pickLineNo);
								    System.out.println("itemInfoMapForRepl after updation :[ "+itemInfoMapForRepl.toString()+" ]");
								    System.out.println("Replenishment returnString inside if : [" +returnString +"]");
								}
							    else	
							    {
							    	/*actulaQty+=availQty;
							    	itemSitemap.remove("QTY_ATUAL");
								    itemSitemap.put("QTY_ATUAL", actulaQty);*/
							    	//Changed by Rohan on 8/7/12 to consider Stock quantity.start
							    	//returnString="Y:"+String.valueOf(availQty);
							    	
							    	if(stockQuantity == availQty)
							    	{
							    		returnString="Y:"+String.valueOf(availQty);
							    	}
							    	else
							    	{
							    		System.out.println("Avail");
							    		availQty = stockQuantity - availQty;
							    		returnString="Y:"+String.valueOf(availQty);
							    	}
							    	//Changed by Rohan on 8/7/12 to consider Stock quantity.end
							    	System.out.println("Replenishment returnString inside else : [" +returnString +"]");
								}
							}
						}
						else
						{
							System.out.println("item does not exist in map ");
							returnString="Y:";
						}
					}
					break;
					
					default:
					break;
				}
					
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ITMException(e);
		}
		
		return returnString;
	}
	
	private double getStockQty(String itemCode,String siteCode,String lotNo,String lotSl,String locCode) throws ITMException
	{
		double stockQuantity = 0.0;
		try
		{
		
			ArrayList tempItemInfoList = null;
			
			if(itemInfoMapForRepl.containsKey(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode))
			{
				tempItemInfoList = (ArrayList) itemInfoMapForRepl.get(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode);
				
				Iterator itemIterator= tempItemInfoList.iterator();
				
				while(itemIterator.hasNext())
				{
					HashMap itemSitemap = (HashMap)itemIterator.next(); 
					 if(itemSitemap.containsKey("STOCK_QTY"))
				    {
				    	stockQuantity =(Double)itemSitemap.get("STOCK_QTY");
				    }
			}
			}
		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		
		return stockQuantity;
	}
	
	/** method populateReplHistory use to update the populate the replenishment record from database and put in the memory(Map) 
	*@param itemCodeHis     			Item code for replenishment.
	*@param siteCodeHis     			Site code for replenishment.
	*@param lotNoHis					Item lot Number.
	*@param lotSlHis					Item lot SL.
	*@param locCodeHis					Stock location of the Item.
	*@param conn						Connection object.  
	*@throws ITMException				throws ItemException. 
	*/
	private void populateReplHistory(String itemCodeHis,String siteCodeHis,String lotNoHis,String lotSlHis,String locCodeHis ,Connection conn) throws ITMException
	{
		PreparedStatement pstmtReplHistory =null; 
		String sqlReplHistory= "";
		ResultSet rsReplHistory =null;
		String replOrderHis="",locCodeToHis="",locCodeRepl = "";
		//Changed by Rohan on 27/07/12.start
		String sqlPnd = "";
		String invState = "";
		String picOrd = "";
		String sqlLoc = "";
		String locCode = "";
		int lineNoPick = 0;
		double stkQty = 0.0;
		PreparedStatement pstmtPnd = null;
		PreparedStatement pstmtLoc = null;
		ResultSet rsPnd = null;
		ResultSet rsLoc = null;
		//Changed by Rohan on 27/07/12.end
		int lineNoReplHis=0;
		double quantityReplHis=0.0,actualQtyReplHis	=0.0;
		boolean isReplanished = false;
		//Changed by Rohan on 28/07/12 to crate list.start
		//Chnaged by Rohan on 10-9-12 to define variable.start
		String sqlAvail = "";
		PreparedStatement pstmtAvail = null;
		ResultSet rspstmtAvail = null;
		String pickType = "";
		String sqlReplHis = "";
		String activePickLoc  = discommon.getDisparams("999999","ACTIVE_PICK_INVSTAT",conn);;
		//Changed by Rohan on 10-9-12 to define variable.end
		
		//Changed by Rohan on 06-02-13 to retrive only case Repalnishment
		String casePickInv  = discommon.getDisparams("999999","CASE_PICK_INVSTAT",conn);
		String pndLoc = discommon.getDisparams("999999","PND_INVSTAT",conn);
		
		ArrayList tempHisList = null;
		
		try {
				
				//Chnaged by Rohan on 28/07/12 to crate list.end
			    //Changed by Rohan on 27/07/12 to move location form caspick location to DOCK location
				//sqlReplHistory= "SELECT REPL_ORDER,QUANTITY,ACTUAL_QTY,LOC_CODE__TO,LINE_NO FROM REPL_ORD_DET WHERE ITEM_CODE =? AND SITE_CODE = ? AND LOT_NO =? AND LOT_SL =? AND LOC_CODE = ?";
				/*sqlReplHistory= "SELECT LOC_CODE,REPL_ORDER,QUANTITY,ACTUAL_QTY,LOC_CODE__TO,LINE_NO,PICK_ORDER,LINE_NO__PICK FROM REPL_ORD_DET"
								//+" WHERE ITEM_CODE =? AND SITE_CODE = ? AND LOT_NO = ? AND LOT_SL = ? AND ACTUAL_QTY >= 0";
						       +" WHERE ITEM_CODE =? AND SITE_CODE = ? AND LOT_NO = ? AND LOT_SL = ? ";*/
			
				//Changed by Rohan on 06-02-13 to retrive only case Repalnishment.start
				/*
			    sqlReplHistory = "SELECT D.LOC_CODE,D.REPL_ORDER,D.QUANTITY,D.ACTUAL_QTY,D.LOC_CODE__TO,D.LINE_NO,D.PICK_ORDER,"
			    				 + " D.LINE_NO__PICK,S.QUANTITY AS STK_QTY FROM REPL_ORD_DET D,STOCK S WHERE D.ITEM_CODE = ? AND "
			    		          +" D.SITE_CODE = ? AND D.LOT_NO = ? AND D.LOT_SL = ?"
								  +" AND D.ITEM_CODE = S.ITEM_CODE AND  D.SITE_CODE =  S.SITE_CODE "
								  +" AND  D.LOT_NO =  S.LOT_NO AND  D.LOT_SL = S.LOT_SL AND D.ACTUAL_QTY > 0";
			    */
			 	//Changed by Rohan on 07-02-13 not consider pnd repanishment in case of active repanishment
				
				sqlReplHistory = "SELECT D.LOC_CODE,D.REPL_ORDER,D.QUANTITY,D.ACTUAL_QTY,D.LOC_CODE__TO,D.LINE_NO,D.PICK_ORDER,"
	        				+ " D.LINE_NO__PICK,S.QUANTITY AS STK_QTY FROM REPL_ORD_DET D,STOCK S ,LOCATION L,REPL_ORD_HDR H WHERE D.ITEM_CODE = ? AND "
	        				+" D.SITE_CODE = ? AND D.LOT_NO = ? AND D.LOT_SL = ?"
	        				+" AND D.ITEM_CODE = S.ITEM_CODE AND  D.SITE_CODE =  S.SITE_CODE "
	        				//Changed by Rohan on 13-02-13 add partial reserv location in map.start
	        				
	        				+" AND  D.LOT_NO =  S.LOT_NO AND  D.LOT_SL = S.LOT_SL AND D.LOC_CODE__TO = L.LOC_CODE AND L.INV_STAT IN( ?,? ) " 
	        				//Change by Rohan on 19-02-13 to not select cancle repanishment & add stock > 0
	        				//+" AND H.REPL_ORDER = D.REPL_ORDER AND H.ORDER_TYPE NOT IN('Q','T','P','E','I') AND D.ACTUAL_QTY > 0 ";
	        				+" AND CASE WHEN CANCEL_MODE IS NULL THEN 'N' ELSE CANCEL_MODE END <> 'Y'  "
	        				+" AND H.REPL_ORDER = D.REPL_ORDER AND H.ORDER_TYPE NOT IN('Q','T','P','E','I') AND D.ACTUAL_QTY > 0 AND S.QUANTITY > 0 ";
	        				
				//Changed by Rohan on 06-02-13 to retrive only case Repalnishment.end
	        			
				pstmtReplHistory =conn.prepareStatement(sqlReplHistory);
				pstmtReplHistory.setString(1, itemCodeHis);
				pstmtReplHistory.setString(2, siteCodeHis);
				pstmtReplHistory.setString(3, lotNoHis);
				pstmtReplHistory.setString(4, lotSlHis);
				
				//Changed by Rohan on 06-02-13 to retrive only case Repalnishment.start
				pstmtReplHistory.setString(5, casePickInv);
				pstmtReplHistory.setString(6, pndLoc);
				//Changed by Rohan on 06-02-13 to retrve only case Repalnishment.end
				
				rsReplHistory = pstmtReplHistory.executeQuery();
				
				while (rsReplHistory.next())
				{
					isReplanished = true;
					locCodeRepl = rsReplHistory.getString("LOC_CODE");
					replOrderHis=rsReplHistory.getString("REPL_ORDER");
					quantityReplHis= rsReplHistory.getDouble("QUANTITY");
					actualQtyReplHis =rsReplHistory.getDouble("ACTUAL_QTY");
					locCodeToHis=rsReplHistory.getString("LOC_CODE__TO");
					
					System.out.println("locCodeToHis********"+locCodeToHis);
					lineNoReplHis=rsReplHistory.getInt("LINE_NO");
					//Changed by Rohan on 27/07/12 to move location form caspick location to DOCK location
					picOrd = rsReplHistory.getString("PICK_ORDER");
					lineNoPick = rsReplHistory.getInt("LINE_NO__PICK");	
					//Changed by Rohan on 8/7/12 to add stock Quantity in Map
					stkQty = rsReplHistory.getDouble("STK_QTY");
					System.out.println("stkQty@@@@@@@@@@@@@@@@@@@@@@@@"+stkQty);
					
					//if(itemInfoMapForRepl.containsKey(itemCodeHis+":"+siteCodeHis+":"+lotNoHis+":"+lotSlHis+":"+locCodeHis))
					if(itemInfoMapForRepl.containsKey(itemCodeHis+":"+siteCodeHis+":"+lotNoHis+":"+lotSlHis+":"+locCodeRepl))
					{
						System.out.println("No!!!! This is not possible"+itemInfoMapForRepl.toString());
						//Changed by rohan on 8/1/12
						//continue;
					}
					else
					{
							
						if(isReplanished)
						{
							//Changed by Rohan on 28/07/12
							/*
							ArrayList tempHisList =new ArrayList();
			                */
							tempHisList =new ArrayList();
							HashMap tempHisMap =new HashMap();
			                
							//Changed by Rohan on 27/07/12 to move location form caspick location to DOCK location.start
							//Changed by Rohan on 27/07/12 to move location form caspick location to DOCK location.start
							//if(!activeRepl)
							//{	
								sqlPnd = "SELECT INV_STAT FROM LOCATION WHERE LOC_CODE = ?";
								pstmtPnd =conn.prepareStatement(sqlPnd);
								pstmtPnd.setString(1, locCodeToHis);			
								rsPnd = pstmtPnd.executeQuery();
								if(rsPnd.next())
								{
									invState = rsPnd.getString("INV_STAT");
								}
								pstmtPnd.close();
								pstmtPnd = null;
								rsPnd.close();
								rsPnd = null;
								
								//Changed by Rohan on 10-09-12 tor bug fixing in case of qty available in active.start
								if(invState.equalsIgnoreCase(activePickLoc))
								{
									sqlAvail = "SELECT PICK_TYPE FROM PICK_ORD_HDR WHERE PICK_ORDER IN " 
											+" (SELECT PICK_ORDER FROM REPL_ORD_DET WHERE REPL_ORDER = ?)";
								}
								else
								{	
									//Rohan need To Check further as this query returns more then one row.
									/*sqlAvail = " SELECT PICK_TYPE FROM PICK_ORD_HDR WHERE PICK_ORDER IN "
										   +"(SELECT PICK_ORDER FROM REPL_ORD_DET WHERE REPL_ORDER = " 
										   +" (SELECT PICK_ORDER FROM REPL_ORD_DET WHERE REPL_ORDER = ?))";*/
									sqlAvail = " SELECT PICK_TYPE FROM PICK_ORD_HDR WHERE PICK_ORDER IN "
										   +"(SELECT PICK_ORDER FROM REPL_ORD_DET WHERE REPL_ORDER IN " 
										   +" (SELECT PICK_ORDER FROM REPL_ORD_DET WHERE REPL_ORDER = ?))";
								}	
								pstmtAvail =conn.prepareStatement(sqlAvail);
								pstmtAvail.setString(1, replOrderHis);			
								rspstmtAvail = pstmtAvail.executeQuery();
								if(rspstmtAvail.next())
								{
									pickType = rspstmtAvail.getString("PICK_TYPE");
								}
								
								if(pstmtAvail != null)
								{
									pstmtAvail.close();
									pstmtAvail = null;
								}
								if(rspstmtAvail != null)
								{
									rspstmtAvail.close();
									rspstmtAvail = null;
								}
								
								if("A".equalsIgnoreCase(pickType))
								{
									
									 sqlReplHis = "SELECT SUM(D.QUANTITY) AS QUANTITY "
						    				 + " FROM REPL_ORD_DET D,STOCK S WHERE D.ITEM_CODE = ? AND "
						    		          +" D.SITE_CODE = ? AND D.LOT_NO = ? AND D.LOT_SL = ?"
											  +" AND D.ITEM_CODE = S.ITEM_CODE AND  D.SITE_CODE =  S.SITE_CODE "
											  +" AND  D.LOT_NO =  S.LOT_NO AND  D.LOT_SL = S.LOT_SL AND D.ACTUAL_QTY >= 0";
									 pstmtAvail = conn.prepareStatement(sqlReplHis);
									 pstmtAvail.setString(1, itemCodeHis);
									 pstmtAvail.setString(2, siteCodeHis);
									 pstmtAvail.setString(3, lotNoHis);
									 pstmtAvail.setString(4, lotSlHis);
									 rspstmtAvail = pstmtAvail.executeQuery();
									 if(rspstmtAvail.next())
									 {
										 quantityReplHis = rspstmtAvail.getDouble("QUANTITY");
									 }
										
								}
								if(pstmtAvail != null)
								{
									pstmtAvail.close();
									pstmtAvail = null;
								}
								if(rspstmtAvail != null)
								{
									rspstmtAvail.close();
									rspstmtAvail = null;
								}
								//Changed by Rohan on 10-09-12 tor bug fixing in case of qty available in active.end
								//Changed by Rohan on 27/07/12 to move location form caspick location to DOCK location.end
								tempHisMap.put("QTY_AVAIL",quantityReplHis);
								tempHisMap.put("QTY_ACTUAL", actualQtyReplHis);
								//Changed by Rohan on 06-02-13 to retrive only case Repalnishment.start
								tempHisMap.put("LAST_REPL_ID", replOrderHis);
								//tempHisMap.put("LAST_REPL_ID", picOrd);
								System.out.println("LAST REPL ID"+replOrderHis);
								////Changed by Rohan on 06-02-13 to retrive only case Repalnishment.end
								//Changed by Roha on 27/07/12 to move location form caspick location to DOCK location.start
								//tempHisMap.put("REPL_LOC_TO",locCodeToHis);
								
								//Changed by Rohan on 06-02-13 to retrive only case Repalnishment 
								//if(invState.startsWith("PND"))
								if(invState.equalsIgnoreCase(pndLoc))
								{
									sqlLoc = "SELECT LOC_CODE__TO FROM REPL_ORD_DET WHERE REPL_ORDER = ? AND LINE_NO = ?";
									pstmtLoc =conn.prepareStatement(sqlLoc);
									pstmtLoc.setString(1, picOrd);
									pstmtLoc.setInt(2, lineNoPick);
									rsLoc = pstmtLoc.executeQuery();
									if(rsLoc.next())
									{
										locCode = rsLoc.getString("LOC_CODE__TO");
										System.out.println("locCode**********************"+locCode);
									}
									pstmtLoc.close();
									pstmtLoc = null;
									rsLoc.close();
									rsLoc = null;
									tempHisMap.put("REPL_LOC_TO",locCode);
								}
								else
								{
									tempHisMap.put("REPL_LOC_TO",locCodeToHis);
								}
						   // }
							//Chnged by Rohan on 8/3/12.start
							/*else
							{
								tempHisMap.put("REPL_LOC_TO",locCodeToHis);
								tempHisMap.put("QTY_AVAIL",quantityReplHis);
								tempHisMap.put("QTY_ACTUAL", actualQtyReplHis);
								tempHisMap.put("LAST_REPL_ID", replOrderHis);
							}
							*/
							//Chnged by Rohan on 8/3/12.end
							
							//Changed by Rohan on 27/07/12 to move location form caspick location to DOCK location.start
							tempHisMap.put("REPL_LINE_NO", lineNoReplHis);
							tempHisMap.put("IS_REPLAINSH","N");
							//Changed by Rohan on 8/7/12 to add stock qty in list
							tempHisMap.put("STOCK_QTY",stkQty);
							tempHisMap.put("PICK_ORD",picOrd);
							tempHisMap.put("LINE_NO_PICK",lineNoPick);
							System.out.println("Stock Quantity"+stkQty+"FOR locCodeRepl"+locCodeRepl);
							tempHisList.add(tempHisMap);
							System.out.println("tempHisList$$$$$"+tempHisList);
							System.out.println("itemCodeHis"+itemCodeHis+"]siteCodeHis["+siteCodeHis+"]lotNoHis["+lotNoHis+"]lotSlHis["+lotSlHis+"]locCodeHis["+locCodeHis+"]locCodeRepl["+locCodeRepl);
							//itemInfoMapForRepl.put(itemCodeHis+":"+siteCodeHis+":"+lotNoHis+":"+lotSlHis+":"+locCodeHis, tempHisList);
							itemInfoMapForRepl.put(itemCodeHis+":"+siteCodeHis+":"+lotNoHis+":"+lotSlHis+":"+locCodeRepl, tempHisList);
						}
						
					}
				}
				System.out.println("While loop end");
				
				
				if(pstmtReplHistory != null)
				{
					pstmtReplHistory.close();
					pstmtReplHistory = null;
				}
				if(rsReplHistory != null)
				{
					rsReplHistory.close();
					rsReplHistory = null;
				}
				
				if(pstmtPnd != null)
				{
					pstmtPnd.close();
					pstmtPnd = null;
				}
				if(rsPnd != null)
				{
					rsPnd.close();
					rsPnd = null;
				}
				if(pstmtLoc != null)
				{
					pstmtLoc.close();
					pstmtLoc = null;
				}
				if(rsLoc != null)
				{
					rsLoc.close();
					rsLoc = null;
				}
				System.out.println("Current Map Stored in["+itemInfoMapForRepl.toString()+"]");
				
			}
			catch (Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e) ;
			}
			finally
			{
				
				try
				{
					if(pstmtReplHistory != null)
					{
						pstmtReplHistory.close();
						pstmtReplHistory = null;
					}
					if(rsReplHistory != null)
					{
						rsReplHistory.close();
						rsReplHistory = null;
					}
					
					if(pstmtPnd != null)
					{
						pstmtPnd.close();
						pstmtPnd = null;
					}
					if(rsPnd != null)
					{
						rsPnd.close();
						rsPnd = null;
					}
					if(pstmtLoc != null)
					{
						pstmtLoc.close();
						pstmtLoc = null;
					}
					if(rsLoc != null)
					{
						rsLoc.close();
						rsLoc = null;
					}
				}
				catch(Exception e)
				{
					throw new ITMException(e) ;
				}
			}
		
	}
	
	/** method updateReplenishmentRecord use to update the replenishment record in database as well as in memory(Map) 
	*@param itemCode     			Item code for replenishment done.
	*@param siteCode     			Site code for replenishment.
	*@param lotNo					Item lot Number.
	*@param lotSl					Item lot SL.
	*@param locCode					Stock location of the Item.
	*@param quantity				Alloc quantity (Required Quantity).
	*@param newReplenishmentID 		If replenishment is Yes then used as new replenishment ID otherwise null.
	*@param locCodeTo				To location on which replenishment done.
	*@param lineNo					Replenishment line number from repl_ord_det.
	*@param	flag					If flag=1 then replenishment is true else if flag=2 then replenishment is false.
	*@param conn					Connection object.  
	*@throws ITMException			throws ItemException. 
	*/
	private void updateReplenishmentRecord(String itemCode, String siteCode, String lotNo,String lotSl,String locCode,double quantity,String newReplenishmentID ,String locCodeTo,int lineNo,int flag,double shipperSize,boolean actPick ,Connection conn) throws ITMException
	{
		String returnString="Y";
		ArrayList tempItemInfoList =new ArrayList();
		PreparedStatement pstmtRelenishmentTrue =null,pstmtRelenishmentFalse=null; 
		//Changed by Rohan on 22/08/12 to check manual flag in itemSitemap
		String manualFlag = "N";
		String sqlRelenishmentTrue ="UPDATE REPL_ORD_DET SET ACTUAL_QTY = ? WHERE REPL_ORDER = ?";
		String sqlRelenishmentFalse ="UPDATE REPL_ORD_DET SET ACTUAL_QTY = ? WHERE REPL_ORDER = ?";
		    
		    
	    
		try 
		{
			
			pstmtRelenishmentTrue = conn.prepareStatement(sqlRelenishmentTrue);
			pstmtRelenishmentFalse = conn.prepareStatement(sqlRelenishmentFalse);
			
			if(itemInfoMapForRepl !=null || itemInfoMapForRepl.size() > 0)
			{
				System.out.println("@@@@ itemInfoMapForRepl inside checkForReplenishment :[ "+itemInfoMapForRepl.toString()+" ]" );
				switch (flag) 
				{
					case 1:
					{	
						System.out.println("@@@@ inside case 1");
						if(itemInfoMapForRepl.containsKey(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode))
						{
							tempItemInfoList = (ArrayList) itemInfoMapForRepl.get(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode);
							
							Iterator itemIterator= tempItemInfoList.iterator();
							
							while(itemIterator.hasNext())
							{
			
							    HashMap itemSitemap = (HashMap)itemIterator.next(); 
							    //System.out.print( "element:["+element+"]");
							    double availQty = 0.0;
							    double actulaQty = 0.0;
							    //Changed by Rohan on 8/7/12 To get Stock Qty
							    double stockQuantity = 0.0;
							    String isReplanish = "";
							    
							    if(itemSitemap.containsKey("QTY_AVAIL"))
							    {
							    	availQty= (Double)itemSitemap.get("QTY_AVAIL");
							    }
							    
							    if(itemSitemap.containsKey("QTY_ACTUAL"))
							    {
							    	actulaQty= (Double)itemSitemap.get("QTY_ACTUAL");
							    }
							    //Changed by Rohan on 8/7/12 To get Stock Qty.start
							    if(itemSitemap.containsKey("IS_REPLAINSH"))
							    {
							    	isReplanish =(String)itemSitemap.get("IS_REPLAINSH");
							    }
							   
						    	if(itemSitemap.containsKey("STOCK_QTY"))
							    {
							    	stockQuantity =(Double)itemSitemap.get("STOCK_QTY");
							    }
						    	//Changed by Rohan on 22/08/12 to check manual flag in itemSitemap.start
						    	if(itemSitemap.containsKey("MANUAL_FLAG_ACTIVE"))
							    {
							    	manualFlag =(String)itemSitemap.get("MANUAL_FLAG_ACTIVE");
							    }
							    //Changed by Rohan on 22/08/12 to check manual flag in itemSitemap.end
							   
							    System.out.println("availQty:[ "+availQty+" ] actulaQty:[ "+actulaQty+" ] quantity :[ "+quantity+" ]"+"stockQuantity@@@@@@@"+stockQuantity);
							    if(actulaQty > quantity)
							    {
							        System.out.println("Wrong Logic Buddy!!!!");
								}
							    else	
							    {
							    	//Changed by Rohna on 8/7/12.start
							    	//actulaQty=actulaQty+availQty-quantity
							    	//Changed by Rohan on 22/08/12 to check manual flag in itemSitemap.start
							    	if("Y".equalsIgnoreCase(manualFlag) && !actPick)
							    	{
							    		
							    		actulaQty = stockQuantity - availQty - quantity;
							    		
							    	}
							    	//if(stockQuantity == availQty || "Y".equalsIgnoreCase(isReplanish))
							    	//Changed by Rohan on 22/08/12 to check manual flag in itemSitemap.end
							    	//Changed by Rohan on 26/08/12 for bug Fixing
							    	//else if(stockQuantity == availQty || "Y".equalsIgnoreCase(isReplanish))
							    	else if(stockQuantity == availQty )	
							    	{
							    		
							    		if(actPick)
							    		{
							    			actulaQty = actulaQty + shipperSize - quantity;
							    		}
							    		else
							    		{
							    			actulaQty = actulaQty+availQty-quantity;
							    		}
							    		
							    	}
							    	else
							    	{
							    		actulaQty = stockQuantity - availQty - quantity;	
							    
							    	}
							    	
							    	//Changed by Rohna on 8/7/12.end
							    	itemSitemap.remove("QTY_ACTUAL");
								    itemSitemap.put("QTY_ACTUAL", actulaQty);
								    itemSitemap.remove("LAST_REPL_ID");
								    itemSitemap.put("LAST_REPL_ID", newReplenishmentID);
								    itemSitemap.remove("REPL_LOC_TO");
								    itemSitemap.put("REPL_LOC_TO", locCodeTo);
								    itemSitemap.remove("REPL_LINE_NO");
								    itemSitemap.put("REPL_LINE_NO", lineNo);
								    
								    
								    pstmtRelenishmentTrue.setDouble(1, actulaQty);
								    pstmtRelenishmentTrue.setString(2, newReplenishmentID);
								    int updateCnt=pstmtRelenishmentTrue.executeUpdate();
								 
								    if(updateCnt>0)
								    {
								    	System.out.println("Hey Replenishment updated with actual quantity "+actulaQty+" For replenishment oder :"+newReplenishmentID +" with loc code to :"+locCodeTo+" and lone no :"+lineNo);
								    }
								    else
								    {
								    	System.out.println("Sorry.... no update ");
								    }
								    
								    pstmtRelenishmentTrue.clearParameters();
								    
								}
							}
						}
						else
						{
							System.out.println("Something is Wrong !!!!");
						}
					}
					break;
					
					case 2:
					{
						System.out.println("@@@@ inside case 2===>"+"itemInfoMapForRepl updating"+itemInfoMapForRepl);
						
						if(itemInfoMapForRepl.containsKey(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode))
						{
							tempItemInfoList = (ArrayList) itemInfoMapForRepl.get(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode);
							
							Iterator itemIterator= tempItemInfoList.iterator();
							
							while(itemIterator.hasNext())
							{
			
							    HashMap itemSitemap = (HashMap)itemIterator.next(); 
							    System.out.print( "itemSitemap:["+itemSitemap.toString()+"]");
							    double availQty = 0.0;
							    double actulaQty = 0.0;
							    String oldReplenishmentID="";
							    if(itemSitemap.containsKey("QTY_AVAIL"))
							    {
							    	availQty= (Double)itemSitemap.get("QTY_AVAIL");
							    }
							    
							    if(itemSitemap.containsKey("QTY_ACTUAL"))
							    {
							    	actulaQty= (Double)itemSitemap.get("QTY_ACTUAL");
							    }
							    if(itemSitemap.containsKey("LAST_REPL_ID"))
							    {
							    	oldReplenishmentID= (String)itemSitemap.get("LAST_REPL_ID");
							    }
							    System.out.println("Quantity pAss"+quantity); 
							    if(actulaQty >= quantity)
							    {
							    	
							    	 System.out.println("Case 2 999availQty:[ "+availQty+" ] actulaQty:[ "+actulaQty+" ] quantity :[ "+quantity+" ]"+"stockQuantity@@@@@@@");
							    	actulaQty -= quantity;
								    itemSitemap.remove("QTY_ACTUAL");
								    System.out.println("Actual qty put in map"+actulaQty);
								    itemSitemap.put("QTY_ACTUAL", actulaQty);
								  
								    pstmtRelenishmentFalse.setDouble(1, actulaQty);
								    pstmtRelenishmentFalse.setString(2, oldReplenishmentID);
								    int updateCnt=pstmtRelenishmentFalse.executeUpdate();
								  
								    if(updateCnt>0)
								    {
								    	System.out.println("Hey Replenishment updated with actual quantity=======**=========> "+actulaQty+" For replenishment oder =====>:"+oldReplenishmentID);
								    }
								    else
								    {
								    	System.out.println("Sorry.... no update ");
								    }
								    System.out.println("itemInfoMapForRepl after updation :[ "+itemInfoMapForRepl.toString()+" ]");
								    
								    pstmtRelenishmentFalse.clearParameters();
								}
							    else	
							    {
							    	System.out.println("Wrong Logic...What are you doing?? ");
								}
							}
						}
						else
						{
							System.out.println("item does not exist in map ");
							returnString="Y:";
						}
					}
					break;
					
					default:
					break;
				}
					
		}
			
		if(pstmtRelenishmentTrue != null)
		{
		   pstmtRelenishmentTrue.close();
		   pstmtRelenishmentTrue=null;
		}
		if(pstmtRelenishmentFalse != null)
		{
		  pstmtRelenishmentFalse.close();
		  pstmtRelenishmentFalse=null;
		}
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(pstmtRelenishmentTrue != null)
				{
				   pstmtRelenishmentTrue.close();
				   pstmtRelenishmentTrue=null;
				}
				if(pstmtRelenishmentFalse != null)
				{
				  pstmtRelenishmentFalse.close();
				  pstmtRelenishmentFalse=null;
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
	}
	
	//Changed by sankara on 03-08-2012 for finding single lot[start]
	//public boolean isSingleLotAllowed(String itemCode,Double pendingQuantity,String siteCode,String custCode,Connection conn) throws Exception
	public boolean isSingleLotAllowed(String itemCode,Double pendingQuantity,String siteCode,String singleLot,Connection conn) throws Exception
	{
		PreparedStatement pstmt=null;
		ResultSet rs = null;
		boolean isSingleLot=false;
		int count=0;
		//String singleLot = "";
		//define verible singleLot
		try
		{
			
			   if(singleLot != null && singleLot.trim().length() > 0 && singleLot.equalsIgnoreCase("Y"))
			   {
					   sql = "SELECT COUNT(*) AS COUNT, LOT_NO FROM STOCK WHERE ITEM_CODE = ? AND SITE_CODE = ? "+
				       "GROUP BY LOT_NO HAVING SUM(QUANTITY - ALLOC_QTY - (CASE WHEN HOLD_QTY IS NULL THEN 0 ELSE STOCK.HOLD_QTY END) ) >= ? ";
				       pstmt =  conn.prepareStatement(sql);
				       pstmt.setString(1, itemCode);
				       pstmt.setString(2, siteCode);
				       pstmt.setDouble(3,pendingQuantity);
				       rs = pstmt.executeQuery();
				       
				       if(rs.next())
				        {
				    	   count = rs.getInt("COUNT");
				        }
				       
				       if(count<=0)
				       {
				    	   return isSingleLot = true;
				       }
			   }
			/*sql= "SELECT  SINGLE_LOT  FROM CUSTOMER WHERE CUST_CODE = ? ";
			pstmt =  conn.prepareStatement(sql);
			pstmt.setString(1, custCode);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
			   singleLot = rs.getString(1);
			   System.out.println("singlelot************"+singleLot);
			   if(singleLot == null)
			   {
				   return isSingleLot;
			   }
			   if(singleLot != null && singleLot.trim().length() > 0 && singleLot.equalsIgnoreCase("Y"))
			   {
					   sql = "SELECT COUNT(*) AS COUNT, LOT_NO FROM STOCK WHERE ITEM_CODE = ? AND SITE_CODE = ? "+
				       "GROUP BY LOT_NO HAVING SUM(QUANTITY - ALLOC_QTY - (CASE WHEN HOLD_QTY IS NULL THEN 0 ELSE STOCK.HOLD_QTY END) ) >= ? ";
				       pstmt =  conn.prepareStatement(sql);
				       pstmt.setString(1, itemCode);
				       pstmt.setString(2, siteCode);
				       pstmt.setDouble(3,pendingQuantity);
				       rs = pstmt.executeQuery();
				       
				       if(rs.next())
				        {
				    	   count = rs.getInt("COUNT");
				        }
				       
				       if(count<=0)
				       {
				    	   return isSingleLot = true;
				       }
				}
			}		*/
			///From customer Master get the singlelot value it will check below code iff single lot valu is yes.
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
       }
		catch(Exception e)
		{
			throw e;
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				throw new ITMException(e);
			}
		}
		return isSingleLot;
		
	}
	//Changed by sankara on 03-08-2012 for  finding single lot[end]
	//changed by sumit on 06/08/12 writting jsp file for report start.
	//private String writeReportInJsp(String waveId, Connection conn, String siteCode, String saleOrder) throws ITMException
	//changed by sumit on 06/08/12 writting jsp file for report start.
	private String writeReportInJsp(String waveId, Connection conn, String siteCode) throws ITMException 
	{
		String errString = "";
		ArrayList al = null;
		PreparedStatement pstmt = null;
        ResultSet rs = null;
        StringBuffer replOrderBuffer = new StringBuffer();
        StringBuffer pickOrderBuffer = new StringBuffer();
        
        HashMap mapSaleOrder = new HashMap();

        try
        {
            Calendar calendar = Calendar.getInstance();
            java.util.Date now = calendar.getTime();
            java.sql.Timestamp currentTimestamp = new
            java.sql.Timestamp(now.getTime());
            CommonConstants commonConstants = new CommonConstants();
          
            String fileStr = commonConstants.RESOURCE_PATH+ File.separator+ chgUser + File.separator+ waveId +".jsp";
            System.out.println("fileStr--- >["+fileStr+"]");
            File file =new File(fileStr);

            //if file doesnt exists, then create it
            if(!file.exists())
            {
               file.createNewFile();
            }
            System.out.println(" location :"+file.getAbsoluteFile());
            BufferedWriter out = new BufferedWriter(new FileWriter(file));  
            
          //Changed by Ameya on 16/08/2012 added the heading of all tables
            out.write("<CENTER><b>WAVE PREVIEW</b></CENTER><BR>");

         
            String sql = "SELECT WAVE_ID, TRAN_DATE, SALE_ORDER__FROM, SALE_ORDER__TO, CUST_CODE__FROM, CUST_CODE__TO "+
            "DUE_DATE__FROM, DUE_DATE__TO, HOLD_STATUS FROM WAVE_TASK WHERE WAVE_ID = ?";
           pstmt = conn.prepareStatement(sql);
           pstmt.setString(1, waveId);           
           rs = pstmt.executeQuery();
           ResultSetMetaData rsmd = rs.getMetaData();
           int numColumns = rsmd.getColumnCount();
           al = new ArrayList();
           out.write("");
         
           out.write("<table border='1'><caption><b>WAVE TASKS</b></caption><TR>");
           
         //Changed by Ameya on 17/08/2012 added new variable holdStatus
           String holdStatus="";
           
         //Changed by Ameya on 17/08/2012 added new variable holdStatusIndex
           int holdStatusIndex=0;
           
         //Changed by Ameya on 23/08/2012 added new variable columnValue
           String columnValue="";
           
         //Changed by Ameya on 24/08/2012 added new variable tranDateIndex
           int tranDateIndex=0;
           
           //Changed by Ameya on 24/08/2012 added new variable dueDateTo
           int dueDateToIndex=0;
           
           for (int i=1; i<numColumns+1; i++) {
                String columnName = rsmd.getColumnName(i);
                //String tableName = rsmd.getTableName(i);
                al.add(columnName);
                out.write("<TH>");
                out.write(columnName);
                out.write("</TH>");
                if(columnName.equalsIgnoreCase("HOLD_STATUS"))
                {
                	holdStatusIndex=i;
                }
              //Changed by Ameya on 24/08/2012 seting index for TRAN_DATE & DUE_DATE__TO Start
                if(columnName.equalsIgnoreCase("TRAN_DATE"))
                {
                	tranDateIndex=i;
                }
                if(columnName.equalsIgnoreCase("DUE_DATE__TO"))
                {
                	dueDateToIndex=i;
                }
                //Changed by Ameya on 24/08/2012 seting index for TRAN_DATE & DUE_DATE__TO End
            }
           out.write("</TR>");
           out.newLine();
           out.write("<TR>");
           if( rs.next())
           {
               for (int i=0; i< al.size(); i++)
               {
            	
            	   columnValue=(String)rs.getString(al.get(i).toString());
            		   if(columnValue==null || columnValue.length()==0)
            		   {
            			   out.write("<td>");
                		   out.append("");
                       	   out.write("</td>");
            		   }
            		   else
            		   {
            			           			   
            			   if(dueDateToIndex==(i+1) || tranDateIndex==(i+1) )
            			   {
            				   out.write("<td>");
               		   		  out.append(columnValue.substring(0, columnValue.length()-11));
               		   		  out.write("</td>");
            			   }
            			   else
            			   {
            				   out.write("<td>");
                		   		out.append(columnValue);
                		   		out.write("</td>");
            			   }
            			   //Changed by Ameya on 24/08/2012 seting index for TRAN_DATE & DUE_DATE__TO End
            		   }
            	   
            	   
               }
           }
           rsmd = null;
           rs.close();rs = null;
           pstmt.close();pstmt = null;
           out.write("</TR>");
           out.write("</table><br>");

           //wave_task det
           System.out.println("wave_task-det");
           
           sql = "SELECT WAVE_ID, LINE_NO, REF_SER, REF_ID, STATUS, SALE_ORDER, PTCN FROM WAVE_TASK_DET WHERE WAVE_ID = ?";
           pstmt = conn.prepareStatement(sql);
           pstmt.setString(1, waveId);
         //Changed by Ameya on 25/08/2012 changed 
           //pstmt.setString(2, saleOrder);
           rs = pstmt.executeQuery();
           rsmd = rs.getMetaData();
           numColumns = rsmd.getColumnCount();
           out.newLine();
           al.removeAll(al);

           out.write("<table border='1'><TR>");

         //Changed by Ameya on 17/08/2012 for storing an index of refID
           int refIdIndex=0;
           
           //Changed by Ameya on 25/08/2012 for storing an index of refID
           int saleOrderIndex=0;
           for (int i=1; i<numColumns+1; i++) {
                String columnName = rsmd.getColumnName(i);
                //String tableName = rsmd.getTableName(i);
                al.add(columnName);
                             
                
                if(!"REF_ID".equalsIgnoreCase(columnName))
                {
                	out.write("<TH>");
                	out.write(columnName);
                	out.write("</TH>");
                	//Changed by Ameya on 25/08/2012 to store an index of  SALE_ORDER Start
                	if(columnName.equalsIgnoreCase("SALE_ORDER"))
                	{
                		saleOrderIndex = i;
                	}
                	//Changed by Ameya on 25/08/2012 to store an index of  SALE_ORDER End
                }
                else
                {
                	refIdIndex=i;
                	System.out.println("refIdIndex="+refIdIndex);
                }
                //Changed by Ameya on 17/08/2012 for not displaying REF_ID column heading End
            }
           out.write("</TR>");

           
           while( rs.next())
           {
               out.newLine();
               out.write("<TR>");
               for (int i=0; i< al.size(); i++)
               {
            	 //Changed by Ameya on 17/08/2012 for not adding <td> for REF_ID Start
                   //out.write("<td>");
                   if(refIdIndex!=(i+1))
                   {
                	   out.write("<td>");
                   }
                 //Changed by Ameya on 17/08/2012 for not adding <td> for REF_ID End
                   String temp = rs.getString(al.get(i).toString());
                 //Changed by Ameya on 17/08/2012 for not displaying value REF_ID Start
                   //out.append(temp);
                   if(refIdIndex!=(i+1))
                   {
                	 //out.append(temp);
                  	 //Changed by Ameya on 23/08/2012 check null values Start 
                  	   if(temp.length()==0 || temp==null)
                  	   {
                  		   out.append("");
                  	   }
                  	   else
                  	   {
                  		   out.append(temp);
                  	   }
                  	//Changed by Ameya on 25/08/2012 to store SALE_ORDER in map Start
                  	   if(saleOrderIndex==(i+1))
                  	   {
                  		   mapSaleOrder.put(temp, temp);
                  	   }
                  	   
                  	//Changed by Ameya on 25/08/2012 to store SALE_ORDER in map End
                  	 //Changed by Ameya on 23/08/2012 check null values End 
                   }
                   System.out.println("temp="+temp);
                 //Changed by Ameya on 17/08/2012 for not displaying value REF_ID End
                   if("ref_id".equalsIgnoreCase(al.get(i).toString()))
                   {
                       //System.out.println(" ref_id "+temp);  
                	 //Changed by Ameya on 17/08/2012 for checking temp startswith RT Start
                       //replOrderBuffer.append(getReplOrder(temp, conn)).append(" ");
                       if(temp.startsWith("RT"))
                       {
                    	   replOrderBuffer.append(temp).append(" ");
                    	   System.out.println(" replOrderBuffer "+replOrderBuffer);
                       }
                     //Changed by Ameya on 17/08/2012 for checking temp startswith RT End
                   }
                   if("ref_id".equalsIgnoreCase(al.get(i).toString()))
                   {
                      // System.out.println(" ref_id "+temp);
                	 //Changed by Ameya on 17/08/2012 for checking temp startswith PT Start
                     //pickOrderBuffer.append(getPickOrder(temp, conn)).append(" ");
                      if(temp.startsWith("PT"))
                      {
                    	  pickOrderBuffer.append(temp).append(" ");
                    	  System.out.println(" pickOrderBuffer "+pickOrderBuffer);
                      }
                    //Changed by Ameya on 17/08/2012 for checking temp startswith PT End
                   }
                 //Changed by Ameya on 17/08/2012 for not adding </td> for REF_ID Start
                   //out.write("</td>");
                   if(refIdIndex!=(i+1))
                   {
                	   out.write("</td>");
                   }
                 //Changed by Ameya on 17/08/2012 for not adding </td> for REF_ID End
               }
               out.write("</TR>");
           }
           System.out.println(" string buffer for repl ord hdr "+replOrderBuffer.toString());
           System.out.println(" string buffer for pick ord hdr "+pickOrderBuffer.toString());
           rsmd = null;
           rs.close();rs = null;
           pstmt.close();pstmt = null;
           out.write("</table><br>");
           //for repl_ord_hdr 
         //Changed by Ameya on 16/08/2012 changed the query for selecting only particular columns of table REPL_ORD_HDR
           //sql = "SELECT * FROM REPL_ORD_HDR ";
           sql = "SELECT REPL_ORDER, ORDER_DATE, SITE_CODE, SALE_ORDER, WAVE_ID FROM REPL_ORD_HDR ";
           pstmt = conn.prepareStatement(sql);           
           rs = pstmt.executeQuery();
           rsmd = rs.getMetaData();
           numColumns = rsmd.getColumnCount();
           out.newLine();
           al.removeAll(al);
           //System.out.println("fdfdddddddddddddd"+al);
         //Changed by Ameya on 16/08/2012 added the heading of table REPL_ORD_HDR
           //out.write("<table border='1'><TR>");
           
         
         //Changed by Ameya on 25/08/2012 not displaying header replenishment 
          //  out.write("<table border='1'><caption>REPLENISHMENT TASKS</caption><TR>");          
           for (int i=1; i<numColumns+1; i++) {
                String columnName = rsmd.getColumnName(i);
                //String tableName = rsmd.getTableName(i);
                al.add(columnName);
                
            }
           rsmd = null;
           rs.close();rs = null;
           pstmt.close();pstmt = null;
           
           StringTokenizer replHdrTok = null,replDetTok = null;
           String replString = checkNull(replOrderBuffer.toString());
           if( replString.trim().length() > 0 )
           {
        	   replHdrTok = new StringTokenizer(replOrderBuffer.toString()," ");        	   
           }
           int replCount = 0;           
           if( replHdrTok != null)
           {
	           while( replHdrTok.hasMoreTokens())
	           {
	        	   
                   String replStr = replHdrTok.nextToken();
                 //Changed by Ameya on 16/08/2012 changed the query for selecting only particular columns of table REPL_ORD_HDR
                   //sql = "SELECT * FROM REPL_ORD_HDR WHERE REPL_ORDER = ?";
                   sql = "SELECT REPL_ORDER, ORDER_DATE, SITE_CODE, SALE_ORDER, WAVE_ID FROM REPL_ORD_HDR WHERE REPL_ORDER = ?";
                   pstmt = conn.prepareStatement(sql);
                   pstmt.setString(1, replStr);
                   rs = pstmt.executeQuery();
                   rsmd = rs.getMetaData();
                   numColumns = rsmd.getColumnCount();
                   out.newLine();   
                   
                   rsmd = null;
                   rs.close();rs = null;
                   pstmt.close();pstmt = null;
                   
	           }
           }
         
           sql = "SELECT R.REPL_ORDER, R.SALE_ORDER, R.LINE_NO__SORD AS SORDLNO, R.ITEM_CODE || ' (' ||I.DESCR || ')' AS ITEM_DESCRIPTION , " +
           		"R.LOC_CODE, R.LOT_NO, R.LOT_SL AS LPN, R.NO_ART, R.QUANTITY, "+
           		"R.PICK_ORDER, LOC_CODE__TO FROM REPL_ORD_DET R, ITEM I WHERE R.ITEM_CODE=I.ITEM_CODE"; 
           pstmt = conn.prepareStatement(sql);              
           rs = pstmt.executeQuery();
           rsmd = rs.getMetaData();
           numColumns = rsmd.getColumnCount();
           out.newLine();
           al.removeAll(al);
         
           out.write("<table border='1'><caption><b>REPLENISHMENT TASKS</b></caption><TR>");       
           for (int i=1; i<numColumns+1; i++) 
           {
                String columnName = rsmd.getColumnName(i);
                //String tableName = rsmd.getTableName(i);
                al.add(columnName);
                out.write("<TH>");
                out.write(columnName);
                out.write("</TH>");
            }
           rsmd = null;
           rs.close();rs = null;
           pstmt.close();pstmt = null;  
           if( replString.trim().length() > 0 )
           {
        	   replDetTok = new StringTokenizer(replOrderBuffer.toString()," ");        	   
           }
           if( replDetTok != null)
           {
               while( replDetTok.hasMoreTokens())
	           {
            	   String replStr = replDetTok.nextToken();
            	 
            	   sql = "SELECT R.REPL_ORDER, R.SALE_ORDER, R.LINE_NO__SORD AS SORDLNO, R.ITEM_CODE || ' (' || I.DESCR || ')'  AS ITEM_DESCRIPTION, R.LOC_CODE, R.LOT_NO , " +
            	   		"R.LOT_SL AS LPN, R.NO_ART, R.QUANTITY, "+
            	   		"R.PICK_ORDER, LOC_CODE__TO FROM REPL_ORD_DET R, ITEM I WHERE R.ITEM_CODE=I.ITEM_CODE AND REPL_ORDER = ?";
                   pstmt = conn.prepareStatement(sql);
                   pstmt.setString(1, replStr);
                   rs = pstmt.executeQuery();
                    while( rs.next())
                   {
                       out.newLine();
                       out.write("<TR>");
                       for (int i=0; i< al.size(); i++)
                       {
                    	
                    	   columnValue=rs.getString(al.get(i).toString());
                           
                           out.write("<td>");
                           if(columnValue==null || columnValue.length()==0)
                    	   {
                    		   out.append("");
                    	   }
                    	   else
                    	   {
                    		   out.append(columnValue);
                    	   }
                           out.write("</td>");
                           //Changed by Ameya on 23/08/2012 checking null values End
                       }
                       out.write("</TR>");
                   }
                   rsmd = null;
                   rs.close();rs = null;
                   pstmt.close();pstmt = null;
                                   
	           	}
        	}
           out.write("</table><br>");   

           // pick ord HDR
         //Changed by Ameya on 16/08/2012 changed the query for selecting only particular columns of table PICK_ORD_HDR
           //sql = "SELECT * FROM PICK_ORD_HDR";
           sql = "SELECT PICK_ORDER, ORDER_DATE, SITE_CODE, SALE_ORDER, WAVE_ID, PICK_TYPE FROM PICK_ORD_HDR";
           pstmt = conn.prepareStatement(sql);           
           rs = pstmt.executeQuery();
           rsmd = rs.getMetaData();
           numColumns = rsmd.getColumnCount();
           out.newLine();
           al.removeAll(al);
        
           int pickTypeIndex=0;
           for (int i=1; i<numColumns+1; i++) 
           {
                String columnName = rsmd.getColumnName(i);
                //String tableName = rsmd.getTableName(i);
                al.add(columnName);
                
                if(columnName.equalsIgnoreCase("PICK_TYPE"))
                {
                	pickTypeIndex=i;
                }
              //Changed by Ameya on 17/08/2012 added new variable for pickType index End
            }
           
           StringTokenizer pickHdrToken = null, pickDetToken = null;
           String pickString = checkNull(pickOrderBuffer.toString());
           if( pickString.trim().length() > 0 )
           {
        	   pickDetToken = pickHdrToken = new StringTokenizer(pickOrderBuffer.toString()," ");
        	   //pickDetToken = pickHdrToken;
           }
           int pickCount = 0;   
         //Changed by Ameya on 16/08/2012 strore the value of pick_type
           String pickType="";
           if( pickHdrToken != null)
           {
	           while( pickHdrToken.hasMoreTokens())
	           {
	               String pickStr =  pickHdrToken.nextToken();
	             //Changed by Ameya on 16/08/2012 changed the query for selecting only particular columns of table PICK_ORD_HDR
	               //sql = "SELECT * FROM PICK_ORD_HDR WHERE PICK_ORDER = ?";
	               sql = "SELECT PICK_ORDER, ORDER_DATE, SITE_CODE, SALE_ORDER, WAVE_ID, PICK_TYPE FROM PICK_ORD_HDR WHERE PICK_ORDER = ?";
	               pstmt = conn.prepareStatement(sql);
	               pstmt.setString(1, pickStr);
	               rs = pstmt.executeQuery();
	            
	           }
           }
          
           sql = "SELECT P.PICK_ORDER, P.SALE_ORDER, P.LINE_NO__SORD AS SORDLNO, P.ITEM_CODE || ' (' || I.DESCR ||')' AS ITEM_DESCRIPTION , " +
           		"P.LOC_CODE, P.LOT_NO, P.LOT_SL AS LPN, P.NO_ART, " +
           		"P.QUANTITY, P.LOC_CODE__TO FROM PICK_ORD_DET P, ITEM I WHERE P.ITEM_CODE=I.ITEM_CODE";
           pstmt = conn.prepareStatement(sql);           
           rs = pstmt.executeQuery();
           rsmd = rs.getMetaData();
           numColumns = rsmd.getColumnCount();
           out.newLine();
           al.removeAll(al);
           out.write("<table border='1'><caption><b>PICK TASKS</b></caption><TR>");
           for (int i=1; i<numColumns+1; i++) 
           {
                String columnName = rsmd.getColumnName(i);
                //String tableName = rsmd.getTableName(i);
                al.add(columnName);
                out.write("<TH>");
                out.write(columnName);
                out.write("</TH>");
            }
           rsmd = null;
           rs.close();rs = null;
           pstmt.close();pstmt = null; 
           //System.out.println(" pickDetToken "+pickDetToken);
           if( pickString.trim().length() > 0 )
           {
        	   pickDetToken = new StringTokenizer(pickOrderBuffer.toString()," ");
        	   //pickDetToken = pickHdrToken;
           }
           if( pickDetToken != null)
           {
        	   System.out.println("inside pickDetToken != null ");
	           while( pickDetToken.hasMoreTokens())
	           {
	        	   System.out.println("pickDetToken.hasMoreTokens()");
	        	   String pickStr =  pickDetToken.nextToken();
	        	
	        	   sql = "SELECT P.PICK_ORDER, P.SALE_ORDER, P.LINE_NO__SORD AS SORDLNO, P.ITEM_CODE || ' (' || I.DESCR || ')'  AS  ITEM_DESCRIPTION, " +
	        	   		"P.LOC_CODE, P.LOT_NO, P.LOT_SL AS LPN, P.NO_ART, "+
	        	   		"P.QUANTITY, P.LOC_CODE__TO  FROM PICK_ORD_DET P, ITEM I WHERE P.ITEM_CODE=I.ITEM_CODE AND PICK_ORDER = ?";
                   pstmt = conn.prepareStatement(sql);
                   pstmt.setString(1, pickStr);
                   rs = pstmt.executeQuery();          
                   while( rs.next())
                   {
                       out.newLine();
                       out.write("<TR>");
                       for (int i=0; i< al.size(); i++)
                       {
                    	 
                           columnValue=rs.getString(al.get(i).toString());
                    	   out.write("<td>");
                    	   if(columnValue==null || columnValue.length()==0)
                    	   {
                    		   System.out.println("if null columnValue="+columnValue);
                    		   out.append("");
                    	   }
                    	   else
                    	   {
                    		   System.out.println("if not null columnValue="+columnValue);
                    		   out.append(columnValue);
                    	   }
                           out.write("</td>");
                           //Changed by Ameya on 23/08/2012 check null values End
                       }
                       out.write("</TR>");
                   }                  
           		}	           	
           	}
           out.write("</table><br>");
           
         //Changed by Ameya on 25/08/2012 for to display SORDITEM_TEMP Start
           System.out.println("sorditem_temp starts");
           String currentSaleOrder="";
           //currentSaleOrder = mapSaleOrder.
           Set e= mapSaleOrder.keySet();
   			Iterator itr= e.iterator();
   			boolean flagSordItemHeading = false;
   		   while(itr.hasNext())
       	   {
   			   
   			   currentSaleOrder = (String)itr.next();
   			   System.out.println(currentSaleOrder);
   		
   			   sql = "SELECT * FROM sorditem_temp where sale_order=?";
   			   pstmt = conn.prepareStatement(sql);  
   			   pstmt.setString(1, currentSaleOrder);
   			   rs = pstmt.executeQuery();
   			   rsmd = rs.getMetaData();
   			   numColumns = rsmd.getColumnCount();
   			   out.newLine();
   			   al.removeAll(al);
   			   if(flagSordItemHeading==false)
   			   {
   				   //out.write("<table border='1'><caption><b><center>Sale order Item Reason Details</center></b></caption><TR>");
   				   out.write("<b><center>SALE ORDER ITEM REASON DETAILS</center></b>");
   				   out.write("<table border='1'><TR>");
   				   	for (int i=1; i<numColumns+1; i++) 
   			   		{
   				   		String columnName = rsmd.getColumnName(i);
   				   		//	String tableName = rsmd.getTableName(i);
   				   		al.add(columnName);
   				   		out.write("<TH>");
   				   		out.write(columnName);
   				   		out.write("</TH>");
   			   		}
   				 flagSordItemHeading = true;
   			   }
        	   while(rs.next())
        	   {
        		   out.write("<tr>");
        		   for (int i=0; i< rsmd.getColumnCount(); i++)
        		   { 
        			   out.write("<td>");
        			   out.write(rs.getString(i+1));
        			   out.write("</td>");
        		   }
        		   out.write("</tr>");
        	   }
        	   if(pstmt!=null)
        	   {
        		   pstmt.close();
        		   pstmt = null;
        	   }
        	   if(rsmd!=null)
        	   {	
        		   rsmd = null;
        	   }
        	   if(rs!=null)
        	   {
        		   rs.close();
        		   rs = null;
        	   }
      	   }
   		   //Changed by Ameya on 25/08/2012 for to display SORDITEM_TEMP End
		   if(out != null)
		   {
			   out.flush();
			   out.close();
		   }
		   if(pstmt!=null)
		   {
			   pstmt.close();
			   pstmt = null;
		   }
		   if(rsmd!=null)
		   {	
			   rsmd = null;
		   }
		   if(rs!=null)
		   {
			   rs.close();
			   rs = null;
		   }
           System.out.println(" file written ");

        }
        catch(Exception e)
        {
            System.out.println("error "+e.getMessage());
            e.printStackTrace();
			throw new ITMException(e);
        }
        finally
        {
        	try
        	{
    		   if(pstmt!=null)
    		   {
    			   pstmt.close();
    			   pstmt = null;
    		   }
    		   if(rs!=null)
    		   {
    			   rs.close();
    			   rs = null;
    		   }
        	}
        	catch(Exception e)
        	{
        		throw new ITMException(e);
        	}
        }
		return null;
	}	
	//changed by sumit on 06/08/12 writting jsp file for report end.
	//Changed by sumit 02/08/12 to print expected wave_generation as a report start.
    private String generateReport(String waveId, Connection conn) throws ITMException
    {
    	String errString ="";
    	String printMode = "";
    	String outputFilename = "";
    	TreeMap argMap = null;
    	//Changed by sumit on 06/10/12 
    	String saleOrder = "";
    	PreparedStatement pstmt = null;
    	ResultSet rs = null;
    	
    	try
    	{
    		//Changed by sumit 06/10/12 for getting sale order value start.
    		sql = " SELECT SALE_ORDER FROM WAVE_TASK_DET WHERE WAVE_ID = ? ORDER BY SALE_ORDER";
    		pstmt = conn.prepareStatement(sql);
    		pstmt.setString(1, waveId);
    		rs = pstmt.executeQuery();
    		if( rs.next())
    		{
    			saleOrder = rs.getString("SALE_ORDER");
    		}
    		pstmt.close();pstmt = null;
    		rs.close(); rs = null;
    		
    		//Changed by sumit 06/10/12 for getting sale order value start.
    		
    		printMode = checkNull(discommon.getDisparams("999999","WAVE_PRINT_MODE",conn));
			//if ("R".equalsIgnoreCase(waveMode) && printMode.trim().length() > 0) 	
			//{					
				System.out.println(" printMode ->["+printMode+"]");
				if("REPORT".equalsIgnoreCase(printMode))
				{
					//Changed by sumit on 03/10/12 commented as printer entered inputed .
					//String printerStr  = discommon.getDisparams("999999","WAVE_PRINTER",conn);
					String reportObjName = discommon.getDisparams("999999","WAVE_REP_OBJ_NAME",conn);
					String reportSavetype = discommon.getDisparams("999999","REPORT_SAVE_TYPE",conn);
					if( reportSavetype == null || reportSavetype.trim().length() == 0 )
					{
						reportSavetype = "NATIVE";
					}
					System.out.println("Printer *->["+printer.trim()+"]  report_obj_name ["+reportObjName+"] reportSavetype ->["+reportSavetype+"]");
					
					/*for (int i=0; i< ptcnList.size(); i++)
					{*/
						//System.out.println("inside report generation : and wave id is ["+ptcnList.get(i)+"]");
						System.out.println("inside report  generation :: and wave id is ["+waveId+"]");
						ibase.webitm.reports.utility.JasperReportGenerator jrGenerator = new ibase.webitm.reports.utility.JasperReportGenerator();
						String xsdString ="<Arguments>" +
									"<Argument id=\"p_wave_id\" name=\"p_wave_id\">" +
									"<argType>java.lang.String</argType>" +
									//"<value>"+ptcnList.get(i)+"</value>" +
									"<value>"+waveId+"</value>" +
									"</Argument>" +
									"<Argument id=\"p_rep_mod\" name=\"p_rep_mod\">" +
									"<argType>java.lang.String</argType>" +
									//"<value>"+ptcnList.get(i)+"</value>" +
									"<value>"+waveMode+"</value>" +
									"</Argument>" +
									"<Argument id=\"x_path\" name=\"x_path\">" +
									"<argType>java.lang.String</argType>" +
									"<value>/DocumentRoot/wave_task_main</value>" +
									"</Argument>" +
									"<Argument id=\"design_source\" name=\"design_source\">" +
									"<argType>java.lang.String</argType>" +
									"<value>wave_task_main.jrxml</value>" +
									"</Argument>" +
									"<Argument id=\"data_source\" name=\"data_source\">" +
									"<argType>java.lang.String</argType>" +
									"<value>SQL</value>" +
									"</Argument>" +
									"<Argument id=\"bind_type\" name=\"bind_type\">" +
									"<argType>java.lang.Integer</argType>" +
									"<value>0</value>" +
									"</Argument>" +
									"<Argument id=\"report_type\" name=\"report_type\">" +
									"<argType>java.lang.String</argType>" +
									"<value>JASPER</value>" +
									"</Argument>" +
									"<Argument id=\"report_save_type\" name=\"report_save_type\">" +
									"<argType>java.lang.String</argType>" +
									//Changed by sumit on 07/09/12  changed NATIVE to PDF
									//"<value>NATIVE</value>" +									
									"<value>"+reportSavetype+"</value>" +
									"</Argument>" +
									"</Arguments>";
						System.out.println(" XSD parser **->["+xsdString+"]");
						//Changed by Sumit on 07-09-2012 report generate in inside \ibase.ear\ibase.war\webitm\reports\finalreport\BASE start.						
						//PDFCreator
						//\\\\172.16.100.90\\unimis-hpljP3015-001	
						//errString = jrGenerator.printReport(reportObjName, xsdString, chgUser, printerStr, 1, conn);
						if( "PDF".equalsIgnoreCase(reportSavetype))
						{
							XSDParser xsdParser = new XSDParser(reportObjName);
							argMap = jrGenerator.createArgMap(xsdString);
							System.out.println("TreeMap:::->"+argMap);
							//outputFilename = reportObjName.trim() + chgUser + new Random().nextInt();
							//outputFilename = chgUser + "_" + saleOrder+"_"+waveId;
							outputFilename = chgUser + "_" + saleOrder+"_"+waveId+"_"+ new Random().nextInt();
							jrGenerator.createReport(reportObjName , argMap, xsdParser, chgUser, outputFilename, conn);
						}
						else
						{
							errString = jrGenerator.printReport(reportObjName, xsdString, chgUser, printer.trim(), 1, conn);
						}			
						
						//Changed by sumit on 07/09/12 changed the method as per new requirement
						
						
					//}
					System.out.println(" PRINTING task completed--------**------->");
				}
				else if("JSP".equalsIgnoreCase(printMode))
				{
					errString = writeReportInJsp(waveId, conn, siteCode);
					System.out.println(" written in jsp done");
				}
			//}
			
			
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace();
    		throw new ITMException(e);
    	}
    	//Changed by sumit on 06/10/12 added finally method start.
    	finally
    	{
    		try 
    		{
    			if( pstmt != null)
    			{
					pstmt.close();
					pstmt = null;
    			}
    			if( rs != null)
    			{
    				rs.close();
    				rs = null;
    			}
				
			} 
    		catch (Exception e2) 
			{
				throw new ITMException(e2);
			}
    	}
    	//Changed by sumit on 06/10/12 added finally method end.
    	
    	return errString;
    }
  //Changed by sumit 02/08/12 to print expected wave_generation as a report END.
	public double adjustAvailableQty(String itemCode,String siteCode,String lotNo,String lotSl,String locCode,double qtyAvailAlloc,Connection conn) throws Exception
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
	    String sql = "";
	    PreparedStatement pstmtRepl = null;
		ResultSet rsRepl = null;
	    String sqlRepl = "";
	    String locCodeTo = "";
	    String locCodeToRepl = "";
	    String locInvstat = "";
	    //Changed by Rohan on 14-02-13 to define variable.start
	    String activePickInv1  = discommon.getDisparams("999999","ACTIVE_PICK_INVSTAT",conn);
	    System.out.println("activePickInv1:::>>::>>>"+activePickInv1);
	    //activePickLoc  = discommon.getDisparams("999999","ACTIVE_PICK_INVSTAT",conn);
	    
		double replQuantity = 0.0;
		
		try
		{
			sql= "SELECT R.LOC_CODE__TO,R.ACTUAL_QTY,LOC.INV_STAT FROM REPL_ORD_DET R,LOCATION LOC WHERE R.LOC_CODE = ?  AND R.ITEM_CODE = ?"
				+" AND R.SITE_CODE = ? AND R.LOT_NO = ? AND R.LOT_SL = ? AND LOC.LOC_CODE = R.LOC_CODE__TO ORDER BY REPL_ORDER";
			pstmt =  conn.prepareStatement(sql);
			pstmt.setString(1, locCode);
			pstmt.setString(2, itemCode);
			pstmt.setString(3, siteCode);
			pstmt.setString(4, lotNo);
			pstmt.setString(5, lotSl);
			
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				locCodeTo = rs.getString("LOC_CODE__TO");
				replQuantity = rs.getDouble("ACTUAL_QTY");
				
				pstmtRepl =  conn.prepareStatement(sql);
				pstmtRepl.setString(1, locCode);
				pstmtRepl.setString(2, itemCode);
				pstmtRepl.setString(3, siteCode);
				pstmtRepl.setString(4, lotNo);
				pstmtRepl.setString(5, lotSl);
				
				rsRepl = pstmtRepl.executeQuery();
				if(rsRepl.next())
				{
					locCodeToRepl = rsRepl.getString("LOC_CODE__TO");
					locInvstat = rsRepl.getString("INV_STAT");
				}
				//if(locInvstat.startsWith("ACTPK"))
				//if(locInvstat.equalsIgnoreCase(activePickInv))
				//System.out.println()
				System.out.println("locInvstat"+locInvstat+"activePickInv"+activePickInv1);
				if(locInvstat.trim().equalsIgnoreCase(activePickInv1.trim()))
				{
					System.out.println("Enter in Active Replanishement");
					qtyAvailAlloc = qtyAvailAlloc - replQuantity;
					return qtyAvailAlloc;
					 
				}
			  
			}		
			///From customer Master get the singlelot value it will check below code iff single lot valu is yes.
			
        }
		catch(Exception e)
		{
			throw e;
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if(rsRepl != null)
				{
					rsRepl.close();
					rsRepl = null;
				}
				if(pstmtRepl != null)
				{
					pstmtRepl.close();
					pstmtRepl = null;
				}
			}
			catch(Exception e2)
			{
				throw new ITMException(e2);
			}
			
		}
		return qtyAvailAlloc;
	}
	//Changed by Rohan on 7/8/12 to adjust avaiable Quantity.end
	//Chnaged by Rohan on 22/08/12 to get stock quantity for manual stock allocation.start
	public double getStockQuantity(String itemCode,String siteCode,String locCode,String lotNo,String lotSl,double qtyAllocate,Connection conn) throws Exception
	{
	
		PreparedStatement pstmt = null;
		ResultSet rs = null;
	    String sql = "";
	   
		double quantity = 0.0;
		double allocQty = 0.0;
		double stockQty = 0.0;
		
		try
		{
			sql= "SELECT QUANTITY,ALLOC_QTY FROM STOCK WHERE ITEM_CODE = ? AND SITE_CODE = ? "
				 +" AND LOC_CODE = ? AND LOT_NO = ? AND LOT_SL = ?";
			pstmt =  conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			pstmt.setString(2, siteCode);
			pstmt.setString(3, locCode);
			pstmt.setString(4, lotNo);
			pstmt.setString(5, lotSl);
			
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				quantity = rs.getDouble("QUANTITY");
				allocQty = rs.getDouble("ALLOC_QTY");
			 
			}
			stockQty = quantity - (allocQty - qtyAllocate);
			 
					
        }
		catch(Exception e)
		{
			throw e;
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e2)
			{
				throw new ITMException(e2);
			}
		
		}
	return stockQty;  	
	}
	//Chnaged by Rohan on 22/08/12 to get stock quantity for manual stock allocation.end
	
	//Changed by sumit on 23/08/12n update wave_status as per their sequence of task start.
	private String updateWaveSatus(String waveId,String directPickLoc, Connection conn) throws ITMException
	{
		PreparedStatement pstmt2 = null, pstmt = null, pstmt1 = null;
		ResultSet rs2 = null, rs3 = null, rs1 = null;
		String refSer = "";
		String refId = "";
		String tempOrder = "";
		String saleOrder = "";
		String sql1 = "";
		String errString = "";
		int update = 0;
		
		try
		{
			//Changed by sumit on 30/07/12 giving input START.
			sql = "SELECT REF_SER, REF_ID, SALE_ORDER FROM WAVE_TASK_DET WHERE WAVE_ID = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, waveId);
			rs3 = pstmt.executeQuery();
			while(rs3.next())
			{
				refSer = rs3.getString("REF_SER").trim();
				refId = rs3.getString("REF_ID").trim();
				saleOrder = rs3.getString("SALE_ORDER");
				
				System.out.println("-------@@@@@---------> refSer ["+refSer+"]");
				//Changed by Rohan Bhogale on 1-11-12 to set wave stats c in case of pratial to active replanishment
				//if ("R-DSO".equalsIgnoreCase(refSer)  || "R-TASK".equalsIgnoreCase(refSer) || "RS-DSO".equalsIgnoreCase(refSer) )
				
				//Changed by sumit on 06/11/12 adding ref_ser RD-DSA i.e from deep store to PND, RR-DSA i.e reserve to active 
				//if ("R-DSO".equalsIgnoreCase(refSer)  || "R-TASK".equalsIgnoreCase(refSer) || "RS-DSO".equalsIgnoreCase(refSer) || "RP-ACT".equalsIgnoreCase(refSer))
				if ("R-DSO".equalsIgnoreCase(refSer)  || "R-TASK".equalsIgnoreCase(refSer) || "RS-DSO".equalsIgnoreCase(refSer) || "RP-ACT".equalsIgnoreCase(refSer) || "RD-DSA".equalsIgnoreCase(refSer) || "RR-DSA".equalsIgnoreCase(refSer) || "S-DOC".equalsIgnoreCase(refSer))
				{
					
					//Changed By Pragyan 06/03/13 To update wave status only if it is "N"
					//sql = "UPDATE WAVE_TASK_DET SET WAVE_STATUS = 'C' WHERE REF_ID = ? ";
					sql = "UPDATE WAVE_TASK_DET SET WAVE_STATUS = 'C' WHERE REF_ID = ? AND STATUS = 'N'";
					pstmt2 = conn.prepareStatement(sql);
					pstmt2.setString(1, refId);
					//pstmt.setString(9, "C");
					update = pstmt2.executeUpdate();
					if(pstmt2 != null)
					{
						pstmt2.close();
						pstmt2 = null;
					}									
				}
				//Changed by sumit on 06/11/12 adding ref_ser R-CPA
				//else if ( "R-DSA".equalsIgnoreCase(refSer) )
				else if ( "R-DSA".equalsIgnoreCase(refSer) || "R-CPA".equalsIgnoreCase(refSer))
				{
					tempOrder = "";
					sql1 = "SELECT PICK_ORDER FROM REPL_ORD_DET WHERE REPL_ORDER = ? ";
					pstmt2 = conn.prepareStatement(sql1);
					pstmt2.setString(1, refId);
					rs2 = pstmt2.executeQuery();
					if( rs2.next())
					{
						tempOrder = checkNull(rs2.getString("PICK_ORDER"));
					}
					if(rs2 != null)
					{
						rs2.close();
						rs2 = null;
					}
					if(pstmt2 != null)
					{
						pstmt2.close();
						pstmt2 = null;
					}
					
					//Changed By Pragyan 06/03/13 To update wave status only if it is "N"
					//sql1 = "UPDATE WAVE_TASK_DET SET WAVE_STATUS = 'C' WHERE REF_ID = ? AND WAVE_ID = ? AND SALE_ORDER = ?";
					sql1 = "UPDATE WAVE_TASK_DET SET WAVE_STATUS = 'C' WHERE REF_ID = ? AND WAVE_ID = ? AND SALE_ORDER = ? AND STATUS = 'N'";
					pstmt1 = conn.prepareStatement(sql1);
					pstmt1.setString(1, refId);
					pstmt1.setString(2, waveId);
					pstmt1.setString(3, saleOrder);
					
					if(tempOrder.trim().length() > 0)
					{
						String conf = "";				
						sql = 	" SELECT STATUS FROM WAVE_TASK_DET WHERE REF_ID = ? AND STATUS = ? ";
						pstmt2 = conn.prepareStatement(sql);
						pstmt2.setString(1, tempOrder);
						pstmt2.setString(2, "Y");
						rs2 = pstmt2.executeQuery();
						if( rs2.next())
						{
						 	update = pstmt1.executeUpdate();
						 	if( pstmt1 != null )
						 	{
						 		pstmt1.close();
						 		pstmt1 = null;
						 	}
						 	if( update > 0 )
				 			{
						 		System.out.println(update +"R-DSA is updated ");
				 			}
						}
						if(rs2 != null)
						{
							rs2.close();
							rs2 = null;
						}
						if(pstmt2 != null)
						{
							pstmt2.close();
							pstmt2 = null;
						}
						
					}
					//Changed by sumit on 17/11/12 updating ref_id in case of null pick_order in repl_ord_det ( not dependent) start.
					else if( tempOrder.trim().length() == 0 && "R-CPA".equalsIgnoreCase(refSer))
					{
						update = pstmt1.executeUpdate();
					 	if( pstmt1 != null )
					 	{
					 		pstmt1.close();
					 		pstmt1 = null;
					 	}
					 	if( update > 0 )
			 			{
					 		System.out.println(update +" ref_ser R-CPA  is updated ");
			 			}
					}
					//Changed by sumit on 17/11/12 updating ref_id in case of null pick_order in repl_ord_det ( not dependent) end.
					if( pstmt1 != null )
				 	{
				 		pstmt1.close();
				 		pstmt1 = null;
				 	}
					//Changed by sumit on 17/11/12 updating ref_id in case of null pick_order in repl_ord_det ( not dependent) start.
					
				}
				//Changed by Pragyan 07/03/13 To check "P-PICK" as case pick created or held
				//else if( "A-PICK".equalsIgnoreCase(refSer) || "C-PICK".equalsIgnoreCase(refSer) || "M-PICK".equalsIgnoreCase(refSer))
				else if( "A-PICK".equalsIgnoreCase(refSer) || "C-PICK".equalsIgnoreCase(refSer) || "M-PICK".equalsIgnoreCase(refSer) || "P-PICK".equalsIgnoreCase(refSer))
				{
					tempOrder = "";
					sql1 = "SELECT REPL_ORDER FROM PICK_ORD_DET WHERE PICK_ORDER = ? ";
					//sql1 = "SELECT PICK_ORDER FROM REPL_ORD_DET WHERE PICK_ORDER = ? ";
					pstmt2 = conn.prepareStatement(sql1);
					pstmt2.setString(1, refId);
					rs2 = pstmt2.executeQuery();
					//Changed by sumit on 28/01/13 On multiple location status check start
					/*if( rs2.next())
					{
						tempOrder = checkNull(rs2.getString("REPL_ORDER"));
					}
					System.out.println(" tempOrder ---**->["+tempOrder+"]");
					if(rs2 != null)
					{
						rs2.close();
						rs2 = null;
					}
					if(pstmt2 != null)
					{
						pstmt2.close();
						pstmt2 = null;
					}
					
					sql1 = "UPDATE WAVE_TASK_DET SET WAVE_STATUS = 'C' WHERE REF_ID = ? AND WAVE_ID = ? AND SALE_ORDER = ?";
					pstmt2 = conn.prepareStatement(sql1);
					pstmt2.setString(1, refId);
					pstmt2.setString(2, waveId);
					pstmt2.setString(3, saleOrder);	
					
					if(tempOrder.trim().length() > 0)
					{
						String conf = "";					
						sql = 	" SELECT STATUS FROM WAVE_TASK_DET WHERE REF_ID = ?";
						
						pstmt1 = conn.prepareStatement(sql);
						pstmt1.setString(1, tempOrder);					
						rs1 = pstmt1.executeQuery();
						if( rs1.next())
						{
							conf = checkNull(rs1.getString("STATUS"));
							System.out.println(" conf -> ["+conf+"]");								
							if( "Y".equalsIgnoreCase(conf))
							{
								update = pstmt2.executeUpdate();
							}
						}					
						if( pstmt1 != null)
						{
							pstmt1.close();
							pstmt1 = null;
						}
						if( rs1 != null)
						{
							rs1.close();
							rs1 = null;
						}
					}	
					else
					{
						update = pstmt2.executeUpdate();
					}*/
					
					Set isReplConfirmed = new HashSet();
					while( rs2.next())
					{
						tempOrder = checkNull(rs2.getString("REPL_ORDER"));					
						System.out.println(" tempOrder ---**->["+tempOrder+"]");						
						if(tempOrder.trim().length() > 0)
						{
							String conf = "";
							
							sql = 	" SELECT STATUS FROM WAVE_TASK_DET WHERE REF_ID = ?";							
							pstmt1 = conn.prepareStatement(sql);
							pstmt1.setString(1, tempOrder);					
							rs1 = pstmt1.executeQuery();
							if( rs1.next())
							{
								conf = checkNull(rs1.getString("STATUS"));
								System.out.println(" conf -> ["+conf+"]");								
								if( "Y".equalsIgnoreCase(conf))
								{
									//update = pstmt3.executeUpdate();
									isReplConfirmed.add("true");
								}
								else
								{
									isReplConfirmed.add("false");
								}
							}					
							if( pstmt1 != null)
							{
								pstmt1.close();
								pstmt1 = null;
							}
							if( rs1 != null)
							{
								rs1.close();
								rs1 = null;
							}
						}	
						else
						{
							//update = pstmt3.executeUpdate();
							isReplConfirmed.add("true");
						}
					}
					System.out.println(" isReplConfirmed "+isReplConfirmed);
					if( !isReplConfirmed.contains("false"))
					{
						
						//Changed By Pragyan 06/03/13 To update wave status only if it is "N"
						//sql1 = "UPDATE WAVE_TASK_DET SET WAVE_STATUS = 'C' WHERE REF_ID = ? AND WAVE_ID = ? AND SALE_ORDER = ? ";
						sql1 = "UPDATE WAVE_TASK_DET SET WAVE_STATUS = 'C' WHERE REF_ID = ? AND WAVE_ID = ? AND SALE_ORDER = ? AND STATUS = 'N'";
						pstmt1 = conn.prepareStatement(sql1);
						pstmt1.setString(1, refId);
						pstmt1.setString(2, waveId);
						pstmt1.setString(3, saleOrder);	
						if( pstmt1.executeUpdate() > 0 )							
						{
							System.out.println(refId +" is updated successfully ");
						}
						pstmt1.close(); pstmt1 = null;
						
					}					
					
					
					if(rs2 != null)
					{
						rs2.close();
						rs2 = null;
					}
					if(pstmt2 != null)
					{
						pstmt2.close();
						pstmt2 = null;
					}
					if(pstmt1 != null)
					{
						pstmt1.close();
						pstmt1 = null;
					}
					//Changed by sumit on 28/01/13 On multiple location status check end.
				}
				else if("R-CAPK".equalsIgnoreCase(refSer) )
				{					
					sql =   " SELECT ROD.ITEM_CODE, ROD.SITE_CODE, ROD.LOC_CODE, ROD.LOT_NO, ROD.LOT_SL FROM REPL_ORD_DET ROD, STOCK S " +
							" WHERE ROD.ITEM_CODE = S.ITEM_CODE " +
							" AND ROD.SITE_CODE = S.SITE_CODE " +
							" AND ROD.LOT_NO = S.LOT_NO " +
							" AND ROD.LOT_SL = S.LOT_SL " +
							" AND ROD.REPL_ORDER = ? " +
							" AND S.QUANTITY > 0 ";
					pstmt1 = conn.prepareStatement(sql);
					pstmt1.setString(1, refId);
					//pstmt1.setString(2, saleOrder);
					rs1 = pstmt1.executeQuery();
					if( rs1.next())
					{		
						// AND STATUS = 'N'
						//sql1 = "UPDATE WAVE_TASK_DET SET WAVE_STATUS = 'C' WHERE REF_ID = ? AND STATUS = 'N'";
						pstmt2 = conn.prepareStatement(sql1);
						pstmt2.setString(1, refId);						
						update = pstmt2.executeUpdate();
						System.out.println(" updated ******->"+update);
						if(pstmt2 != null)
						{
							pstmt2.close();
							pstmt2 = null;
						}
					}
				}
				else if("S-DSP".equalsIgnoreCase(refSer) )
				{
					if(directPickLoc != null && directPickLoc.length() > 0)
					{
						sql1 = "UPDATE WAVE_TASK_DET SET WAVE_STATUS = 'C' WHERE REF_ID = ? AND WAVE_ID = ? AND SALE_ORDER = ? AND STATUS = 'N'";
						pstmt1 = conn.prepareStatement(sql1);
						pstmt1.setString(1, refId);
						pstmt1.setString(2, waveId);
						pstmt1.setString(3, saleOrder);	
						if( pstmt1.executeUpdate() > 0 )							
						{
							System.out.println(refId +" is updated successfully ");
						}
						pstmt1.close(); pstmt1 = null;
					}
				}
				
				if(pstmt1 != null)
				{
					pstmt1.close();
					pstmt1 = null;
				}
				if(rs1 != null)
				{
					rs1.close();
					rs1 = null;
				}
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			if( pstmt2 != null )
			{
				pstmt2.close();
				pstmt2 = null;
			}
			if( rs2 != null)
			{
				rs2.close();
				rs2 = null;
			}
			if( rs3 != null)
			{
				rs3.close();
				rs3 = null;
			}
			//Changed by sumit on 30/07/12 giving input END.	
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(pstmt1 != null)
				{
					pstmt1.close();
					pstmt1 = null;
				}
				if(rs1 != null)
				{
					rs1.close();
					rs1 = null;
				}
				if( pstmt2 != null )
				{
					pstmt2.close();
					pstmt2 = null;
				}
				if( rs2 != null)
				{
					rs2.close();
					rs2 = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				if( rs3 != null)
				{
					rs3.close();
					rs3 = null;
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return errString;
	}	
	//Changed by sumit on 23/08/12n update wave_status as per their sequence of task end.
	public ArrayList getActiveCaseReplMap(String replType ,String locInvstat,String pndInvstat,String deepStoreInvstat,String reserveInvstat,String itemCode,String siteCode,String locCode,String lotNo,String lotSl,double reqQuantity,Connection conn) throws Exception
	{
	
		PreparedStatement pstmt = null;
		ResultSet rs = null;
	    String sql = "",sqlPnd = "";
	   
		double quantity = 0.0;
		double actuaQty = 0.0;
		String LocCodeTo = ""; 
		String replOrder = "";
		String replLineNo = "";
		String pickOrder = "";
		String lineNoPick = "";
		ArrayList tempList = new ArrayList();
		
		try
		{

				if(replType == "")
				{
					sql= "SELECT R.REPL_ORDER,R.LINE_NO,R.PICK_ORDER,R.LINE_NO__PICK,R.LOC_CODE__TO,R.ACTUAL_QTY FROM REPL_ORD_DET R WHERE R.ITEM_CODE = ? AND R.SITE_CODE = ? "
						//Change by Rohan on 20-02-13 not select uncacle repanishment.	
						//+" AND R.LOC_CODE = ? AND R.LOT_NO = ? AND R.LOT_SL = ? AND R.REPL_TYPE IS NULL AND R.ACTUAL_QTY > 0";
					     +" AND R.LOC_CODE = ? AND R.LOT_NO = ? AND R.LOT_SL = ? AND CASE WHEN R.CANCEL_MODE IS NULL THEN 'N' ELSE R.CANCEL_MODE END <> 'Y' AND R.REPL_TYPE IS NULL AND R.ACTUAL_QTY > 0 ";
				}
				else
				{
					sql= "SELECT R.REPL_ORDER,R.LINE_NO,R.PICK_ORDER,R.LINE_NO__PICK,R.LOC_CODE__TO,R.ACTUAL_QTY FROM REPL_ORD_DET R WHERE R.ITEM_CODE = ? AND R.SITE_CODE = ? "
							//Chnage by Rohan on 20-02-13 not select uncacel repanishment	
						//+" AND R.LOC_CODE = ? AND R.LOT_NO = ? AND R.LOT_SL = ? AND R.REPL_TYPE = ? AND R.ACTUAL_QTY > 0";
						+" AND R.LOC_CODE = ? AND R.LOT_NO = ? AND R.LOT_SL = ? AND CASE WHEN R.CANCEL_MODE IS NULL THEN 'N' ELSE R.CANCEL_MODE END <> 'Y' AND R.REPL_TYPE = ? AND R.ACTUAL_QTY > 0";
				}
				
				
				//sqlPnd = "SELECT R.REPL_ORDER,R.LINE_NO,R.PICK_ORDER,R.LINE_NO__PICK,R.LOC_CODE__TO,R.ACTUAL_QTY FROM REPL_ORD_DET R,lOCATION L WHERE R.REPL_ORDER = ? AND R.LINE_NO = ?";
				
			/*else if(replType.equalsIgnoreCase("I"))
			{
				
			}*/
			
			
			pstmt =  conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			pstmt.setString(2, siteCode);
			pstmt.setString(3, locCode);
			pstmt.setString(4, lotNo);
			pstmt.setString(5, lotSl);
			if(replType != "")
			{
				pstmt.setString(6, replType);
			}
			
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				System.out.println("case1");
				replOrder =  checkNull(rs.getString("REPL_ORDER"));
				replLineNo =  checkNull(rs.getString("LINE_NO"));
				pickOrder = checkNull(rs.getString("PICK_ORDER"));
				lineNoPick = checkNull(rs.getString("LINE_NO__PICK"));
				LocCodeTo = checkNull(rs.getString("LOC_CODE__TO"));
				actuaQty = rs.getDouble("ACTUAL_QTY");
				
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			
			//if((replType.equalsIgnoreCase("I") || replType == "") && ( pickOrder != null && pickOrder.length() > 0))
			if(replType.equalsIgnoreCase("I") || locInvstat.equalsIgnoreCase(deepStoreInvstat))
			{
				
				
				
				
				if(replType == "I")
				{
					sqlPnd = "SELECT R.REPL_ORDER,R.LINE_NO,R.PICK_ORDER,R.LINE_NO__PICK,R.LOC_CODE__TO,R.ACTUAL_QTY FROM REPL_ORD_DET R,lOCATION L WHERE R.PICK_ORDER = ? AND L.LOC_CODE = R.LOC_CODE AND R.LINE_NO__PICK = ?";
					System.out.println("case2");
					pstmt =  conn.prepareStatement(sqlPnd);
					pstmt.setString(1, replOrder);
					pstmt.setString(2, replLineNo);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						replOrder =  checkNull(rs.getString("REPL_ORDER"));
						replLineNo =  checkNull(rs.getString("LINE_NO"));
						pickOrder = checkNull(rs.getString("PICK_ORDER"));
						lineNoPick = checkNull(rs.getString("LINE_NO__PICK"));
						LocCodeTo = checkNull(rs.getString("LOC_CODE__TO"));
					}
				}
				else
				{
					sqlPnd = "SELECT R.REPL_ORDER,R.LINE_NO,R.PICK_ORDER,R.LINE_NO__PICK,R.LOC_CODE__TO,R.ACTUAL_QTY FROM REPL_ORD_DET R,lOCATION L " +
							" WHERE R.PICK_ORDER = ? AND R.LINE_NO__PICK = ? AND L.LOC_CODE = R.LOC_CODE AND L.INV_STAT = ?";
					System.out.println("case2");
					pstmt =  conn.prepareStatement(sqlPnd);
					pstmt.setString(1, replOrder);
					pstmt.setString(2, replLineNo);
					pstmt.setString(3, pndInvstat);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						replOrder =  checkNull(rs.getString("REPL_ORDER"));
						replLineNo =  checkNull(rs.getString("LINE_NO"));
						pickOrder = checkNull(rs.getString("PICK_ORDER"));
						lineNoPick = checkNull(rs.getString("LINE_NO__PICK"));
						LocCodeTo = checkNull(rs.getString("LOC_CODE__TO"));
					}
				}
				
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
		
				
			
			
			if(LocCodeTo != null && LocCodeTo.length() > 0)
			{
				System.out.println("case3");
				tempList.add(LocCodeTo);
				tempList.add(actuaQty);
				tempList.add(replOrder);
				tempList.add(replLineNo);
				tempList.add(pickOrder);
				tempList.add(lineNoPick);
			}
					
        }
		catch(Exception e)
		{
			throw e;
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e2)
			{
				throw new ITMException(e2);
			}
		
		}
	return tempList;  	
	}
	
	public int updateReplOrdDet(String replType,String itemCode,String siteCode,String locCode,String lotNo,String lotSl,String locCodeTo ,double reqQuantity,String replOrder,Connection conn) throws Exception
	{
	
		PreparedStatement pstmt = null;
		ResultSet rs = null;
	    String sql = "";
	   
		double quantity = 0.0;
		double actuaQty = 0.0;
		String LocCodeTo = ""; 
		String replLineNo = "";
		ArrayList tempList = new ArrayList();
		int updatedRecordCount = 0 ;
		try
		{
			sql= "UPDATE REPL_ORD_DET SET ACTUAL_QTY = ?,REPL_TYPE = ? WHERE ITEM_CODE = ?" +
					" AND LOC_CODE = ? AND SITE_CODE = ? AND LOT_NO = ? AND LOT_SL = ? AND REPL_ORDER = ?" ;
					//"AND LOC_CODE__TO = ?";
			
			
			pstmt =  conn.prepareStatement(sql);
			pstmt.setDouble(1, reqQuantity);
			pstmt.setString(2, replType);
			pstmt.setString(3, itemCode);
			pstmt.setString(4, locCode);
			pstmt.setString(5, siteCode);
			pstmt.setString(6, lotNo);
			pstmt.setString(7, lotSl);
			pstmt.setString(8, replOrder);
			updatedRecordCount = pstmt.executeUpdate();
					
        }
		catch(Exception e)
		{
			throw e;
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e2)
			{
				throw new ITMException(e2);
			}
		
		}
	return updatedRecordCount;  	
	}
	//Chnged by Rohan on 09/03/12 to get Volume & weight form pack code.start
	
	public int updateMasterCarton(String pickRefId,String packRefId,int masterCount,Connection conn) throws Exception
	{
	
		PreparedStatement pstmt = null;
		PreparedStatement pstmtPick = null;
		ResultSet rs = null;
		ResultSet rsPick = null;
	    String sql = "";
	    String  sQLPick = "";
	    String cartonNo = "";
	    String masterCartonNo = "";
		int updatedRecordCount = 0 ;
		
		try
		{
			
			sQLPick = "SELECT CARTON_NO FROM CARTON_MASTER WHERE PICK_ORDER = ?  AND MASTER_CARTON IS NULL"  
					+" AND ROWNUM <= ? ORDER BY CARTON_NO "; 
			
			
			
			sql=	" UPDATE CARTON_MASTER SET MASTER_CARTON = (SELECT CARTON_NO FROM CARTON_MASTER WHERE PICK_ORDER =?)"
					+ " WHERE PICK_ORDER = ? AND CARTON_TYPE='C' AND CARTON_NO = ? AND MASTER_CARTON IS NULL ";
			pstmt =  conn.prepareStatement(sql);
			pstmtPick =  conn.prepareStatement(sQLPick);
			
			pstmtPick.setString(1, pickRefId);
			pstmtPick.setInt(2, masterCount);

			
			rsPick = pstmtPick.executeQuery();
			
			while(rsPick.next())
			{
				cartonNo = rsPick.getString("CARTON_NO");
				
				pstmt.setString(1, packRefId);
				pstmt.setString(2, pickRefId);
				pstmt.setString(3, cartonNo);
				updatedRecordCount = pstmt.executeUpdate();
				pstmt.clearParameters();
				
				System.out.println("Currently Updated Count on carton Master["+updatedRecordCount+"]");
			}
		
			
					
        }
		catch(Exception e)
		{
			throw e;
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if(rsPick != null)
				{
					rsPick.close();
					rsPick = null;
				}
				if(pstmtPick != null)
				{
					pstmtPick.close();
					pstmtPick = null;
				}
			}
			catch(Exception e2)
			{
				throw new ITMException(e2);
			}
		
		}
	return updatedRecordCount;  	
	}
	private String getPackItemVolumeWeight(double weight,double volume, String packType,Connection conn)throws Exception
	{
		
		String sql = "",sSQL = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		PreparedStatement pstmt1 = null;
		ResultSet rs1 = null;
		double volumeItem = 0.0;
		double weightItem = 0.0;
			
		try
		{
			
			sql= "SELECT GROSS_WEIGHT,LENGTH*WIDTH*HEIGHT AS VOLUME "+
		 		" FROM PACKING WHERE " +
		 		"LENGTH*WIDTH*HEIGHT>=? and "+
		 		"GROSS_WEIGHT= ( SELECT MIN(GROSS_WEIGHT) " +
		 		"FROM PACKING WHERE " +
		 		"LENGTH*WIDTH*HEIGHT =(SELECT MIN(LENGTH*WIDTH*HEIGHT) "+ 
		 		"VOLUME FROM PACKING WHERE " +
		 		"GROSS_WEIGHT>=? AND LENGTH*WIDTH*HEIGHT>=? AND PACK_TYPE IN(?,'B') ) AND PACK_TYPE IN(?,'B')  ) AND PACK_TYPE IN(?,'B') "+
		 		"ORDER BY LENGTH*WIDTH*HEIGHT";
			
			sSQL = "SELECT GROSS_WEIGHT,LENGTH*WIDTH*HEIGHT AS VOLUME "
					+" FROM PACKING WHERE PACK_TYPE IN( ?,'B') AND ( LENGTH*WIDTH*HEIGHT) > 0   AND GROSS_WEIGHT > 0 "
					+" ORDER BY LENGTH*WIDTH*HEIGHT DESC";
			
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setDouble(1, volume);
			pstmt.setDouble(2, weight);
			pstmt.setDouble(3, volume);
			pstmt.setString(4, packType);
			pstmt.setString(5, packType);
			pstmt.setString(6, packType);
		
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				weightItem = Math.floor( rs.getDouble("GROSS_WEIGHT"));
				volumeItem = Math.floor( rs.getDouble("VOLUME"));
			}
			else
			{
				pstmt1 = conn.prepareStatement(sSQL);
				pstmt1.setString(1, packType);
				
				rs1 = pstmt1.executeQuery();
				
				if(rs1.next())
				{
					weightItem = Math.floor( rs1.getDouble("GROSS_WEIGHT"));
					volumeItem = Math.floor( rs1.getDouble("VOLUME"));
				}
				
				if(rs1 != null)
				{
					rs1.close();
					rs1 = null;
				}
				if(pstmt1 != null)
				{
					pstmt1.close();
					pstmt1 = null;
				}
			}
			
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		finally
		{			
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			
				
			}
			catch(Exception e)
			{
				throw new Exception();		
			}
		}
		
		return weightItem+":"+volumeItem;
	}
	//Chnged by Rohan on 09/03/12 to get Volume & weight form pack code.end
	//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header
	//public int updateReplOrdDet(String replType,String itemCode,String siteCode,String locCode,String lotNo,String lotSl,String locCodeTo ,double reqQuantity,String replOrder,Connection conn) throws Exception
public int updateReplOrdDet(String replType,String itemCode,String siteCode,String locCode,String lotNo,String lotSl,String locCodeTo ,double reqQuantity,String replOrder,String replLineNo,Connection conn) throws Exception
{

	PreparedStatement pstmt = null;
	ResultSet rs = null;
    String sql = "";
   
	double quantity = 0.0;
	double actuaQty = 0.0;
	String LocCodeTo = ""; 
	//Changed by Rohan on 13-09-12 to generate only one Repalnishmement Header
	//String replLineNo = "";
	ArrayList tempList = new ArrayList();
	int updatedRecordCount = 0 ;
	try
	{
		sql= "UPDATE REPL_ORD_DET SET ACTUAL_QTY = ?,REPL_TYPE = ? WHERE ITEM_CODE = ?" +
				//" AND LOC_CODE = ? AND SITE_CODE = ? AND LOT_NO = ? AND LOT_SL = ? AND REPL_ORDER = ?" ;
				" AND LOC_CODE = ? AND SITE_CODE = ? AND LOT_NO = ? AND LOT_SL = ? AND REPL_ORDER = ? AND LINE_NO = ?" ;
				//"AND LOC_CODE__TO = ?";
		
		
		pstmt =  conn.prepareStatement(sql);
		pstmt.setDouble(1, reqQuantity);
		pstmt.setString(2, replType);
		pstmt.setString(3, itemCode);
		pstmt.setString(4, locCode);
		pstmt.setString(5, siteCode);
		pstmt.setString(6, lotNo);
		pstmt.setString(7, lotSl);
		pstmt.setString(8, replOrder);
		pstmt.setInt(9, Integer.parseInt(replLineNo));
		updatedRecordCount = pstmt.executeUpdate();
				
    }
	catch(Exception e)
	{
		throw e;
	}
	finally
	{
		try
		{
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
		}
		catch(Exception e2)
		{
			throw new ITMException(e2);
		}
	
	}
return updatedRecordCount;  	
}
//Chnged by Rohan on 09/03/12 to get Volume & weight form pack code.start

//Chnged by sumit on 24/11/12 to get label print start
private String generatedLabelPrint(String waveId, String printer, Connection conn) throws ITMException
{
	
		String errString ="";
    	String printMode = "";
    	String outputFilename = "";
    	TreeMap argMap = null;
    	String isReplenishment = "N";
    	String saleOrder = "";
    	PreparedStatement pstmt = null;
    	ResultSet rs = null;
    	
    	try
    	{
    		
    		//Changed as per sagar baht for hardcode passing the value "N" for repleneishment.start
    		/*//Changed by sumit 06/10/12 for getting sale order value start.
    		sql = " SELECT REPL_ORDER FROM REPL_ORD_HDR WHERE WAVE_ID = ? ";
    		pstmt = conn.prepareStatement(sql);
    		pstmt.setString(1, waveId);
    		rs = pstmt.executeQuery();
    		if( rs.next())
    		{
    			isReplenishment = "Y";
    		}
    		else
    		{
    			isReplenishment = "N";
    		}
    		pstmt.close();pstmt = null;
    		rs.close(); rs = null;	*/
    		//Changed as per sagar baht for hardcode passing the value "N" for repleneishment.end
    		
			String reportObjName = discommon.getDisparams("999999","WAVE_LABEL_OBJ_NAME",conn);			
			System.out.println("Printer *->["+printer.trim()+"]  report_obj_name ["+reportObjName+"] wave id ->["+waveId+"]");		
			ibase.webitm.reports.utility.JasperReportGenerator jrGenerator = new ibase.webitm.reports.utility.JasperReportGenerator();
			String xsdString ="<Arguments>" +
						"<Argument id=\"WAVE_ID\" name=\"WAVE_ID\">" +
						"<argType>java.lang.String</argType>" +								
						"<value>"+waveId+"</value>" +
						"</Argument>" +
						"<Argument id=\"PRINTVAL\" name=\"PRINTVAL\">" +
						"<argType>java.lang.String</argType>" +
						//"<value>"+ptcnList.get(i)+"</value>" +
						"<value>"+isReplenishment+"</value>" +
						"</Argument>" +
						"<Argument id=\"x_path\" name=\"x_path\">" +
						"<argType>java.lang.String</argType>" +
						"<value>/DocumentRoot/pick_label</value>" +
						"</Argument>" +
						"<Argument id=\"design_source\" name=\"design_source\">" +
						"<argType>java.lang.String</argType>" +
						"<value>pick_label.jrxml</value>" +
						"</Argument>" +
						"<Argument id=\"data_source\" name=\"data_source\">" +
						"<argType>java.lang.String</argType>" +
						"<value>SQL</value>" +
						"</Argument>" +
						"<Argument id=\"bind_type\" name=\"bind_type\">" +
						"<argType>java.lang.Integer</argType>" +
						"<value>0</value>" +
						"</Argument>" +
						"<Argument id=\"report_type\" name=\"report_type\">" +
						"<argType>java.lang.String</argType>" +
						"<value>JASPER</value>" +
						"</Argument>" +
						"<Argument id=\"report_save_type\" name=\"report_save_type\">" +
						"<argType>java.lang.String</argType>" +									
						"<value>NATIVE</value>" +									
						"</Argument>" +
						"</Arguments>";
			System.out.println(" XSD parser **->["+xsdString+"]");									
			errString = jrGenerator.printReport(reportObjName, xsdString, chgUser, printer.trim(), 1, conn);			
			System.out.println(" PRINTING task completed--------**------->");		
				
			//}
	}
	catch(Exception e)
	{
		e.printStackTrace();
		throw new ITMException(e);
	}
	return errString;
}
//Chnged by sumit on 24/11/12 to get label print end.
//Changed by sumit on 10/12/12 suggesting active location for same item code and lot No. start.	
//Changed by sumit on 09/02/13 adding site code method parameter 
private String getPickLocForSameItemLotNo(String invStat, String pickType, String itemCode, String lotNo, String lotSl, String suggLocCode, String siteCode, Connection conn) throws ITMException
{
	 
	 String itemCodeTemp = "";
	 String lotNoTemp = "";
	 String lotSlTemp = "";
	 String locCodeTo = "";
	 String saleOrder = "";
	 String sql2 = "";// added by sumit on 08/02/13
	 boolean isLocAvail = false;// added by sumit on 08/02/13
	 double quantity = 0.0;
	 PreparedStatement pstmt = null, pstmt1 = null;
	 ResultSet rs = null, rs1 = null;
	 
	 try
	 {
	 	Set sordList = saleOrderWiseMap.keySet();
		Iterator it = sordList.iterator();			
		while(it.hasNext())
		{			
			String sorderKey = (String)it.next();			
			ArrayList itemMapList = (ArrayList)saleOrderWiseMap.get(sorderKey);
			saleOrder = sorderKey.substring(0,sorderKey.indexOf(":"));			
			System.out.println(" saleOrder ["+saleOrder+"] invStat ["+invStat+"]");			
			int itemMapListLen = itemMapList.size();				
			for(int i =0;i<itemMapListLen;i++)
			{					
				HashMap loadMap = (HashMap)itemMapList.get(i);
				//Changed by sumit on 07/03/13 adding condition.
				//if(itemCode.equalsIgnoreCase(loadMap.get("item_code").toString()) && lotNo.equalsIgnoreCase(loadMap.get("lot_no").toString()))
				if(itemCode.equalsIgnoreCase(loadMap.get("item_code").toString()) && lotNo.equalsIgnoreCase(loadMap.get("lot_no").toString()) && !isLocAvail)
				{					
					itemCodeTemp = (String)loadMap.get("item_code");
					lotNoTemp = (String)loadMap.get("lot_no");
					lotSlTemp = (String)loadMap.get("lot_sl");
					Map temp = new HashMap();
					temp.put("item_code", itemCodeTemp);
					temp.put("lot_no", lotNoTemp);
					//Changed by sumit on 08/02/13 adding site code in sql
					//sql = "SELECT LOC_CODE FROM STOCK WHERE ITEM_CODE = ? AND INV_STAT = ? AND LOT_NO = ? ";
					sql = "SELECT S.LOC_CODE FROM STOCK S, LOCATION L WHERE S.LOC_CODE = L.LOC_CODE AND S.ITEM_CODE = ? " +
							" AND S.SITE_CODE = ? AND L.INV_STAT = ? AND S.LOT_NO = ?  AND S.QUANTITY > 0 ";
					pstmt= conn.prepareStatement(sql);
					pstmt.setString(1, itemCode);
					//Changed by sumit on 08/02/13 
					pstmt.setString(2, siteCode);
					pstmt.setString(3,invStat);
					pstmt.setString(4, lotNo);
					rs = pstmt.executeQuery();
					if(rs.next())
					{	
						isLocAvail = true;
						locCodeTo = rs.getString("LOC_CODE");
						suggLocCode = locCodeTo;
						//Changed by sumit on 19/02/13 commenting not required 
						//temp.put("loc_code__to", locCodeTo);
					}
					rs.close(); rs = null;
					pstmt.close(); pstmt = null;
					System.out.println("  isLocAvail ["+isLocAvail+"]");
					//Changed by sumit on 06/03/13 checking whether repl pending for active suggetion start
					if( !isLocAvail)
					{											
						sql =   " SELECT ROD.REPL_ORDER, ROD.LOC_CODE__TO  FROM REPL_ORD_DET ROD, WAVE_TASK_DET WTD, WAVE_TASK WT, LOCATION L " +
								" WHERE ROD.ITEM_CODE = ? AND ROD.LOT_NO = ? AND ROD.LOC_CODE__TO = L.LOC_CODE AND L.INV_STAT = ? AND WTD.WAVE_ID = WT.WAVE_ID " +
								" AND WTD.REF_ID = ROD.REPL_ORDER AND CASE WHEN ROD.CANCEL_MODE IS NULL THEN 'N' ELSE ROD.CANCEL_MODE END <> 'Y' " +
								//Changed By sumit 02/04/13 To check wave status should not confirmed
								//" AND ROD.SITE_CODE = ? ";
								" AND ROD.SITE_CODE = ? AND WTD.STATUS = ?";
								
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, itemCodeTemp);
						pstmt.setString(2, lotNoTemp);
						pstmt.setString(3, invStat);
						pstmt.setString(4, siteCode);
						//Changed By sumit 02/04/13 To check wave status should not confirmed
						pstmt.setString(5, "N");
						rs = pstmt.executeQuery();
						if( rs.next())
						{	
							isLocAvail = true;
							locCodeTo = rs.getString("LOC_CODE__TO");
							suggLocCode = locCodeTo;
						}
						rs.close(); rs = null;
						pstmt.close(); pstmt = null;						
						
					}
					//Changed by sumit on 06/03/13 checking whether repl pending for active suggetion end
					//Changed by sumit on 08/02/13 checking zero stock stock start.
					/*if( !isLocAvail)
					{
						sql = "SELECT LOC_CODE FROM STOCK WHERE ITEM_CODE = ? AND INV_STAT = ? AND LOT_NO = ? AND SITE_CODE = ? AND QUANTITY = 0 ";
						pstmt= conn.prepareStatement(sql);
						
						sql2 = "SELECT SUM(QUANTITY) FROM STOCK WHERE SITE_CODE = ? " +
								" AND LOC_CODE = ? ";
						pstmt1= conn.prepareStatement(sql2);						
						pstmt1.setString(1,siteCode);
						pstmt1.setString(2, suggLocCode);						
						rs1 = pstmt1.executeQuery();
						if( rs1.next())
						{	
							quantity = rs1.getDouble(1);							
						}
						rs1.close(); rs1 = null;
						pstmt1.close(); pstmt1 = null;
						if( quantity ==0 )
						{
							isLocAvail = true;	
							locCodeTo = suggLocCode;
							temp.put("loc_code__to", suggLocCode);
						}
						System.out.println(" is 00000 avail ["+isLocAvail+"]");
					}*/		
					
					//Changed by sumit on 19/02/13 commenting if condition 
					/*if( !isLocAvail )
					{*/
						
						/*sql = "SELECT PD.LOC_CODE FROM PICK_ORD_DET PD, PICK_ORD_HDR PH WHERE " +
								" PH.PICK_ORDER  = PD.PICK_ORDER AND PH.PICK_TYPE = ? " +
								" AND PD.ITEM_CODE = ? AND PD.LOT_NO = ?";
						pstmt1 = conn.prepareStatement(sql);
						pstmt1.setString(1, "A");
						pstmt1.setString(2, itemCode);
						pstmt1.setString(3, lotNo);
						rs1 = pstmt1.executeQuery();
						if( rs1.next())
						{
							locCodeTo = rs1.getString("LOC_CODE");							
							suggLocCode = locCodeTo;
							temp.put("loc_code__to", locCodeTo);
						}
						else
						{*/
						//loop for already suggested location for same item and lot no.
							boolean isSame = false;
							if(pickSaleOrderDetail.size() > 0 && !isLocAvail)
							{
								Set lotSlKey = pickSaleOrderDetail.keySet();
								Iterator is = lotSlKey.iterator();
								//Changed by sumit on 19/02/13 using below code here and changed while condition start.
								//while(is.hasNext())								
								while(is.hasNext() && !isSame)
								{
								//Changed by sumit on 19/02/13 using below code here and changed while condition end.
									String lo = (String)is.next();
									System.out.println(" key is ["+lo+"]");								
									ArrayList lotSLLIST = (ArrayList) pickSaleOrderDetail.get(lo);
									locCodeTo = "";
									int temp1 = lotSLLIST.size();
									//Changed by sumit on 19/02/13 commenting this and written in above 
									//boolean isSame = false;
									for(int j = 0; j < temp1 ;j++)
									{
										HashMap loadMap2 = (HashMap)lotSLLIST.get(j);
										if(itemCode.equalsIgnoreCase(loadMap2.get("item_code").toString()) && lotNo.equalsIgnoreCase(loadMap2.get("lot_no").toString()))
										{
											//Changed by sumit on 07/03/13 for identify loc found
											isLocAvail = true;
											isSame = true;										
											temp.put("loc_code__to", loadMap2.get("loc_code__to").toString());
											break;
										}
									}								
									//Changed by sumit on 19/02/13 commenting not required, written below start
									/*if(!isSame)
									{										
										temp.put("loc_code__to", suggLocCode);
									}*/	
									//Changed by sumit on 19/02/13 commenting not required, written below end
								}
								//Changed by sumit on 19/02/13  written here above code start
								if(!isSame)
								{
									//Changed by sumit on 07/03/13 for identify loc found
									isLocAvail = true;
									temp.put("loc_code__to", suggLocCode);
								}
								//Changed by sumit on 19/02/13  written here above code end
							}
							else
							{
								//Changed by sumit on 07/03/13 for identify loc found
								isLocAvail = true;
								temp.put("loc_code__to", suggLocCode);
							}
						/*}
						if(pstmt1 != null)
						{
							pstmt1.close();
							pstmt1 = null;
						}
						if( rs1 != null )
						{
							rs1.close();
							rs1 = null;
						}*/
					//}
					ArrayList tempList = new ArrayList();
					tempList.add(temp);
					//Changed by sumit on 13/02/13 adding condition to add list in map
					//pickSaleOrderDetail.put((""+(pickSaleOrderDetail.size()+1)), tempList);
					if(!isSame && isLocAvail)
					{
						pickSaleOrderDetail.put((""+(pickSaleOrderDetail.size()+1)), tempList);	
					}
					System.out.println(" populated pickSaleOrderDetail "+pickSaleOrderDetail);
					
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
					if( rs != null )
					{
						rs.close();
						rs = null;
					}
				}					
				
			}
			
			/*if(pickSaleOrderDetail.size() == 1)
			{
				return suggLocCode;
			}
			else
			{*/
				Set lotSlKey = pickSaleOrderDetail.keySet();
				Iterator is = lotSlKey.iterator();			
				while(is.hasNext())
				{
					String lo = (String)is.next();
					System.out.println(" key iss ["+lo+"]");
					//ArrayList lotSLLIST = new ArrayList();
					ArrayList lotSLLIST = (ArrayList) pickSaleOrderDetail.get(lo);
					locCodeTo = "";
					int temp = lotSLLIST.size();
					for(int j = 0; j < temp ;j++)
					{
						HashMap loadMap2 = (HashMap)lotSLLIST.get(j);
						if(itemCode.equalsIgnoreCase(loadMap2.get("item_code").toString()) && lotNo.equalsIgnoreCase(loadMap2.get("lot_no").toString()))
						{								
							locCodeTo  =  loadMap2.get("loc_code__to").toString();
							System.out.println(" item_code ["+loadMap2.get("item_code").toString()+"] lotno ["+loadMap2.get("lot_no").toString()+"] locCodeTo["+locCodeTo+"]");
							return locCodeTo;
						}
					}
					
				}					
				/*if( locCodeTo.length() == 0)
				{						
					return locCodeTo = suggLocCode;
				}*/
			//}			
			
		}	
		
	 }
	 catch(Exception e)
	 {
		 e.printStackTrace();
		 throw new ITMException(e);
	 }	
	 finally
	 {
		 try
		 {
		 	if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
		 	if(pstmt1 != null)
			{
				pstmt1.close();
				pstmt1 = null;
			}			
			if( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( rs1 != null )
			{
				rs1.close();
				rs1 = null;
			}
		 }
		 catch(Exception es)
		 {
			 es.printStackTrace();
			 throw new ITMException(es);
		 }
	 }
	 return locCodeTo;
}
//Changed by sumit on 10/12/12 suggesting active location for same item code and lot No. end.

//Changed by sumit on 31/01/12 convert qty as per unit start
private double getStockQtyAfterConvert(String saleOrder, String lineNo,String itemCode,double quantity,int check, Connection conn) throws ITMException
{
	 String sql = "";
	 String itemUnit = "";
	 String orderUnit = "";
	 String unitStd = "";	 
	 double convQtyStduom = 0.0;
	 double newQty = 0.0;
	 double convFact = 0;
	 PreparedStatement pstmt = null;
	 ResultSet rs = null;
	 
	 try
	 {
		 //System.out.println(" -- saleOrder ["+saleOrder+"] lineNo ["+lineNo+"] itemCode ["+itemCode+"] ");
		 sql = "SELECT DISTINCT ITEM.UNIT ,SORDDET.UNIT AS ORDER_UNIT,SORDDET.UNIT__STD AS  UNIT__STD, " +
			 		" SORDDET.CONV__QTY_STDUOM FROM ITEM, SORDDET WHERE ITEM.ITEM_CODE = ? " +
			 		" AND SORDDET.SALE_ORDER = ? AND SORDDET.LINE_NO = ? AND ITEM.ITEM_CODE = SORDDET.ITEM_CODE ";
		 pstmt = conn.prepareStatement(sql);
		 pstmt.setString(1, itemCode);
		 pstmt.setString(2, saleOrder);
		 pstmt.setString(3, lineNo);
		 rs = pstmt.executeQuery();
		 if( rs.next())
		 {
			 itemUnit = rs.getString("UNIT");
			 orderUnit = rs.getString("ORDER_UNIT");
			 unitStd = rs.getString("UNIT__STD");
			 convQtyStduom = rs.getDouble("CONV__QTY_STDUOM");			
		 }
		 rs.close(); rs = null;
		 pstmt.close(); pstmt = null;
		 ArrayList convQtyList = new ArrayList();
		 
		 if(!orderUnit.equalsIgnoreCase(unitStd))
		 {
			if(convQtyStduom != 0 && check == 1)
			{
				convFact = convQtyStduom;
			}
			System.out.println(" orderUnit ["+orderUnit+"] itemUnit ["+itemUnit+"] unitStd ["+unitStd+"] convQtyStduom ["+convQtyStduom+"]  convFact["+convFact+"]");
			if( check == 1 )
			{
				convQtyList = new ArrayList();
				convQtyList = discommon.getConvQuantityFact(orderUnit, unitStd, itemCode, quantity, convFact,conn);
			}
			else if ( check == 2 )
			{
				convQtyList = new ArrayList();
				convQtyList = discommon.getConvQuantityFact(unitStd, orderUnit, itemCode, quantity, convFact,conn);
			}
			System.out.println("convQtyList = "+convQtyList);
			newQty = Double.parseDouble(convQtyList.get(1).toString());
			System.out.println("newQty ["+newQty+"]");
	
			if(newQty == -999999999)
			{
				newQty = 0;								
			}
			if (convQtyStduom == 0)
			{
				convQtyStduom= Double.parseDouble(convQtyList.get(0).toString());
			}
		 }
		 else
		 {
			 newQty = quantity;
		 }
		//pendingQty = meffQty;
		 
	 }
	 catch(Exception ex)
	 {
		 ex.printStackTrace();
		 throw new ITMException(ex);
	 }
	 return newQty;
 }
//Changed by sumit on 31/01/12 convert qty as per unit end
//Changed By Pragyan 26/02/13 For Master/Parcel convert.Start
private String getPalletNo(String siteCode,String lotNo, String lotSl,String itemCode,String oldPtcn , Connection conn) throws ITMException
{
	 String sql = "";
	 String palletNo = "";
	 PreparedStatement pstmt = null;
	 ResultSet rs = null;
	 
	 try
	 {
		 //System.out.println(" -- saleOrder ["+saleOrder+"] lineNo ["+lineNo+"] itemCode ["+itemCode+"] ");
		 sql =   " SELECT H.PALLET_NO FROM PICK_ISS_HDR H, PICK_ISS_DET D, WAVE_TASK_DET W,WAVE_TASK T "
				 + " WHERE T.WAVE_ID = W.WAVE_ID  AND W.REF_ID = H.PICK_ORDER  AND H.TRAN_ID = D.TRAN_ID "
				// + " AND D.SITE_CODE = ? AND D.LOT_NO =?  AND D.LOT_SL =?  AND D.ITEM_CODE = ?  AND T.CANCEL = ? ";
				 + " AND D.SITE_CODE = ? AND D.LOT_NO =?  AND D.LOT_SL =?  AND D.ITEM_CODE = ?  AND W.PTCN = ? AND H.PALLET_NO IS NOT NULL ";
		 pstmt = conn.prepareStatement(sql);
		 pstmt.setString(1, siteCode);
		 pstmt.setString(2, lotNo);
		 pstmt.setString(3, lotSl);
		 pstmt.setString(4, itemCode);
		 //pstmt.setString(5, "Y");
		 pstmt.setString(5, oldPtcn);
		 
		 rs = pstmt.executeQuery();
		 if( rs.next())
		 {
			 palletNo = rs.getString(1);
			
		 }
		 rs.close(); rs = null;
		 pstmt.close(); pstmt = null;	 
		 
	 }
	 catch(Exception ex)
	 {
		 ex.printStackTrace();
		 throw new ITMException(ex);
	 }
	 return palletNo;
 }
private void updatePalletNo(String PTCN,String palletNo , Connection conn) throws ITMException
{
	 String sql = "",sql1 = "";
	 PreparedStatement pstmt = null;
	 ResultSet rs = null;
	 
	 try
	 {
		 //System.out.println(" -- saleOrder ["+saleOrder+"] lineNo ["+lineNo+"] itemCode ["+itemCode+"] ");
		 sql =   "UPDATE CARTON_MASTER SET PALLET_NO = ? WHERE PTCN = ? AND CARTON_TYPE IN ('A','M')";
		 sql1 =   "UPDATE PALLET_NO SET STATUS = ? WHERE PALLET_NO = ?";
		 pstmt = conn.prepareStatement(sql);
		 pstmt.setString(1, palletNo);
		 pstmt.setString(2, PTCN);
		 int updCartonMaster = pstmt.executeUpdate();
		 
		 if(updCartonMaster > 0)
		 {
			 System.out.println("Updating Carton Master With the pallet No ["+palletNo+"]");
		 }
		 pstmt.close(); pstmt = null;	 
		 
		 pstmt = conn.prepareStatement(sql1);
		 pstmt.setString(1, "U");
		 pstmt.setString(2, palletNo);
		 int updPalletStatus = pstmt.executeUpdate();
		 
		 if(updPalletStatus > 0)
		 {
			 System.out.println("Updating Pallet No Table With the Table Status ["+updPalletStatus+"]");
		 }
		 
	 }
	 catch(Exception ex)
	 {
		 ex.printStackTrace();
		 throw new ITMException(ex);
	 }

 }
//Changed By Pragyan 26/02/13 For Master/Parcel convert.end

//Changed By Pragyan 14/03/13  For Active Transfer/update craton no in pack oder detail.start
private void updateActivePackingCarton(String pickOrder ,int pickLineNo,String activeCartonNo,String packCode, Connection conn) throws ITMException
{
	 String sql = "",sql1 = "";
	 PreparedStatement pstmt = null;
	 ResultSet rs = null;
	 int maxLineNo = 1;
	 int updLineCtr = 0; 
	 
	 try
	 {
		 //System.out.println(" -- saleOrder ["+saleOrder+"] lineNo ["+lineNo+"] itemCode ["+itemCode+"] ");
		 sql =   "SELECT MIN(LINE_NO) FROM PICK_ORD_DET WHERE PICK_ORDER = ? AND PACK_CODE IS NULL";
		 sql1 =   "UPDATE PICK_ORD_DET SET CARTON_NO = ?,PACK_CODE = ? WHERE PICK_ORDER = ? AND LINE_NO = ?";
		 pstmt = conn.prepareStatement(sql);
		 pstmt.setString(1, pickOrder);
		 
		 rs = pstmt.executeQuery();
		 
		 if(rs.next())
		 {
			 maxLineNo = rs.getInt(1);
		 }
		 pstmt.close(); pstmt = null;	 
		 rs.close(); rs = null;	 
		 pstmt = conn.prepareStatement(sql1);
		 
		 while(maxLineNo <= pickLineNo)
		 {
			 pstmt.setString(1,activeCartonNo);
			 pstmt.setString(2,packCode);
			 pstmt.setString(3,pickOrder);
			 pstmt.setInt(4,maxLineNo);
			 updLineCtr =  pstmt.executeUpdate();
			 if(updLineCtr > 0)
			 {
				 System.out.println("Updating Carton / Pack Code  ["+updLineCtr+"] For Lin No["+maxLineNo+"]Carton No["+activeCartonNo+"]Pack Code["+packCode+"]");
			 }
			 pstmt.clearParameters();
			 maxLineNo++;
		 }
		 pstmt.close(); pstmt = null;	 
		 
	 }
	 catch(Exception ex)
	 {
		 ex.printStackTrace();
		 throw new ITMException(ex);
	 }

 }
//Changed By Pragyan 14/03/13  For Active Transfer/ no in pack oder detail.end
}