/*
    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 ibase.webitm.utility.wms.CompareAllocQty;

import java.awt.image.BufferedImage;
import java.awt.print.PrinterJob;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;
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.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.imageio.ImageIO;
import javax.print.PrintService;

//import org.apache.fop.fo.properties.ForcePageCount;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import sun.misc.BASE64Decoder;

import com.adsionline.ADSIShippingWS.ADSIShippingLocator;
import com.adsionline.ADSIShippingWS.ADSIShippingSoap;
import com.adsionline.ADSIShippingWS.Address;
import com.adsionline.ADSIShippingWS.Carrier;
import com.adsionline.ADSIShippingWS.CommodityInfo;
import com.adsionline.ADSIShippingWS.Country;
import com.adsionline.ADSIShippingWS.EnumManifestAction;
import com.adsionline.ADSIShippingWS.EnumPackageType;
import com.adsionline.ADSIShippingWS.EnumTerms;
import com.adsionline.ADSIShippingWS.EnumTimeInTransit;
import com.adsionline.ADSIShippingWS.EnumUnitOfMeasure;
import com.adsionline.ADSIShippingWS.ImageRotation;
import com.adsionline.ADSIShippingWS.NameValuePair;
import com.adsionline.ADSIShippingWS.Package2;
import com.adsionline.ADSIShippingWS.PackageResult2;
import com.adsionline.ADSIShippingWS.ShipResponse;
import com.adsionline.ADSIShippingWS.ShipWithLabelType;
import com.adsionline.ADSIShippingWS.Shipment2;
import com.adsionline.ADSIShippingWS.ShipmentResult2;
import com.adsionline.ADSIShippingWS.ShipmentResultReturn2;

@javax.ejb.Stateless
public class WaveGenerationPrc extends ProcessEJB implements WaveGenerationPrcLocal,WaveGenerationPrcRemote //SessionBean
{
	String new_trackingNo = null;
	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 = "";
	// Changed by Megha on 22/01/2015 :D14JSUN007  batch_id for back order processing
    String batchID = null;    
	String saleOrderFr = null;
	String saleOrderTo = null;
	String postOrderFg = null;
	String 	sql = null;
	String 	sqlInsertData = null;
	String 	sqlInsertData1 = 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;
	ArrayList F = new ArrayList();
	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();	
	//Changed By Pragyan 11-AUG-14 To check and Facility Master implementation.start
	ibase.webitm.utility.wms.CommonWmsUtil commonWmsUtility = ibase.webitm.utility.wms.CommonWmsUtil.getInstance();
	
	private HashMap itemInfoMapForRepl = new HashMap();
	//Changed By Pragyan 16-APR-14 To store the active Repl Qty and  in same wave [taro live issue]
	private HashMap itemQtyMapForActiveRepl = new HashMap();
	ArrayList replanismentInfoList = new ArrayList();
	//ArrayList masterOrParclNoList = new ArrayList();
	ArrayList masterOrParclNoList = null ;
	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
	//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam.start
	Set<String> dsoLocationset = null;
	Set<String> pndLocationset = null;
	Set<String> caspkLocationset = null;
	Set<String> psoLocationset = null;
	Set<String> prsvLocationset = null;
	//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam.start
	//Global declared by Shipment2 shipment2 object
	ADSIShippingLocator locator = null;
	ADSIShippingSoap  soap = null;
	Shipment2 shipment2 = null;
	//Changed By Pragyan 18-DEC-13 To check ADSI Connection is required.(KB/Ashish mail Dt.121413) 
	String isADSIConnReq = "N";
	boolean isRemotePrintRptSrvCofigur = false;
	
	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); 				
			}
			long startTime2 = System.currentTimeMillis();
			rtrStr = getData(headerDom, detailDom, windowName, xtraParams);
			long endTime2 = System.currentTimeMillis();
			System.out.println("DIFFERANCE IN TIME FOR GET DATA IN SECONDS:::["+(endTime2-startTime2)/1000+"]");
			
		}
		catch (Exception e)
		{
			System.out.println("Exception :StockAllocationPrcEJB :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			rtrStr = e.getMessage();
		}
		return rtrStr; 
	}
	//Changed BY Pragyan 20JUL13 TO Optimize the code for Open  maximum open cursors.start
	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 minMaxSql = "",minMaxSqlLot = "";
		String resrvLoc  = "";
		String casePickLoc  = "";
		String activePickLoc  = "";
		String deepStoreLoc = "";
		String partialResrvLoc = "";
		String packInstr ="";	
		PreparedStatement pstmtStock = null;
		double balStockQtyTemp = 0.0,sordItemQty=0.0,balStk=0.0;
		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 = "";
		//Changed By Pragyan 14/08/14 for transporter code argument loc type parent. 
		String tranCodeInput = "";
		String locTypeParentInput = "";
		//Chnaged by Rohan on 21-08-13 for get data for min and max self life.start
		int maxSelfLife = 0;
		double meffQty = 0,convQtyStduom = 0 ,convFact = 0, quantity = 0.0;	
		String sqlFnManual = "",sqlTotHoldQty = "",sqlManQty = "";
		PreparedStatement pstmt1 = null,pstmtManul = null,pstmtHold = null,pstmtManQty = null;
		ResultSet rs2 = null,rsMan = null,rsHld = null,rsM = null;
		//changed by sankara on 04/02/14 getting order type
	    String saleOrdertype = "";
	    //changed by sankara on 26/09/14 getting order type
	    String siteCodeShip = "";
		//chnaged by pragyan on 15/10/14 for cold chain
	    String locTypeParent = "";
		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;
			
			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);  
	
			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);  

			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;
			}			

			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));
			globalParcelPackAllow = checkNull(genericUtility.getColumnValue("parcelpack_allow",headerDom));
			
			shipType = genericUtility.getColumnValue("ship_type",headerDom);
			directPickLoc = genericUtility.getColumnValue("direct_pick_loc",headerDom);
			
			printer = "";
			printer = checkNull(genericUtility.getColumnValue("printer_name",headerDom));
			printLabel = genericUtility.getColumnValue("print_label",headerDom);
			//changed by sankara on 04/02/14 for getting sale order type
			saleOrdertype = genericUtility.getColumnValue("order_type",headerDom);
			//Changed By Pragyan 14/08/14 for tran code argumnet and loc type parent start.
			tranCodeInput = checkNull(genericUtility.getColumnValue("tran_code",headerDom));
			locTypeParentInput = checkNull(genericUtility.getColumnValue("loc_type_parent",headerDom));
			
			System.out.println("saleOrdertype:::"+saleOrdertype);
			
			//Changed by Megha on 22/01/2015 :D14JSUN007  batch_id for back order processing..start
			batchID = checkNull(genericUtility.getColumnValue("batch_id",headerDom));
			System.out.println("batchID is ****:::"+batchID);
			
			
			getDataSql =" SELECT SORDER.CUST_CODE, CUSTOMER.CUST_NAME,SORDDET.LINE_NO, "
				       +"SORDER.SALE_ORDER,SORDER.DUE_DATE,SORDITEM.ITEM_CODE,"
					   +"ITEM.DESCR,SORDITEM.QUANTITY,"
				       //Changed By Pragyan 13-nov-13 to get pending qty
					   //+"(SORDITEM.QUANTITY - SORDITEM.QTY_DESP - SORDITEM.QTY_ALLOC) PENDING_QUANTITY,"
					   +" FN_GET_CONV_QTY(SORDER.SALE_ORDER, SORDDET.LINE_NO) PENDING_QUANTITY,"
					   +" SORDITEM.QTY_ALLOC,SORDDET.PACK_INSTR, "
					   +" SORDITEM.SITE_CODE,SORDITEM.EXP_LEV, "
					 //Changed by sankara on 01/08/13 single_lot also available in sales order  
					   // +"SORDER.PART_QTY AS PART_QTY, CUSTOMER.SINGLE_LOT AS SINGLE_LOT, SORDITEM.MIN_SHELF_LIFE AS MIN_SHELF_LIFE "//Gulzar 5/13/2012
					  //Chnaged by Rohan on 27-08-13 to get Max self life
					   //+"SORDER.PART_QTY AS PART_QTY, SORDER.SINGLE_LOT AS SINGLE_LOT, SORDITEM.MIN_SHELF_LIFE AS MIN_SHELF_LIFE "//Gulzar 5/13/2012
					   +"SORDER.PART_QTY AS PART_QTY, SORDER.SINGLE_LOT AS SINGLE_LOT, SORDITEM.MIN_SHELF_LIFE AS MIN_SHELF_LIFE ,  SORDITEM.MAX_SHELF_LIFE AS MAX_SHELF_LIFE"
					   +" ,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  "
					   +" ,ITEM.UNIT AS UNIT_STD ,SORDDET.UNIT ORDER_UNIT,SORDDET.UNIT__STD AS  UNIT__STD, SORDDET.CONV__QTY_STDUOM "
					   	//chnaged by pragyan on 15/10/14 for cold chain
					   //+" , SORDER.CUST_CODE__DLV, C.CUST_NAME AS CUST_DLV_NAME "
					   +" , SORDER.CUST_CODE__DLV, C.CUST_NAME AS CUST_DLV_NAME ,ITEM.LOC_TYPE__PARENT "
					   +"FROM SORDDET,SORDER,SORDITEM,CUSTOMER,ITEM , WAVE_TYPE,CUSTOMER C  "
					   +"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 Pragyan 17-SEP-13 To join the wave type with cust_code__dlv
					   //+"( CUSTOMER.WAVE_TYPE = WAVE_TYPE.WAVE_TYPE(+)) AND "
					   +"( C.WAVE_TYPE = WAVE_TYPE.WAVE_TYPE(+)) AND "
					   +" SORDITEM.SITE_CODE = ? AND "
					   +" ITEM.ITEM_SER >=? AND "
					   +" ITEM.ITEM_SER <=? AND "  
					   +" ITEM.ITEM_CODE >=? AND "
					   /*  +" ITEM.ITEM_CODE <=? AND "
					  	+" CUSTOMER.CUST_CODE >=? AND "*/
					 // Changed by Megha on 22/01/2015 :D14JSUN007  batch_id for back order processing..start
					   +" ITEM.ITEM_CODE <=? ";
					   System.out.println("new batch id is ---"+ batchID);
					   if(batchID.trim().length() > 0)
					   {
						   getDataSql = getDataSql + " AND SORDER.SALE_ORDER IN (SELECT DISTINCT SALE_ORDER FROM SORDALLOC WHERE BATCH_ID = ?)" ;
						   
					   }else if(batchID == null || batchID == "")
					   { 
						   getDataSql = getDataSql + " AND SORDER.SALE_ORDER >= ? AND SORDER.SALE_ORDER <= ? ";   
					   }
					  
					   getDataSql = getDataSql + " AND CUSTOMER.CUST_CODE >=? "
					   // Changed by Megha on 22/01/2015 :D14JSUN007  batch_id for back order processing..end 
					   +" AND CUSTOMER.CUST_CODE <=? AND "  
					   +" SORDER.CUST_CODE__DLV >=? AND " 	
					   +" SORDER.CUST_CODE__DLV <=? AND " 
					  // +" SORDER.SALE_ORDER >= ? AND "
					 //  +" SORDER.SALE_ORDER <= ? AND " 
					   +" SORDER.DUE_DATE >=  ?  AND" 
					   +" SORDER.DUE_DATE <= ? " 
					   +" AND SORDER.CUST_CODE__DLV = C.CUST_CODE "  
					   +" 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 CASE WHEN SORDDET.HOLD_FLAG IS NULL THEN 'N' ELSE SORDDET.HOLD_FLAG end <> 'Y'"
					   //Changed By Pragyan 13-nov-13 to get pending qty
					  // +" AND ((SORDITEM.QUANTITY - SORDITEM.QTY_DESP - SORDITEM.QTY_ALLOC > 0 ) "
					   +" AND ((FN_GET_CONV_QTY(SORDER.SALE_ORDER, SORDDET.LINE_NO) > 0 ) "
					   //FN_GET_CONV_QTY(SORDER.SALE_ORDER, SORDDET.LINE_NO)
					   +" OR (FN_CHECK_MANUAL_STOCK_ALLOC(SORDER.SALE_ORDER, SORDDET.LINE_NO) = 0 ) )"				   
					   +" AND SORDITEM.LINE_TYPE = 'I'";
					   //changed by sankara on 04/02/14 for getting sale order type start.
					   //+" ORDER BY SORDER.CUST_CODE,SORDER.SALE_ORDER,SORDITEM.ITEM_CODE__ORD"; 
			
						//Changed By Pragyan 14/08/14 for tran code argumnet and loc type parent start.
						if(locTypeParentInput != null && locTypeParentInput.length() > 0)
						{
							getDataSql = getDataSql + " AND SORDDET.LOC_TYPE = ITEM.LOC_TYPE AND ITEM.LOC_TYPE__PARENT = '"+locTypeParentInput+"'";
						}
						//Changed By Pragyan 14/08/14 for tran code argumnet and loc type parent end.
			
					   if( saleOrdertype != null && saleOrdertype.trim().length() > 0 )
					   {
						   System.out.println("ordtypeGetData::::::::"+saleOrdertype);
						   getDataSql = getDataSql + " AND TRIM ( SORDER.ORDER_TYPE ) = ? ORDER BY SORDER.CUST_CODE,SORDER.SALE_ORDER,SORDITEM.ITEM_CODE__ORD "; 
					   }
					   else
					   {
						   System.out.println("no sale order type");
						   getDataSql = getDataSql + " ORDER BY SORDER.CUST_CODE,SORDER.SALE_ORDER,SORDITEM.ITEM_CODE__ORD "; 
					   }
			          //changed by sankara on 04/02/14 for getting sale order type end.
				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+"]");
				
				long startTime = System.currentTimeMillis();
				
				pstmt = conn.prepareStatement(getDataSql);
				pstmt.setString(1,siteCode);
				pstmt.setString(2,itemSerFr);
				pstmt.setString(3,itemSerTo);
				pstmt.setString(4,itemCodeFr);
				pstmt.setString(5,itemCodeTo);
				//Changed by Megha on 22/01/2015 :D14JSUN007  batch_id for back order processing.start
				/*pstmt.setString(6,custCodeFr);
				pstmt.setString(7,custCodeTo);
				pstmt.setString(8,custCodeDlvFr); 	
				pstmt.setString(9,custCodeDlvTo); 
				pstmt.setString(10,saleOrderFr);
				pstmt.setString(11,saleOrderTo);
				pstmt.setTimestamp(12,dateFr);
				pstmt.setTimestamp(13,dateTo);
				//changed by sankara on 04/02/14 for getting sale order type start.
				if( saleOrdertype != null && saleOrdertype.trim().length() > 0 )
				{
					System.out.println("ordtypeGetData::::::::"+saleOrdertype);
					pstmt.setString(14,saleOrdertype);
				}*/
				if(batchID.trim().length() > 0 )
				{
					System.out.println("+batch id is :+" +batchID);
					pstmt.setString(6,batchID);
					pstmt.setString(7,custCodeFr);
					pstmt.setString(8,custCodeTo);
					
					pstmt.setString(9,custCodeDlvFr);
					pstmt.setString(10,custCodeDlvTo); 
					
					pstmt.setTimestamp(11,dateFr);
					pstmt.setTimestamp(12,dateTo);
					
					if( saleOrdertype != null && saleOrdertype.trim().length() > 0 )
					{
						System.out.println("ordtypeGetData::::::::"+saleOrdertype);
						pstmt.setString(13,saleOrdertype);
					}
				}else
				{
					pstmt.setString(6,saleOrderFr);
					pstmt.setString(7,saleOrderTo);
					pstmt.setString(8,custCodeFr);
					pstmt.setString(9,custCodeTo);
					
					pstmt.setString(10,custCodeDlvFr);
					pstmt.setString(11,custCodeDlvTo);
					
					pstmt.setTimestamp(12,dateFr);
					pstmt.setTimestamp(13,dateTo);
					
					if( saleOrdertype != null && saleOrdertype.trim().length() > 0 )
					{
						System.out.println("ordtypeGetData1::::::::"+saleOrdertype);
						pstmt.setString(14,saleOrdertype);
					}
				}
				//Changed by Megha on 22/01/2015 :D14JSUN007  batch_id for back order processing.end
				//changed by sankara on 04/02/14 for getting sale order type end.
				st = conn.createStatement();
				rs = pstmt.executeQuery();

			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  ";
     				//Changed By Pragyan 31/AUG/13
     				//Changed by Rohan on 27-08-13 for adding condition of min and max self life
     				//+"AND (MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE) > ? ) ";
     				//+" AND (MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE) BETWEEN  ? AND  ?  ) ";
			   	
			
			 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) ) >= ?) ";
			 				//Changed by Rohan on 27-08-13 for adding condition of min and max self life
			 				//+"AND (MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE) > ? ) ";
			 				//+" AND (MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE) BETWEEN  ? AND  ?  ) ";
			 				
			sqlTran = "SELECT TRAN_NAME FROM TRANSPORTER WHERE TRAN_CODE = ?";

			int count = 0;
			String partQty = "";
			String singleLot = "";
			String itemCode = "";
			String siteCode = "";
			int minSelfLife = 0;
			ResultSet rsStock = null;
			double pendingQty = 0d;
			boolean isActives = false;
			sqlFnManual = " SELECT FN_MANUAL_STOCK_FOR_EACHITEM(?,?) AS ALLOC_FLAG FROM DUAL";
			pstmtManul = conn.prepareStatement(sqlFnManual);
			sqlTotHoldQty = "SELECT SUM(HOLD_QTY) AS HOLD_QTY FROM STOCK WHERE ITEM_CODE = ? AND SITE_CODE = ?";
			pstmtHold = conn.prepareStatement(sqlTotHoldQty);
			sqlManQty = "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'";
			pstmtManQty = conn.prepareStatement(sqlManQty);
			
			
			if(rs.next())
			{
				do
				{
					minSelfLife = 0;
					//Chnaged by Rohan on 21-08-13 for get data for min and max self life
					maxSelfLife = 0;
					orderByStkStr = "";
					tranName = "";
					pickType = "";
					//shipType = genericUtility.getColumnValue("ship_type",headerDom);
					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");
					//Chnaged by Rohan on 21-08-13 for get max self life
					maxSelfLife = rs.getInt("MAX_SHELF_LIFE");
					
					System.out.println("minSelfLife["+minSelfLife+"]max self life["+maxSelfLife+"]");
					
					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("globalMasterPackAllow ["+globalMasterPackAllow+"] globalActivePickAllow ["+globalActivePickAllow+"] globalStockToDockAllow ["+globalStockToDockAllow+"]globalParcelPackAllow ["+globalParcelPackAllow+"]");
					System.out.println("masterPackAllow ["+masterPackAllow+"] activePickAllow ["+activePickAllow+"] stockToDockAllow ["+stockToDockAllow+"]parcelPackAllow ["+parcelPackAllow+"]");
					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+"]");
					//chnaged by pragyan on 15/10/14 for cold chain
					locTypeParent = rs.getString("LOC_TYPE__PARENT");
							
					if(unitStd != "")
					{
						mbaseUnit = unitStd;
					}
					
					quantity = rs.getDouble(8);
					if(!unit.equalsIgnoreCase(mbaseUnit))
					{
						if(convQtyStduom != 0)
						{
							convFact = convQtyStduom;
						}	
						
						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;
						if(unit != null && !"CS".equalsIgnoreCase(unit.trim()))
						{
							pendingQty = meffQty;
						}
						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;								
						}						
					}
					
					
					if(maxSelfLife > 0)
					{
						minMaxSql =  " AND (CEIL(MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE)) BETWEEN  ? AND  ?  ) ";
						minMaxSqlLot =  " AND (CEIL(MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE)) BETWEEN  ? AND  ?  ) ";
					}
					else
					{
						minMaxSql = "AND (CEIL(MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE)) > ? ) ";
						minMaxSqlLot =  "AND (CEIL(MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE)) > ? ) ";
					}
				
					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;				
					getTranInfo = new HashMap();
					saleOrderTran = rs.getString("SALE_ORDER");
					System.out.println("CURRENT PICK TYPE BEFORE["+pickType+"]ShipType["+shipType+"]");
					//changed by sankara on 30/07/14 validation for item lot pack size start.
					double itemSize = (Double)itemVolMap.get("ITEM_SIZE");
					System.out.println("itemsize:["+itemSize+"]");
					double lotSize = (Double)itemVolMap.get("LOT_SIZE");
					System.out.println("lotSize:["+lotSize+"]");
					double packweight = (Double)itemVolMap.get("PACK_WEIGHT");
					System.out.println("packweight:["+packweight+"]");

					if( itemSize == 0 || lotSize == 0 || itemWeight == 0 || packweight == 0 || packSize == 0   )
					{
						errString = getError(saleOrderTran + "]ItemCode["+itemCode+"]","VTINVDAETL",conn);
						return errString;
					}
					//changed by sankara on 30/07/14 validation for item lot pack size end.
					//if("Y".equalsIgnoreCase(globalMasterPackAllow))
					if("Y".equalsIgnoreCase(globalMasterPackAllow) || (globalMasterPackAllow.length() == 0 && "Y".equalsIgnoreCase(masterPackAllow)))
					{
						pickType = "M";
					}
					//else if("Y".equalsIgnoreCase(globalParcelPackAllow))
					if("Y".equalsIgnoreCase(globalParcelPackAllow) || (globalParcelPackAllow.length() == 0 && "Y".equalsIgnoreCase(parcelPackAllow)))
					{
						pickType = "P";
					}
					
					//Changed By Pragyan 14/08/14 for tran code and loc type parent start.
					if(tranCodeInput == null || tranCodeInput.trim().length() <= 0)
					{
						//Changed By Pragyan recursive call if master pack yes and as well as parcel pick yes.start			
						System.out.println("CURRENT PICK TYPE AFTER["+pickType+"]ShipType["+shipType+"]");					
						/*getTranInfo = getTransporterInfoMap(saleOrderTran, itemWeight * pendingQty, noArt, pickType, shipType, conn);
						tranCod = (String)getTranInfo.get("TRAN_CODE");*/
						//if("Y".equalsIgnoreCase(globalMasterPackAllow) && "Y".equalsIgnoreCase(globalParcelPackAllow))
						if(("Y".equalsIgnoreCase(globalMasterPackAllow) && "Y".equalsIgnoreCase(globalParcelPackAllow)) || (globalSingleLot.length() == 0 && "Y".equalsIgnoreCase(masterPackAllow) && "Y".equalsIgnoreCase(parcelPackAllow)))
						{
							
							System.out.println("searching for parcel transporter");
							pickType = "P";
							long startTime2 = System.currentTimeMillis();
							//chnaged by pragyan on 15/10/14 for cold chain
							//getTranInfo = getTransporterInfoMap(saleOrderTran, itemWeight * pendingQty, noArt, pickType, shipType, conn);
							getTranInfo = getTransporterInfoMap(saleOrderTran, itemWeight * pendingQty, noArt, pickType, shipType,locTypeParent, conn);
							long endTime2 = System.currentTimeMillis();
							System.out.println("DIFFERANCE IN TIME FOR GET TRANSPORTER INFO FOR PICKT TYPE P IN SECONDS:::["+(endTime2-startTime2)/1000+"]");
							
							if(!pickType.equalsIgnoreCase((String)getTranInfo.get("SHIP_TYPE")))
							{
								System.out.println("searching for master transporter");
								pickType = "M";
								long startTime3 = System.currentTimeMillis();
								//chnaged by pragyan on 15/10/14 for cold chain
								//getTranInfo = getTransporterInfoMap(saleOrderTran, itemWeight * pendingQty, noArt, pickType, shipType, conn);
								getTranInfo = getTransporterInfoMap(saleOrderTran, itemWeight * pendingQty, noArt, pickType, shipType,locTypeParent, conn);
								long endTime3 = System.currentTimeMillis();
								System.out.println("DIFFERANCE IN TIME FOR GET TRANSPORTER INFO FOR PICKT TYPE M IN SECONDS:::["+(endTime3-startTime3)/1000+"]");
							}
						}
						else
						{
							System.out.println("searching for  transporter["+pickType);
							long startTime4 = System.currentTimeMillis();
							//chnaged by pragyan on 15/10/14 for cold chain
							//getTranInfo = getTransporterInfoMap(saleOrderTran, itemWeight * pendingQty, noArt, pickType, shipType, conn);
							getTranInfo = getTransporterInfoMap(saleOrderTran, itemWeight * pendingQty, noArt, pickType, shipType,locTypeParent, conn);
							long endTime4 = System.currentTimeMillis();
							System.out.println("DIFFERANCE IN TIME FOR GET TRANSPORTER INFO FOR PICKT TYPE +"+pickType+" IN SECONDS:::["+(endTime4-startTime4)/1000+"]");
						}
					}
					else
					{
						getTranInfo = getArgTransporterInfoMap(saleOrderTran, itemWeight * pendingQty, noArt, pickType, shipType,tranCodeInput, conn);
					}
					//Changed By Pragyan 14/08/14 for tran code and loc type parent end.
					if(getTranInfo != null & getTranInfo.size() > 0)
					{
							tranCod = (String)getTranInfo.get("TRAN_CODE");
					}
					else
					{
						tranCod = "";
					}
					
					//Changed By Pragyan recursive call if master pack yes and as well as parcel pick yes.end	
					//Changed By Pragyan for Site transporter
					 siteCodeShip = (String)getTranInfo.get("SHIP_CODE");
					//Changed By Site Transporter on 22/09/14 start.
					//docLocation = getDocLoc(tranCod, conn);
					docLocation = getDocLoc(tranCod,siteCodeShip, 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;
					}
					
					if(globalSingleLot != null && !globalSingleLot.equalsIgnoreCase(singleLot) && globalSingleLot.length() > 0)
					{
						singleLot = globalSingleLot;
					}
					
					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 ";
					}
					
					
					if ( partQty.trim().length() > 0 )
					{
						System.out.println("in side if");
					
						if( "2".equalsIgnoreCase(partQty))
						{
							partQtyValue = "Ship Available";
						}
						
						else if ("0".equalsIgnoreCase(partQty))
						{
							partQtyValue = "Ship Complete";
						}
						else if("1".equalsIgnoreCase(partQty))
						{
							partQtyValue = "Ship Complete Lines";
						}
						
						System.out.println("partQtyValue is --> ["+partQtyValue+"]");
					}
		
					if(itemCodeMap.containsKey(rs.getString(6)))
					{						
						balStockQty = Double.parseDouble(itemCodeMap.get(rs.getString(6)).toString());
						bappend = false ;
					}
					else
					{
						long startTime1 = System.currentTimeMillis();
						
						if(directPickLoc != null && directPickLoc.length() > 0)
						{
							//changed by pragyan on 12/12/13 for bug fixing.
							//pstmtStock = conn.prepareStatement(sSQL + orderByStkStr);
							pstmtStock = conn.prepareStatement(sSQL + minMaxSql +orderByStkStr);
							pstmtStock.setString(1,"Y");
							pstmtStock.setString(2,rs.getString(6));
							pstmtStock.setString(3,rs.getString(12));
							pstmtStock.setInt(4,minSelfLife);
							if(maxSelfLife > 0)
							{
								pstmtStock.setInt(5,maxSelfLife);
								pstmtStock.setString(6,directPickLoc);
							}
							else
							{
								pstmtStock.setString(5,directPickLoc);
							}
							//Chnaged by Rohan on 21-08-13 for get data for min and max self life.start
							/*
							pstmtStock.setString(5,directPickLoc);
							*/
							/*pstmtStock.setInt(5,maxSelfLife);
							pstmtStock.setString(6,directPickLoc);*/
							//Chnaged by Rohan on 21-08-13 for get data for min and max self life.end
							
						}
						else if ( singleLot.trim().length() > 0 && singleLot.trim().equalsIgnoreCase("Y") )
						{
							
							//pstmtStock = conn.prepareStatement(sSingleLotSql + orderByStkStr);
							pstmtStock = conn.prepareStatement(sSingleLotSql + minMaxSqlLot + 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);
							
							if(maxSelfLife > 0)
							{
								pstmtStock.setInt(8,maxSelfLife);
								pstmtStock.setString(9,resrvLoc);
								pstmtStock.setString(10,casePickLoc);
								pstmtStock.setString(11,activePickLoc);
								pstmtStock.setString(12,deepStoreLoc);
								pstmtStock.setString(13,partialResrvLoc);
							}
							else
							{
								pstmtStock.setString(8,resrvLoc);
								pstmtStock.setString(9,casePickLoc);
								pstmtStock.setString(10,activePickLoc);
								pstmtStock.setString(11,deepStoreLoc);
								pstmtStock.setString(12,partialResrvLoc);
							}
							//Chnaged by Rohan on 21-08-13 for get data for min and max self life.start
							/*
							
							pstmtStock.setString(8,resrvLoc);
							pstmtStock.setString(9,casePickLoc);
							pstmtStock.setString(10,activePickLoc);
							pstmtStock.setString(11,deepStoreLoc);
							pstmtStock.setString(12,partialResrvLoc);
							*/
							
							/*pstmtStock.setInt(8,maxSelfLife);
							pstmtStock.setString(9,resrvLoc);
							pstmtStock.setString(10,casePickLoc);
							pstmtStock.setString(11,activePickLoc);
							pstmtStock.setString(12,deepStoreLoc);
							pstmtStock.setString(13,partialResrvLoc);*/
							//Chnaged by Rohan on 21-08-13 for get data for min and max self life.start
						}
						else
						{
							//sSQL = sSQL + orderByStkStr;
							//pstmtStock = conn.prepareStatement(sSQL + orderByStkStr);
							pstmtStock = conn.prepareStatement(sSQL + minMaxSql + 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
							//Chnaged by Rohan on 21-08-13 for get data for min and max self life.start
							/*
							
							pstmtStock.setString(5,resrvLoc);
							pstmtStock.setString(6,casePickLoc);
							pstmtStock.setString(7,activePickLoc);
							pstmtStock.setString(8,deepStoreLoc);
							pstmtStock.setString(9,partialResrvLoc);
							*/
							
							if(maxSelfLife > 0)
							{
								pstmtStock.setInt(5,maxSelfLife);
								pstmtStock.setString(6,resrvLoc);
								pstmtStock.setString(7,casePickLoc);
								pstmtStock.setString(8,activePickLoc);
								pstmtStock.setString(9,deepStoreLoc);
								pstmtStock.setString(10,partialResrvLoc);
							}
							else
							{
								pstmtStock.setString(5,resrvLoc);
								pstmtStock.setString(6,casePickLoc);
								pstmtStock.setString(7,activePickLoc);
								pstmtStock.setString(8,deepStoreLoc);
								pstmtStock.setString(9,partialResrvLoc);
							}
							/*pstmtStock.setInt(5,maxSelfLife);
							pstmtStock.setString(6,resrvLoc);
							pstmtStock.setString(7,casePickLoc);
							pstmtStock.setString(8,activePickLoc);
							pstmtStock.setString(9,deepStoreLoc);
							pstmtStock.setString(10,partialResrvLoc);*/
							
							//Chnaged by Rohan on 21-08-13 for get data for min and max self life.end
							
						}
						rs1 = pstmtStock.executeQuery();
						
						if (rs1.next())
						{
							bappend = true;
							balStockQty = rs1.getDouble(1);
							holdQty = rs1.getDouble(2);
							itemCodeMap.put(rs.getString(6),new Double(rs1.getDouble(1)));
							
							System.out.println("Bal stk qty for item ....." + rs.getString(6) + " is " + balStockQty);
						}
						long endTime1 = System.currentTimeMillis();
						
						System.out.println("DIFFERANCE IN TIME FOR GET STOCK SQL IN SECONDS:::["+(endTime1-startTime1)/1000+"]");
						
						if(rs1 != null)
						{
							rs1.close();
						}
						pstmtStock.clearParameters();
					}

					double itemStkQty = 0d;
			
					if(itemCodeMap.containsKey(rs.getString(6)))
					{
						itemStkQty = (Double)itemCodeMap.get(rs.getString(6));
						System.out.println("balStockQty =["+itemStkQty+"]");				
						retTabSepStrBuff.append( "<Detail2>\r\n" );				
						retTabSepStrBuff.append( "<cust_code><![CDATA[" ).append(rs.getString(1)).append( "]]></cust_code>\r\n" );
						retTabSepStrBuff.append( "<cust_name><![CDATA[" ).append(rs.getString(2)).append( "]]></cust_name>\r\n" );
					//  changed by sankara on 25-07-13 for sql select is changed in metadata  start.....
						retTabSepStrBuff.append( "<cust_code__dlv><![CDATA[" ).append(checkNull(rs.getString("CUST_CODE__DLV"))).append( "]]></cust_code__dlv>\r\n" );
						retTabSepStrBuff.append( "<customer_cust_name><![CDATA[" ).append(checkNull(rs.getString("CUST_DLV_NAME"))).append( "]]></customer_cust_name>\r\n" );
					//  changed by sankara on 25-07-13 for sql select is changed in metadata  end.....
						retTabSepStrBuff.append( "<line_no><![CDATA[" ).append(rs.getString(3)).append( "]]></line_no>\r\n" );   
						retTabSepStrBuff.append( "<sale_order><![CDATA[" ).append(rs.getString(4)).append( "]]></sale_order>\r\n" );
						System.out.println("Due Date Format===>>>>>>>>=="+rs.getDate(5));
						retTabSepStrBuff.append( "<due_date><![CDATA[" ).append(rs.getDate(5)).append( "]]></due_date>\r\n" );
						dueDate = rs.getTimestamp(5);
						retTabSepStrBuff.append( "<item_code><![CDATA[" ).append(rs.getString(6)).append( "]]></item_code>\r\n" );        
						retTabSepStrBuff.append( "<item_descr><![CDATA[" ).append(rs.getString(7)).append( "]]></item_descr>\r\n" );
						if (globalSingleLot.trim().length() > 0) 
						{							
							retTabSepStrBuff.append( "<single_lot><![CDATA[" ).append(globalSingleLot).append( "]]></single_lot>\r\n" );
							retTabSepStrBuff.append( "<master_pack_allow><![CDATA[" ).append(globalMasterPackAllow).append( "]]></master_pack_allow>\r\n" );
							retTabSepStrBuff.append( "<active_pick_allow><![CDATA[" ).append(globalActivePickAllow).append( "]]></active_pick_allow>\r\n" );			
							retTabSepStrBuff.append( "<stock_to_dock_allow><![CDATA[" ).append(globalStockToDockAllow).append( "]]></stock_to_dock_allow>\r\n" );
							retTabSepStrBuff.append( "<parcelpack_allow><![CDATA[" ).append(globalParcelPackAllow).append( "]]></parcelpack_allow>\r\n" );

						}
						else
						{
							retTabSepStrBuff.append( "<single_lot><![CDATA[" ).append(singleLot).append( "]]></single_lot>\r\n" );
							retTabSepStrBuff.append( "<master_pack_allow><![CDATA[" ).append(masterPackAllow).append( "]]></master_pack_allow>\r\n" );
							retTabSepStrBuff.append( "<active_pick_allow><![CDATA[" ).append(activePickAllow).append( "]]></active_pick_allow>\r\n" );
							retTabSepStrBuff.append( "<stock_to_dock_allow><![CDATA[" ).append(stockToDockAllow).append( "]]></stock_to_dock_allow>\r\n" );
							retTabSepStrBuff.append( "<parcelpack_allow><![CDATA[" ).append(parcelPackAllow).append( "]]></parcelpack_allow>\r\n" );

						}	
						
						retTabSepStrBuff.append( "<ship_type><![CDATA[" ).append(shipType).append( "]]></ship_type>\r\n" );		
						retTabSepStrBuff.append( "<quantity><![CDATA[" ).append(quantity).append( "]]></quantity>\r\n" );	
						retTabSepStrBuff.append( "<part_qty><![CDATA[" ).append(partQtyValue).append( "]]></part_qty>\r\n" );		
						retTabSepStrBuff.append( "<pending_quantity><![CDATA[" ).append(pendingQty).append( "]]></pending_quantity>\r\n" );
						pendQty = pendingQty;
						balStockQtyTemp = balStockQty; 
						if (bappend == true)
						{
							retTabSepStrBuff.append( "<stock_quantity><![CDATA[" ).append(balStockQty).append( "]]></stock_quantity>\r\n" );	
						}
						else
						{
							retTabSepStrBuff.append( "<stock_quantity><![CDATA[" ).append("0.0").append( "]]></stock_quantity>\r\n" );	
						}
						
						 pstmtManul.setString(1,saleOrderTran);
						 pstmtManul.setString(2,rs.getString(3));
						 rsMan = pstmtManul.executeQuery();
						 if(rsMan.next())
						 {
							 allocFlag = rsMan.getString("ALLOC_FLAG");
						 }
						 if ("M".equalsIgnoreCase(allocFlag))
						 {
							 allocFlag = allocFlag;
						 }
						 else
						 {
							 allocFlag = "";
						 }
						 pstmtManul.clearParameters();
					
						if(balStockQty >= pendQty)
						{
							allocQty = pendQty;
							balStockQty -= pendQty;
						}
						else
						{
							allocQty = balStockQty;
							balStockQty = 0;
						}
			        // 	changed by sankara on 25-07-2013 for changeing in sql select in metadata start.......		
						pstmtHold.setString(1, itemCode);
						pstmtHold.setString(2, siteCode);
						rsHld = pstmtHold.executeQuery();
						
						if(rsHld.next())
						{
							retTabSepStrBuff.append( "<hold_qty><![CDATA[" ).append(rsHld.getDouble(1)).append( "]]></hold_qty>\r\n" );
						}
						pstmtHold.clearParameters();   
					// 	changed by sankara on 25-07-2013 for changeing in sql select in metadata end.......			
						
						if(DefaultQtyFlag.equals("Y") && !"M".equalsIgnoreCase(allocFlag))
						{
							retTabSepStrBuff.append( "<qty_alloc><![CDATA[" ).append(allocQty).append( "]]></qty_alloc>\r\n" );	
							
						}
						else
						{
							retTabSepStrBuff.append( "<qty_alloc><![CDATA[" ).append("0.0").append( "]]></qty_alloc>\r\n" );
						}
						
                   /* changed by sankara on 25-07-2013 already declared in above start....
					    pstmtHold.setString(1, itemCode);
						pstmtHold.setString(2, siteCode);
						rsHld = pstmtHold.executeQuery();
						
						if(rsHld.next())
						{
							retTabSepStrBuff.append( "<hold_qty><![CDATA[" ).append(rsHld.getDouble(1)).append( "]]></hold_qty>\r\n" );
						}
						pstmtHold.clearParameters();   
					   changed by sankara on 25-07-2013 already declared in above end....   */
						itemCodeMap.put(rs.getString(6), new Double(balStockQty));
						sordItemQty= rs.getDouble(8);
						balStk = balStockQtyTemp - pendQty ;
						System.out.println("balStk ::"+balStk);
						
						if(balStk >= 0)
						{
							retTabSepStrBuff.append( "<bal_qty><![CDATA[" ).append(balStk).append( "]]></bal_qty>\r\n" );
						}
						else
						{
							retTabSepStrBuff.append( "<bal_qty><![CDATA[" ).append("0.0").append( "]]></bal_qty>\r\n" );
						}
					
						pstmtManQty.setString(1, saleOrderTran);
						pstmtManQty.setString(2, rs.getString(3));
						rsM = pstmtManQty.executeQuery();
						if( rsM.next())
						{
							retTabSepStrBuff.append( "<manual_allocqty><![CDATA[" ).append((rsM.getString("MAN_QTY") == null) ? "0.0" :rsM.getString("MAN_QTY")).append( "]]></manual_allocqty>\r\n" );
						}
						else
						{
							retTabSepStrBuff.append( "<manual_allocqty><![CDATA[" ).append("0.0").append( "]]></manual_allocqty>\r\n" );
						}
						pstmtManQty.clearParameters();
						
						if (allocFlag == null)
						{
							allocFlag = "";
						}

						 retTabSepStrBuff.append( "<alloc_flag><![CDATA[" ).append(allocFlag).append( "]]></alloc_flag>\r\n" );
						 retTabSepStrBuff.append( "<tran_code><![CDATA[" ).append(tranCod).append( "]]></tran_code>\r\n" );
						 retTabSepStrBuff.append( "<tran_name><![CDATA[" ).append(tranName).append( "]]></tran_name>\r\n" );
						 retTabSepStrBuff.append( "<lock_code__dock><![CDATA[" ).append(docLocation).append( "]]></lock_code__dock>\r\n" );
						 
						 packInstr = rs.getString(11);
						if (packInstr == null)
						{
							packInstr = "";
						}
						
						retTabSepStrBuff.append( "<pack_instr><![CDATA[" ).append(packInstr).append( "]]></pack_instr>\r\n" );
						retTabSepStrBuff.append( "<site_code><![CDATA[" ).append(rs.getString(12)).append( "]]></site_code>\r\n" );
						retTabSepStrBuff.append( "<exp_lev><![CDATA[" ).append(rs.getString(13)).append( "]]></exp_lev>\r\n" );
						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 sankara on 25/07/13 cust_code_dlv,name already declared in above start....	
						retTabSepStrBuff.append( "<cust_code__dlv><![CDATA[" ).append(checkNull(rs.getString("CUST_CODE__DLV"))).append( "]]></cust_code__dlv>\r\n" );
						retTabSepStrBuff.append( "<customer_cust_name><![CDATA[" ).append(checkNull(rs.getString("CUST_DLV_NAME"))).append( "]]></customer_cust_name>\r\n" );
					    changed by sankara on 25/07/13 cust_code_dlv,name already declared in above end....		*/
						retTabSepStrBuff.append( "</Detail2>\r\n" );
					}
				}while(rs.next());
				 retTabSepStrBuff.append( "</Header0>\r\n</group0>\r\n</DocumentRoot>\r\n" );		
				resultString = retTabSepStrBuff.toString();
				System.out.println("ResultString....." + resultString);
				pstmt.clearParameters();	
			}
			
			else
			{
				errCode ="VTNOREC2";
			}
			
			long endTime = System.currentTimeMillis();
			
			System.out.println("DIFFERANCE IN TIME FOR GET DATA SQL IN SECONDS:::["+(endTime-startTime)/1000+"]");
			
			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;
			}
			if(pstmtManul != null)
			{
				pstmtManul.close();
				pstmtManul = null;
			}
			if( rsMan != null)
			{
				rsMan.close();
				rsMan = null;
			}			
			if(rsHld != null)
			{
				rsHld.close();
				rsHld = null;

			}
			if(pstmtHold != null)
			{
				pstmtHold.close();
				pstmtHold = null;	
			}
			if(pstmtManQty != null)
			{
				pstmtManQty.close();
				pstmtManQty = null;
			}
			if( rsM != null)
			{
				rsM.close();
				rsM = 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;
					}
					if(pstmtManul != null)
					{
						pstmtManul.close();
						pstmtManul = null;
					}
					if( rsMan != null)
					{
						rsMan.close();
						rsMan = null;
					}	
					
					if(rsHld != null)
					{
						rsHld.close();
						rsHld = null;

					}
					if(pstmtHold != null)
					{
						pstmtHold.close();
						pstmtHold = null;	
					}
					if(pstmtManQty != null)
					{
						pstmtManQty.close();
						pstmtManQty = null;
					}
					if( rsM != null)
					{
						rsM.close();
						rsM = null;
					}			
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				errString = e.getMessage();
				e.printStackTrace();
				throw new ITMException(e);
			}
		}		
		return resultString;	
	}
	/*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, "
				 //Changed by Rohan on 08-05-13 for considering sorditem.site_code instead of sorder.site_Code__SHIP
				   //+"SORDER.SITE_CODE__SHIP,SORDITEM.EXP_LEV, "
				   +"SORDITEM.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
				   //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 "
				   
				   // change by venkat on 02/05/13 adding column customer name and customer delivery name
				  +" , SORDER.CUST_CODE__DLV, C.CUST_NAME AS CUST_DLV_NAME "
				  // changed by venkat on 06/05/13 adding customer c for getting customer name data
				  //+"FROM SORDDET,SORDER,SORDITEM,CUSTOMER,ITEM , WAVE_TYPE "
				   +"FROM SORDDET,SORDER,SORDITEM,CUSTOMER,ITEM , WAVE_TYPE,CUSTOMER C  "
				   //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 "
				   //Changed by Rohan on 08-05-13 for considering sorditem.site_code instead of sorder.site_Code__SHIP
				   //+" SORDER.SITE_CODE__SHIP = ? AND "
				    +" SORDITEM.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 <= ? " 
				   // changed by venkat on 02-05-2013 add join of customer delivery of sorder and customer code
				   +" AND SORDER.CUST_CODE__DLV = C.CUST_CODE "  
				   +"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" );	
						//changed by venkat on 02/05/13 append shipType in porpar format 
						retTabSepStrBuff.append( "<ship_type><![CDATA[" ).append(shipType).append( "]]></ship_type>\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");
						//Changed by venkat on 02/05/13 display cust_code__dlv and customer_cust_name start.
						retTabSepStrBuff.append( "<cust_code__dlv><![CDATA[" ).append(checkNull(rs.getString("CUST_CODE__DLV"))).append( "]]></cust_code__dlv>\r\n" );
						retTabSepStrBuff.append( "<customer_cust_name><![CDATA[" ).append(checkNull(rs.getString("CUST_DLV_NAME"))).append( "]]></customer_cust_name>\r\n" );
						//Changed by venkat on 02/05/13 display cust_code__dlv and customer_cust_name end.
					
						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;	
	}*/
	//Changed BY Pragyan 20JUL13 TO Optimize the code for Open  maximum open cursors.end
	
	//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);
			}
			  	
			long startTime22 = System.currentTimeMillis();
		    retStr = process(headerDom, detailDom, windowName, xtraParams);
		    long endTime22 = System.currentTimeMillis();
		    System.out.println("DIFFERANCE IN TIME FOR TOTAL WAVE PROCESS IN SECONDS:::["+(endTime22-startTime22)/1000+"]");
		    
		}
		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,pstmtMan = null,pstmtInv=null;
		ResultSet rsMan = null,rsInv = 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 
		//Changed by Rohan on 12-06-13 for defining variables.start
		String resrvLoc  = "";
		String casePickLoc  = "";
		String activePickLoc  = "";
		String deepStoreLoc = "";
		String partialResrvLoc = "";
		String replHistStr = "";
		String prvReplID = "";
		String prvLocCodeTo = "";
		int prvReplLineNo = 0;
		String prvPickOrd = "";
		int prvPickLineNo = 0;
		String isRepl = "";
		String replQuantity = "";
		//Changed by Rohan on 12-06-13 for defining variables.end
		double allocQty = 0;
		double quantity = 0;
		double qtyAvailAlloc = 0;
		String stockQuantity = "";
		String errString = "";
		String sSQLUpdatSord = "";
		//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;
		PreparedStatement pstmtUpdSord = 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 Rohan on 04-07-13 for split active replanishment task based on configuration of disparam.start
		dsoLocationset = new HashSet<String>();
		pndLocationset = new HashSet<String>();
		caspkLocationset = new HashSet<String>();
		psoLocationset = new HashSet<String>();
		prsvLocationset = new HashSet<String>();
		//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam.end
				
		//Changed By Pragyan To store previous location code as blank.
		prevsLocCode = "";
		//Changed By Pragyan 23/02/13 To store ship type .
		String shipType = "";
		String shipTypeLine = "A";
		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
		HashMap sordLineMAp = new HashMap();
		//Changed By Pragyan 17/08/13
		HashMap sordWaveTypeMap = new HashMap();
		ArrayList waveTypeList = null;
		
		//changed by sankara on 21/08/13 for bug fixing start..	
		String errMessage = "";
		boolean isError = false;
	   //changed by sankara on 21/08/13 for bug fixing end..
	   //changed by sankara on 24/09/13 for update status in sorddet start.
	    Set saleOrderSet =  new java.util.HashSet();
		String salesOrder ="";
	  //changed by sankara on 24/09/13 for update status in sorddet end.
		try
		{
			//Changed By Pragyan 30JUN14 to take the connection above 
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver = null;
			//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+"]");
			//Changed by sankara on 22/07/14 not reuired as per pragyan sir
			//PrintService[] printServices = PrinterJob.lookupPrintServices();
			//ArrayList<String> arry = new ArrayList<String>();
			//Changed by sumit on 24/11/12 adding print label condition
			//isRemotePrintRptSrvCofigur = isRemotePrintSrvCofigured("IS_REMOTE_PRNTSRV_CONFIGRD",conn);
			
			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))
			{				
				//Changed by Dhanraj on 27JUN14 to validate printer name from net printers table.start
				//Changed by sankara on 22/07/14 not reuired as per pragyan sir
				/*if(isRemotePrintRptSrvCofigur)
				{*/
					sql="select printer_name from net_printers where printer_name= ? ";
		    		pstmt = conn.prepareStatement(sql);
		    		pstmt.setString(1, printer.trim());
		    		rs = pstmt.executeQuery();
		    		if( rs.next())
		    		{
		    			System.out.println("Printer Found in  net_printers..........["+printer+"]");
		    		}
		    		else
		    		{
						
						errString="INVPRINTER";
						errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
						return errString;
					}
		    		pstmt.close();pstmt = null;
		    		rs.close(); rs = null;
		    	//Changed by sankara on 22/07/14 not reuired as per pragyan sir start.	
				/*}
				else
				{
					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();			
				}*/
				//end Dhanraj 27Jun14
		    	//Changed by sankara on 22/07/14 not reuired as per pragyan sir end.	
	    		//hide by Dhanraj 27Jnn14
				/*System.out.println(" in inside if");
				for (PrintService printService : printServices) 
				{
		            String name = printService.getName();
		            System.out.println("printer service name --> "+name);
		            arry.add(name);					            
		        }
				if( !arry.contains(printer.trim()))
	            {
	            	errFields.add( childNodeName.toLowerCase() );
					errList.add( "INVPRINTER" );
	            }							
				arry.clear();		*/		          
	    		//Changed by Dhanraj 27JUN14 to validate printer name from net printers table.end				           
			}
			//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);
			
			//Changed By Pragyan 30JUN14 to take the connection above 
			/*ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver = null;*/
			shipment2 = 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();
			//Changed By Pragyan 16-APR-14 To store the active Repl Qty and  in same wave [taro live issue]
			itemQtyMapForActiveRepl.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));		
			//isADSIConnReq = discommon.getDisparams("999999","CONN_TO_ADSI_APP",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.
			
			long startTime5 = System.currentTimeMillis();
			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"))
					{
						if ( childNode != null && childNode.getFirstChild() != null )
						{
							stockQuantity = childNode.getFirstChild().getNodeValue();
						}					
					}
					
					if (childNodeName.equals("sale_order"))
					{
						if ( childNode != null && childNode.getFirstChild() != null )
						{
						  saleOrder = childNode.getFirstChild().getNodeValue();
						}
					}

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

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

					if (childNodeName.equals("qty_alloc"))
					{
						if ( childNode != null && childNode.getFirstChild() != null )
						{
							allocQty = Double.parseDouble(childNode.getFirstChild().getNodeValue());
							System.out.println("qty_alloc======>"+allocQty);
						}	
						
					}
					if (childNodeName.equals("exp_lev"))
					{
						if ( childNode != null && childNode.getFirstChild() != null )
						{
							expLev = childNode.getFirstChild().getNodeValue();
						}					
					}
					//changed by sankara on 03-08-2012 adding pending quantity[start]
					
					if (childNodeName.equals("pending_quantity"))
					{
						if ( childNode != null && childNode.getFirstChild() != null )
						{
							pendingQuantity = Double.parseDouble(childNode.getFirstChild().getNodeValue());
						}				
					}
					if (childNodeName.equals("cust_code"))
					{
						if ( childNode != null && childNode.getFirstChild() != null )
						{
							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"))
					{
						if ( childNode != null && childNode.getFirstChild() != null )
						{
							isActivePickChecked = childNode.getFirstChild().getNodeValue();
						}			
					}
					if (childNodeName.equals("stock_to_dock_allow"))
					{
						if ( childNode != null && childNode.getFirstChild() != null )
						{
							isStockToDockChecked = childNode.getFirstChild().getNodeValue();
						}	
					}
					if (childNodeName.equals("master_pack_allow"))
					{
						if ( childNode != null && childNode.getFirstChild() != null )
						{
							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"))
					{
						if ( childNode != null && childNode.getFirstChild() != null )
						{
							System.out.println("isParcelPickChecked["+childNode.getFirstChild().getNodeValue()+"]");
							isParcelPickChecked = childNode.getFirstChild().getNodeValue();
						}
					}
					if (childNodeName.equals("ship_type"))
					{
						if ( childNode != null && childNode.getFirstChild() != null )
						{
							System.out.println("shipTypeLine["+childNode.getFirstChild().getNodeValue()+"]");
							shipTypeLine = 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 = "";
						}
						
					}
					if (childNodeName.equals("order_unit"))
					{							
						if(childNode.getFirstChild() != null)
						{
							
							unit = checkNull(childNode.getFirstChild().getNodeValue());
							System.out.println("Order Unit---["+unit+"]");
						}
						else
						{
							unit = "";
						}
						
					}
					
					
					//Changed by sumit on 14/12/12 adding validation incase of manualy allocating saleorder and modifiying qty_allow end.
					//changed by sankara on 24/09/13 for update status in sordet.
					saleOrderSet.add(saleOrder);
				}
				
				
				String lineNoSord = lineNo;
				lineNoSord = "   " + lineNoSord; 
				lineNoSord = lineNoSord.substring(lineNoSord.length()-3);
				
				
				
				//Changed By Pragyan 26-02-13 To validate inputs combination given by the user.start
				
				System.out.println("isMasterPickChecked["+isMasterPickChecked+"]isParcelPickChecked ["+isParcelPickChecked+"]shipType["+shipType+"]shipTypeLine["+shipTypeLine+"]");
				
				/*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);
				}*/
				System.out.println("Sales Order date ["+sordWaveTypeMap.toString()+"]");
				
				if(sordWaveTypeMap.containsKey(saleOrder))
				{
					System.out.println("Always ["+sordWaveTypeMap.toString()+"]");
					waveTypeList = (ArrayList)sordWaveTypeMap.get(saleOrder);
					System.out.println("Always ["+waveTypeList.toString()+"]");
					if(!isActivePickChecked.equalsIgnoreCase((String)waveTypeList.get(1)))
					{
						return errString = getError(saleOrder +" Line No "+ lineNoSord+ " (Active Pick Selection)", "VTINVSELAP", conn);
					}
					else if(!isMasterPickChecked.equalsIgnoreCase((String)waveTypeList.get(2)))
					{
						return errString = getError(saleOrder +" Line No "+ lineNoSord+ " (Master Pick Selection)", "VTINVSELAP", conn);
					}
					else if(!isParcelPickChecked.equalsIgnoreCase((String)waveTypeList.get(3)))
					{
						return errString = getError(saleOrder +" Line No "+ lineNoSord+ " (Parcel Pack Selection)", "VTINVSELAP", conn);
					}
					else if(!isStockToDockChecked.equalsIgnoreCase((String)waveTypeList.get(4)))
					{
						return errString = getError(saleOrder +" Line No "+ lineNoSord+ " (Stock To Dock Selection)", "VTINVSELAP", conn);
					}
					else if(!shipTypeLine.equalsIgnoreCase((String)waveTypeList.get(5)))
					{
						return errString = getError(saleOrder +" Line No "+ lineNoSord+ " (Shipment Type Selection)", "VTINVSELAP", conn);
					}
				}
				else
				{
					waveTypeList = new ArrayList();
					waveTypeList.add(lineNoSord);
					waveTypeList.add(isActivePickChecked);
					waveTypeList.add(isMasterPickChecked);
					waveTypeList.add(isParcelPickChecked);
					waveTypeList.add(isStockToDockChecked);
					waveTypeList.add(shipTypeLine);
					sordWaveTypeMap.put(saleOrder, waveTypeList);
					System.out.println("Always ["+sordWaveTypeMap.toString()+"]");
				}
				
				
				//Changed By Pragyan 26-02-13 To validate inputs combination given by the user.End
				if(("Y".equalsIgnoreCase(isMasterPickChecked)) && !("A".equalsIgnoreCase(shipTypeLine) || "M".equalsIgnoreCase(shipTypeLine)))
				{
					//return errString = itmDBAccessEJB.getErrorString("","ATLSTSELMP","","",conn);
					return errString = getError(saleOrder +" Line No "+ lineNoSord , "ATLSTSELMP", conn);
				}
				else if(("Y".equalsIgnoreCase(isParcelPickChecked)) && !("A".equalsIgnoreCase(shipTypeLine) || "P".equalsIgnoreCase(shipTypeLine)))
				{
					//return errString = itmDBAccessEJB.getErrorString("","ATLSTSELPP","","",conn);
					return errString = getError(saleOrder +" Line No "+ lineNoSord , "ATLSTSELPP", conn);
				}
				else if(!("Y".equalsIgnoreCase(isParcelPickChecked) || "Y".equalsIgnoreCase(isMasterPickChecked) ) && ("M".equalsIgnoreCase(shipTypeLine) || "P".equalsIgnoreCase(shipTypeLine)))
				{
					//return errString = itmDBAccessEJB.getErrorString("","ATLSTSENAN","","",conn);
					return errString = getError(saleOrder +" Line No "+ lineNoSord , "ATLSTSENAN", conn);
				}
				//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 + "] Line No ["+lineNo+"]Item Code["+itemCode+"]",errString,conn);
					return errString;								
				}
				
				
				
				sql = 	"SELECT UNIT FROM SORDDET WHERE SALE_ORDER = ? AND  LINE_NO = ?"; 
		
				pstmt = conn.prepareStatement(sql);	
				pstmt.setString(1,saleOrder);
				pstmt.setString(2,lineNoSord);
				
				rs = pstmt.executeQuery();
				
				if(rs.next())
				{
					unit = rs.getString("UNIT");
				}
				
				if( pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if( rs != null)
				{
					rs.close();
					rs = null;
				}
				
				unit = unit != null ? unit.trim():"";
				
				System.out.println("Current Unit For Saleorde"+saleOrder+"]line No["+lineNo+"]Unit["+unit+"]");
				// 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 + "] Line No ["+lineNo+"]Item Code["+itemCode+"]","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
							
				//changed by Pragyan to return error string of active pick "Y" and sale order in "case".start
				if("Y".equalsIgnoreCase(isActivePickChecked) && "CS".equalsIgnoreCase(unit))
				{
					System.out.println(" inside Case order and active yes");
					errString = getError(saleOrder + "] Line No ["+lineNo+"]Item Code["+itemCode+"]","VTACTPKCSC",conn);
					return errString;
				}
				//changed by Pragyan to return error string of active pick "Y" and sale order in "case".end
				
				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.
	                	stkQuantity =	Math.floor(stkQuantity/itemPackSize) * itemPackSize;
	    				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);
                    
                    //Changed by Rohan on 12/06/13 for bug fixing for setting location code.start
                    
                    locCodeTo = locCodeTo != null && locCodeTo.length() > 0 ?locCodeTo:locCode;
                    tempMap.put("sugg_loc", locCodeTo);
                    
                    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);
        		
					if(((invSt.trim().equalsIgnoreCase(resrvLoc) || invSt.trim().equalsIgnoreCase(deepStoreLoc)) && (qtyAllocate >= packSize)) || invSt.trim().equalsIgnoreCase(partialResrvLoc))
					{
						System.out.println("Inside For Creating Repelnishment packSizeActive:::::["+packSize+"]lotQtyToBeAllocated["+qtyAllocate+"]");
					
						if(itemInfoMapForRepl.containsKey(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode))
						{
							isStockToDock = false;
							
							System.out.println("Replenishment str for ["+quantity+"]");
							replHistStr = checkForReplenishment(itemCode, siteCode, lotNo, lotSl, locCode, qtyAllocate, 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;
						
							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+"]");
									 }
								}
							}
							System.out.println("Location Code To Found as Replenishment Exist ["+locCodeTo+"]");
		                }
		                else
		                {
		                	
		                	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;
		                	}
		       	
		                	System.out.println("Location Code To Found To Create Replenishment  After ["+locCodeTo+"]");
		                }
					}
					locCodeTo = locCodeTo != null && locCodeTo.length() > 0 ?locCodeTo:locCd;
					
					System.out.println("Finally  Loc Code["+locCode+"]Loc Code To["+locCodeTo+"]");
					
					tempMap.put("sugg_loc", locCodeTo);
                    //Changed by Rohan on 12/06/13 for bug fixing for setting location code.end
    
                    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 || "M".equalsIgnoreCase(allocFlag))
				{
					/*
					 //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...===>.....");	
					
					
					///New Changes acc to start
					ArrayList tmpLineList = null;
					if(sordLineMAp.containsKey(saleOrder + ":" + "itemCode" ))
					{
						tmpLineList = (ArrayList)sordLineMAp.get(saleOrder + ":" + "itemCode" );
					}
					else
					{
						tmpLineList = new ArrayList();
					}
					HashMap chkMap = new HashMap();
					chkMap.put("saleOrder", saleOrder);
					chkMap.put("lineNo", lineNo);
					chkMap.put("itemCode", itemCode);
					chkMap.put("allocQty", allocQty);
					chkMap.put("singleLot", singleLot);
					chkMap.put("pendingQuantity", pendingQuantity);
					chkMap.put("isActivePickChecked", isActivePickChecked);
					chkMap.put("isMasterPickChecked", isMasterPickChecked);
					chkMap.put("isStockToDockChecked", isStockToDockChecked);
					chkMap.put("isParcelPickChecked", isParcelPickChecked);
					chkMap.put("expLev", expLev);
					chkMap.put("allocFlag", allocFlag);
					chkMap.put("mannual_alloc_qty", manualAllocqty);
					chkMap.put("ship_type", shipTypeLine);
					tmpLineList.add(chkMap);
					sordLineMAp.put(saleOrder + ":" + "itemCode", tmpLineList);
					
					////New Changes acc to end
					
					//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 
			long endTime5 = System.currentTimeMillis();
			System.out.println("DIFFERANCE IN TIME FOR PREPRATION OF sordLineMAp IN SECONDS:::["+(endTime5-startTime5)/1000+"]");
			if(sordLineMAp.size() > 0)
			{
				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);
    			
				Set keySet = sordLineMAp.keySet();
				ArrayList keyList = new ArrayList(keySet);
				Collections.sort(keyList);
				for (Object object : keyList) 
				{
					ArrayList sordLineList = (ArrayList)sordLineMAp.get(object);
					Collections.sort(sordLineList,new CompareAllocQty());
					
					System.out.println("Finally Sorted Data ["+sordLineList.toString()+"]");
					
					for (Object object2 : sordLineList) 
					{
						
						HashMap mapData = (HashMap)object2;
						saleOrder = (String)mapData.get("saleOrder"); 
						lineNo = (String)mapData.get("lineNo") ;
						itemCode = (String)mapData.get("itemCode");
						allocQty = (Double)mapData.get("allocQty");
						singleLot = (String)mapData.get("singleLot");
						pendingQuantity = (Double)mapData.get("pendingQuantity");
						isActivePickChecked = (String)mapData.get("isActivePickChecked");
						isMasterPickChecked = (String)mapData.get("isMasterPickChecked");
						isStockToDockChecked = (String)mapData.get("isStockToDockChecked");
						isParcelPickChecked = (String)mapData.get("isParcelPickChecked");
						shipTypeLine = (String)mapData.get("ship_type");
						expLev = (String)mapData.get("expLev");
						waveFlag = "";
						String lineNoSord = lineNo;
						lineNoSord = "   " + lineNoSord; 
						lineNoSord = lineNoSord.substring(lineNoSord.length()-3);
						
												
						sql = 	" SELECT D.WAVE_FLAG FROM SORDALLOC D"+
								" WHERE D.SALE_ORDER = ?"+
								" AND D.LINE_NO = ?"+
								" AND D.ITEM_CODE = ?" +
								" AND D.EXP_LEV = ?"+
								" AND D.ALLOC_MODE <> ?";
				
								pstmt = conn.prepareStatement(sql);	
								pstmt.setString(1,saleOrder);
								pstmt.setString(2,lineNoSord);
								pstmt.setString(3,itemCode);
								pstmt.setString(4,expLev);
								pstmt.setString(5,"W");
			
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							waveFlag = rs.getString("WAVE_FLAG");
						/*	if(waveFlag == null)
								waveFlag = "N";
						}
						if( rs != null)
						{
							rs.close();
							rs = null;
						}
						if( pstmt != null)
						{
							pstmt.close();
							pstmt = null;
						}
						System.out.print("Current Wave Flag ["+waveFlag+"]");
						
						*/
								waveFlag = waveFlag != null?waveFlag:"N";
								
								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,"+
												" 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 = ? "+
												" AND S.ALLOC_MODE <> ?"+
												" AND S.QTY_ALLOC > 0";
							   
									pstmtMan = conn.prepareStatement(sodreAlloc);	
									pstmtMan.setString(1,saleOrder);
									pstmtMan.setString(2,  lineNo);
									pstmtMan.setString(3,itemCode);
									pstmtMan.setString(4,expLev);
									pstmtMan.setString(5,"W");
										
									rsMan = pstmtMan.executeQuery();
									while(rsMan.next())
									{
										
										qtyAllocate = rsMan.getInt("QTY_ALLOC");
										noOfArticals = rsMan.getInt("QUANTITY");
										lotSl = rsMan.getString("LOT_SL");
										lotNo = rsMan.getString("LOT_NO");
										locCd = rsMan.getString("LOC_CODE");
										locTypeParent = rsMan.getString("LOC_TYPE__PARENT"); 
										locType =  rsMan.getString("LOC_TYPE");
										locZonePref = rsMan.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= ?";
										pstmtInv = conn.prepareStatement(sqlinvStat);	
										pstmtInv.setString(1,locCd);
										rsInv = pstmtInv.executeQuery();
										if(rsInv.next())
										{
											invSt= rsInv.getString("INV_STAT");
											System.out.println("INV STATSSS"+invSt);
										}
										if(pstmtInv != null)
										{
											pstmtInv.close();
											pstmtInv = null;
										}
										if(rsInv != null)
										{
											rsInv.close();
											rsInv = null;
										}
										String resvInvStat = "";
										resvInvStat = discommon.getDisparams("999999","RESERV_LOCATION",conn);
										if (resvInvStat == null)
										{
											resvInvStat = "";
										}
										
										HashMap itmVolumeMap = getItemVoumeMap(itemCode,lotNo,conn);
										double itemPackSize = (Double)itmVolumeMap.get("PACK_SIZE");
										double stkQuantity = getStockQuantity(itemCode,siteCode,locCd,lotNo,lotSl,qtyAllocate,conn);
										
										//changed by Pragyan to Mannualy Allocated Stock is on Hold.start
										if(stkQuantity <= 0)
										{
											System.out.println(" Mannualy Allocated Stock is on Hold");
											errString = getError(saleOrder + "] Line No ["+lineNo+"]Item Code["+itemCode+"]","VTMNSTKHLD",conn);
											return errString;
										}
										//changed by Pragyan to Mannualy Allocated Stock is on Hold.end
										
										populateReplHistory(itemCode,siteCode,lotNo,lotSl,locCd,conn);
									
										
										Map tempMapReplenishment =new HashMap();
										Map tempMapActiveRepl = null;
										String lastReplenishmentID="",locCodeTo="";
										int lineNoRepl=0;
										System.out.println("Current Stock Qty ["+stkQuantity+"]");
										if(((invSt.trim().equalsIgnoreCase(resrvLoc) || invSt.trim().equalsIgnoreCase(deepStoreLoc)) && (qtyAllocate >= itemPackSize)) || invSt.trim().equalsIgnoreCase(partialResrvLoc))
										{
											if(itemInfoMapForRepl.containsKey(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCd))
											{
												
												System.out.println("Current Mannual Map Exist------------------------------- ");
												ArrayList tempListTestForRepl = (ArrayList)itemInfoMapForRepl.get(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCd);
													
							                }
							                else
							                {
							                	
							                	System.out.println("In Case Of Mannual Stock Allocation current avilable stock ["+stkQuantity+"]");
							                	tempListForRepl  = new ArrayList();
							                	qtyActual=0.0;                	
							                	if(!invSt.equalsIgnoreCase(partialResrvLoc))
							                	{
							                		stkQuantity =	Math.floor(stkQuantity/itemPackSize) * itemPackSize;
							                	}
							                	System.out.println("In Case Of Mannual Stock Allocation current avilable stock in case ["+stkQuantity+"]invSt["+invSt+"]");
							    				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 Pragyan 16-APR-14 To store the active Repl Qty and  in same wave [taro live issue].start
										else
										{
											if(((invSt.equalsIgnoreCase(resrvLoc) || invSt.equalsIgnoreCase(deepStoreLoc)) && (qtyAllocate < itemPackSize) && !(itemInfoMapForRepl.containsKey(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCd))))
											{
												double totalCaseQty = 0.0,totalPickQty = 0.0,stkActReplQty = 0.0;
												if(itemQtyMapForActiveRepl.containsKey(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCd))
												{
													tempMapActiveRepl = (HashMap)itemQtyMapForActiveRepl.get(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCd);
													totalCaseQty = (Double)tempMapActiveRepl.get("ACTIVE_REPL_QTY");
													totalPickQty = (Double)tempMapActiveRepl.get("REPL_PICK_QTY");
													stkActReplQty= (Double)tempMapActiveRepl.get("REPL_STK_QTY");
													
													if((totalPickQty + qtyAllocate) > totalCaseQty)
													{
														totalCaseQty = totalCaseQty + itemPackSize;
													}
													
												}
												else
												{
													tempMapActiveRepl = new HashMap();
													totalCaseQty = itemPackSize;
													stkActReplQty = stkQuantity;
												}
												
												totalPickQty = totalPickQty + qtyAllocate;
												
												tempMapActiveRepl.put("ACTIVE_REPL_QTY",totalCaseQty);
												tempMapActiveRepl.put("REPL_PICK_QTY",totalPickQty);
												tempMapActiveRepl.put("REPL_STK_QTY",stkActReplQty);
												itemQtyMapForActiveRepl.put(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCd, tempMapActiveRepl);
												System.out.println("itemQtyMapForActiveRepl Present In Mannual>>>>>>>>>>"+itemQtyMapForActiveRepl.toString()+"]");
											}
											
										}
										//Changed By Pragyan 16-APR-14 To store the active Repl Qty and  in same wave [taro live issue].end
									 	System.out.println("Current Mannual Map-------------------["+itemInfoMapForRepl.toString()+"]");
										
										 perItemVolume = (Double)itmVolumeMap.get("ITEM_SIZE");
										 caseVolume = (Double)itmVolumeMap.get("LOT_SIZE");
										 caseWeight = (Double)itmVolumeMap.get("PACK_WEIGHT");
										 hazardous = (String)itmVolumeMap.get("HAZARDOUS");
										 itemWeight = (Double)itmVolumeMap.get("ITEM_WEIGHT");
										// caseCount = qtyAllocate /packSize;
										 caseCount = qtyAllocate /itemPackSize;
										 
										 //Changed By Pragyan 03-JUL-14 Issue Tracker No(401) not to create Stock To Dock from Mannual allocation.start
										/*if(invSt != null && invSt.trim().equalsIgnoreCase(resvInvStat.trim()))
										{
											
											double palletVolume  = Double.parseDouble(discommon.getDisparams("999999","PER_PALLET__VOLUME",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 Pragyan 03-JUL-14 Issue Tracker No(401) not to create Stock To Dock from Mannual allocation.end
										 
										if(tempList != null)
										{
											 System.out.println("Before Manual tempList["+tempList.size()+"]data["+tempList.toString()+"]");
										}
										
										if(saleOrderWiseMap.containsKey(saleOrder+":"+locTypeParent))
					                    {
											tempList = (ArrayList) saleOrderWiseMap.get(saleOrder+":"+locTypeParent); 
					                    }
										
					                    else
					                    {                    	
					                        tempList  = new ArrayList();
					                    }
						               
					                    tempMap = new HashMap();
					                    
					                    tempMap.put("site_code", siteCode);
					                    tempMap.put("item_code", itemCode);
					                    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);
					                   
					                    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("ship_type", shipTypeLine);
					                    tempMap.put("exp_lev", expLev);
					                    
					                    System.out.println("CHECKING FOR THE WRONG PACK SIZE1["+packSize+"]itemCode ["+itemCode+"]locCode["+locCode+"]");
					                    //tempMap.put("pack_size", packSize);
					                    tempMap.put("sord_lineNo", lineNo);
					                    tempMap.put("item_weight", itemWeight);
					                    
					        		
										if(((invSt.trim().equalsIgnoreCase(resrvLoc) || invSt.trim().equalsIgnoreCase(deepStoreLoc)) && (qtyAllocate >= packSize)) || invSt.trim().equalsIgnoreCase(partialResrvLoc))
										{
											System.out.println("Inside For Creating Repelnishment packSizeActive:::::["+packSize+"]lotQtyToBeAllocated["+qtyAllocate+"]");
										
											if(itemInfoMapForRepl.containsKey(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode))
											{
												isStockToDock = false;
												
												System.out.println("Replenishment str for ["+quantity+"]");
												replHistStr = checkForReplenishment(itemCode, siteCode, lotNo, lotSl, locCode, qtyAllocate, 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;
											
												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+"]");
														 }
													}
												}
												System.out.println("Location Code To Found as Replenishment Exist ["+locCodeTo+"]");
							                }
							                else
							                {
							                	
							                	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;
							                	}
							       	
							                	System.out.println("Location Code To Found To Create Replenishment  After ["+locCodeTo+"]");
							                }
										}
										locCodeTo = locCodeTo != null && locCodeTo.length() > 0 ?locCodeTo:locCd;
										
										System.out.println("Finally  Loc Code["+locCode+"]Loc Code To["+locCodeTo+"]");
										
										tempMap.put("sugg_loc", locCodeTo);
					                    		    
					                    tempMap.put("hazard", hazardous);
					                    tempList.add(tempMap);          
					                    System.out.println("Sale Order and Size Manuall allocate ["+saleOrder+"]line no ["+lineNo+"]["+itemCode+"qtyAllocate["+qtyAllocate+"]");
					                    System.out.println("tempList["+tempList.size()+"]data["+tempList.toString()+"]");
					                    saleOrderWiseMap.put(saleOrder+":"+locTypeParent,tempList);
					                    
				                    
									}
									
									
								}//if(rs.next())
								
								if( rsMan != null)
								{
									rsMan.close();
									rsMan = null;
								}
								if( pstmtMan != null)
								{
									pstmtMan.close();
									pstmtMan = null;
								}
					
								if(manualStock)
								{
									int update = 0;
									sql= "UPDATE SORDALLOC SET WAVE_FLAG = 'Y' WHERE SALE_ORDER = ? AND LINE_NO = ?";
									pstmtInv = conn.prepareStatement(sql);
									pstmtInv.setString(1, saleOrder);
									pstmtInv.setString(2, lineNoSord);
									update = pstmtInv.executeUpdate();
									if(update > 0)
									{
										System.out.println(" SORD_ALLOC updated ["+update+"]");
									}
									if( pstmtInv!= null)
									{
										pstmtInv.close();
										pstmtInv = null;
									}
								}
						}//	if(rs.next())
						
						if( rs != null)
						{
							rs.close();
							rs = null;
						}
						if( pstmt != null)
						{
							pstmt.close();
							pstmt = null;
						}
						System.out.print("Current Wave Flag ["+waveFlag+"]");
						
								
						if(allocQty > 0)
						{
	
							System.out.println("Going For ItemCode Quantity"+ itemCode+"saleOrder"+saleOrder+"]lineNo["+lineNo+"]allocQty["+allocQty+"]");
							//errString = sorderAllocate(headerDom, detailDom, saleOrder, lineNo, itemCode, allocQty,singleLot,pendingQuantity,isActivePickChecked,isMasterPickChecked,isStockToDockChecked,isParcelPickChecked, expLev, xtraParams, conn );
							long startTime6 = System.currentTimeMillis();
							errString = sorderAllocate(headerDom, detailDom, saleOrder, lineNo, itemCode, allocQty,singleLot,pendingQuantity,isActivePickChecked,isMasterPickChecked,isStockToDockChecked,isParcelPickChecked, expLev, xtraParams,shipTypeLine, conn );
							long endTime6 = System.currentTimeMillis();
							System.out.println("DIFFERANCE IN TIME FOR ALLOCATE STOCK IN SECONDS:::["+(endTime6-startTime6)/1000+"]");
							if (errString != null && errString.trim().length() > 0)
							{
								System.out.println("errString :"+errString);
								return errString;
							}
							//saleOrderWiseMapCpy = (HashMap) saleOrderWiseMap.clone();
						}
					}
				}
				
			}		
			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*/)
			{	
				long startTime7 = System.currentTimeMillis();
				errString = updateWaveTask(headerDom, detailDom, xtraParams, conn);
				long endTime7 = System.currentTimeMillis();
				System.out.println("DIFFERANCE IN TIME FOR UPDATE WAVE_TASK IN SECONDS:::["+(endTime7-startTime7)/1000+"]");
			}
			//changed by sankara on 24/09/13 for update status in sordet start.
			Iterator it = saleOrderSet.iterator();		
			while(it.hasNext())
			{
				salesOrder = (String)it.next();
				if(salesOrder != null)
				{
					updateBackOrderStatus ( salesOrder,conn);
				}
			}
			saleOrderSet.clear();
			//changed by sankara on 24/09/13 for update status in sordet end.
			//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))
				{
					long startTime8 = System.currentTimeMillis();
					generatedLabelPrint(waveId,printer, conn);
					long endTime8 = System.currentTimeMillis();
					System.out.println("DIFFERANCE IN TIME FOR GET GENERATE LABLE PRINT SQL IN SECONDS:::["+(endTime8-startTime8)/1000+"]");
				}
				//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+"]");
				long startTime7 = System.currentTimeMillis();
				errString = generateReport(waveId, conn);
				long endTime7 = System.currentTimeMillis();
				System.out.println("DIFFERANCE IN TIME FOR GENERATE REPORT IN SECONDS:::["+(endTime7-startTime7)/1000+"]");
				/*//Changed By Pragyan WM3DSUN015 To update status in Sorder as InProcess after .start
				
				if("P".equalsIgnoreCase(waveMode))
				{
					int updateSorder = 0;
					sSQLUpdatSord = "UPDATE SORDER SET SHIP_STATUS = ? WHERE SALE_ORDER IN (SELECT SALE_ORDER FROM " +
									" WAVE_TASK_DET WHERE WAVE_ID = ? )";
					
					
					pstmtSord = conn.prepareStatement(sSQLUpdatSord);
					pstmtSord.setString(1, waveId);
					updateSorder = pstmtSord.executeUpdate();
					
					if(updateSorder > 0)
					{
						System.out.println(" SORDER UPDATE COUNT ["+updateSorder+"]");
					}
					if( pstmtSord!= null)
					{
						pstmtSord.close();
						pstmtSord = null;
					}
				}
				//Changed By Pragyan WM3DSUN015 To update status in Sorder as InProcess after .end
				 */		
				
			}
			//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();
			//changed by sankara on 21/08/13 for fixing bug start..
			// throw e;
			 isError = true;
			//changed by sankara on 21/08/13 for fixing bug end..
		}
		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.
				}
				
				// Changed by sankara on 21/08/13 for fixing bug start..		
				if( isError )
				{ 
					System.out.println("throwing new Exception1;;;;;;;;;;;;;;;;.");			  
					errMessage = printExceptionMessage("VTPRCERR",conn,errString);
					return errMessage ;
				}
				// Changed by sankara on 21/08/13 for fixing bug 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,String shipTypeLine, 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; 
			//Changed by Rohan on 27-08-13 for define variable
			int maxShelfLife = 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;
			//Changed By Pragyan 06-DEC-13 to get Stock alloc quantity as per KB sir
			double stkAllocQty = 0.0;
			String hazardous = "";
			//changed by pragyan on 31/05/14 for single lot
			String currentSelectdLotNo = "";
			
			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
				//Changed by Rohan on 27-08-13 for adding condition of min and max self life
				//minShelf = "SELECT MIN_SHELF_LIFE FROM SORDITEM WHERE SALE_ORDER = ? AND LINE_NO = ? AND EXP_LEV = ?";
				minShelf = "SELECT MIN_SHELF_LIFE,MAX_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");
					//Changed by Rohan on 27-08-13 for get  max self life
					maxShelfLife = rSetShelf.getInt("MAX_SHELF_LIFE");
					System.out.println("minShelfLife======>"+minShelfLife+"[maxShelfLife]"+maxShelfLife+"]");
				}
				
				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;
						//Changed By Pragyan 04/DEC/13 UAT KB Sir for not integral quantity only case should allocate
						//orderByStkStr = "AND LOCATION.INV_STAT IN(?,?,?,?) ORDER BY STOCK.EXP_DATE,INVSTAT.ALLOC_PREF, STOCK.LOC_CODE ";
						orderByStkStr = "AND LOCATION.INV_STAT IN(?,?,?,?) ORDER BY STOCK.EXP_DATE,INVSTAT.ALLOC_PREF_CASE, 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, "
							   //Changed By Pragyan 06-DEC-13 to get Stock alloc quantity as per KB sir
							   //+"STOCK.NO_ART,INVSTAT.INV_STAT,ITEM.LOC_TYPE__PARENT,ITEM.LOC_TYPE,ITEM.LOC_ZONE__PREF " 
							    +"STOCK.NO_ART,INVSTAT.INV_STAT,ITEM.LOC_TYPE__PARENT,ITEM.LOC_TYPE,ITEM.LOC_ZONE__PREF,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 = ? 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 NOT EXISTS (SELECT 1 FROM INV_RESTR I WHERE I.INV_STAT = INVSTAT.INV_STAT AND I.REF_SER = 'S-DSP' ) ";
							 //Changed by Rohan on 27-08-13 for adding condition of min and max self life
							   //+"AND (MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE) > ? ) "
							   //+" AND (MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE) BETWEEN ? AND ?  ) "
					 		  // +"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 ";
								
								if(maxShelfLife > 0)
								{
									getDataSql = getDataSql  + " AND (CEIL(MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE)) BETWEEN ? AND ?  ) ";
								}
								else
								{
									getDataSql = getDataSql  + "AND (CEIL(MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE)) > ? ) ";
								}
						
						
								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);
								if(maxShelfLife > 0)
								{
									pstmtStock.setInt(7,maxShelfLife);
									pstmtStock.setString(8,directPickLoc);  
								}
								else
								{
									pstmtStock.setString(7,directPickLoc);
								}
								//Changed by Rohan on 27-08-13 for adding condition of min and max self life.start
								//pstmtStock.setString(7,directPickLoc);
							/*	pstmtStock.setInt(7,maxShelfLife);
								pstmtStock.setString(8,directPickLoc);  */   
								//Changed by Rohan on 27-08-13 for adding condition of min and max self life.end
								
					}
					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, "
							   //Changed By Pragyan 06-DEC-13 to get Stock alloc quantity as per KB sir
							  // +"STOCK.NO_ART,INVSTAT.INV_STAT,ITEM.LOC_TYPE__PARENT,ITEM.LOC_TYPE,ITEM.LOC_ZONE__PREF " 
							  	+"STOCK.NO_ART,INVSTAT.INV_STAT,ITEM.LOC_TYPE__PARENT,ITEM.LOC_TYPE,ITEM.LOC_ZONE__PREF,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 = ? 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 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) ) >= ?) " 
							   //Changed by Rohan on 27-08-13 for adding condition of min and max self life
							   //+"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 (MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE) BETWEEN ? AND ?  ) "
					 		   
							  //+"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 ";
								if(maxShelfLife > 0)
								{
									getDataSql = getDataSql +" AND (CEIL(MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE)) BETWEEN ? AND ?  ) ";
								}
								else
								{
									getDataSql = getDataSql + "AND (CEIL(MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE)) > ? ) ";
								}
								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);
								//Changed by Rohan on 27-08-13 for adding condition of min and max self life
								/*
								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);
								}
								
								*/
								
								if(maxShelfLife > 0)
								{
									pstmtStock.setInt(7,maxShelfLife);
									pstmtStock.setString(8,resrvLoc);
									pstmtStock.setString(9,casePickLoc);
									
									if( "N".equalsIgnoreCase(isActivePickChecked))
									{
										pstmtStock.setString(10,"");
									}
									else
									{
										pstmtStock.setString(10,activePickLoc);
									}
								
									pstmtStock.setString(11,deepStoreLoc);
									
									if(isActives)
									{
										pstmtStock.setString(12,partialResrvLoc);
									}  
									
								}
								else
								{
									pstmtStock.setString(7,resrvLoc);
									pstmtStock.setString(8,casePickLoc);
									
									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);
									}
									
								}
								/*pstmtStock.setInt(7,maxShelfLife);
								pstmtStock.setString(8,resrvLoc);
								pstmtStock.setString(9,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(10,"");
								}
								else
								{
									pstmtStock.setString(10,activePickLoc);
								}
								//Changed by sumit on 29/12/12 hiding active pick if user no need from active end
								pstmtStock.setString(11,deepStoreLoc);
								
								if(isActives)
								{
									pstmtStock.setString(12,partialResrvLoc);
								}  
								//Changed by Rohan on 27-08-13 for adding condition of min and max self life.end
								 */				
					}
					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, "
							   //Changed By Pragyan 06-DEC-13 to get Stock alloc quantity as per KB sir
							  // //+"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)
							   +"STOCK.NO_ART,INVSTAT.INV_STAT,ITEM.LOC_TYPE__PARENT,ITEM.LOC_TYPE,ITEM.LOC_ZONE__PREF,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 = ? 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 
							   ////Changed by Rohan on 27-08-13 for adding condition of min and max self life
							   //+"AND (MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE) > ? ) " //Change by Rohan on 4/7/12
							   //+" AND (MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE) BETWEEN ? AND ?  ) "
					 		   +"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 ";
								if(maxShelfLife > 0)
								{
									getDataSql = getDataSql +" AND (CEIL(MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE)) BETWEEN ? AND ?  ) ";
								}
								else
								{
									getDataSql = getDataSql + "AND (CEIL(MONTHS_BETWEEN(TO_DATE(STOCK.EXP_DATE),SYSDATE)) > ? ) ";
								}
								pstmtStock = conn.prepareStatement(getDataSql + orderByStkStr);
								
								pstmtStock.setString(1,itemCode);
								pstmtStock.setString(2,siteCode);
								pstmtStock.setInt(3,minShelfLife);
								//Changed by Rohan on 27-08-13 for adding condition of min and max self life.start
								/*
								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);
								}
								*/
								if(maxShelfLife > 0)
								{
									pstmtStock.setInt(4,maxShelfLife);
									pstmtStock.setString(5,resrvLoc);
									pstmtStock.setString(6,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(7,"");
									}
									else
									{
										pstmtStock.setString(7,activePickLoc);
									}
									//Changed by sumit on 29/12/12 hiding active pick if user no need from active end
									pstmtStock.setString(8,deepStoreLoc);
									
									if(isActives)
									{
										pstmtStock.setString(9,partialResrvLoc);
									}
									//Changed by Rohan on 27-08-13 for adding condition of min and max self life.end
								}
								else
								{
									pstmtStock.setString(4,resrvLoc);
									pstmtStock.setString(5,casePickLoc);
									
									if( "N".equalsIgnoreCase(isActivePickChecked))
									{
										pstmtStock.setString(6,"");
									}
									else
									{
										pstmtStock.setString(6,activePickLoc);
									}
									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...........For allocation.["+allocQty);
				//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);
				//Changed By Pragyan 06-DEC-13 to get Stock alloc quantity as per KB sir
				stkAllocQty = rs.getDouble(17);
				/*
				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 Pragyan 31-MAY-14 for single lot start
				System.out.println("Stock Lot No["+lotNo+"]currentSelectdLotNo["+currentSelectdLotNo+"]");
				if("Y".equalsIgnoreCase(singleLot) && currentSelectdLotNo != "" && !currentSelectdLotNo.equalsIgnoreCase(lotNo))
				{
					System.out.println("Continue as Lot No is different["+lotNo+"]");
					continue;
				}
				else
				{
					currentSelectdLotNo = lotNo;
				
				}
				
				//Changed By Pragyan 31-MAY-14 end
				//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 */
				invStat = invStat != null?invStat.trim():"";
				System.out.println("allocQty"+allocQty+"qtyAvailAlloc:::"+qtyAvailAlloc);
				
				//if(((invStat.equalsIgnoreCase(resrvLoc) || invStat.equalsIgnoreCase(deepStoreLoc)  || invStat.equalsIgnoreCase(casePickLoc) )) && "N".equalsIgnoreCase(isActivePickChecked))
				if(((invStat.equalsIgnoreCase(resrvLoc) || invStat.equalsIgnoreCase(deepStoreLoc)  || invStat.equalsIgnoreCase(casePickLoc) )))
				{
					if("N".equalsIgnoreCase(isActivePickChecked))
					{
						qtyAvailAlloc = Math.floor(qtyAvailAlloc/packSizeActive) * packSizeActive;
						System.out.println("Only Case avilable Quantity["+qtyAvailAlloc+"]");
					}
					else
					{
						/*double avilbleActives = qtyAvailAlloc % packSizeActive;
						double quantiAvilableAsCase = Math.floor(qtyAvailAlloc/packSizeActive) * packSizeActive;
						double requiredCases = Math.floor(allocQty/packSizeActive) * packSizeActive;
						double requiredActives = allocQty % packSizeActive;
						
						System.out.println("From Stock Avilable Actives["+avilbleActives+"]");
						System.out.println("From Stock quantiAvilableAsCase["+avilbleActives+"]");
						
						System.out.println("Required Actives ["+avilbleActives+"]");
						System.out.println("Required Cases ["+avilbleActives+"]");
						*/
						/*if(allocQty < packSizeActive && quantiAvilableAsCase <= 0 &&  allocQty > avilbleActives)
						{
							
							System.out.println("case1 --["+(allocQty < packSizeActive && quantiAvilableAsCase <= 0 &&  allocQty > avilbleActives)+"]");
							qtyAvailAlloc = avilbleActives;
						}
						else if(allocQty > packSizeActive && allocQty >= qtyAvailAlloc && requiredCases >= quantiAvilableAsCase)
						{
							qtyAvailAlloc = quantiAvilableAsCase * packSizeActive;
							System.out.println("case2 --["+(allocQty > packSizeActive && allocQty >= qtyAvailAlloc && requiredCases >= quantiAvilableAsCase)+"]");
						}
						else if( requiredCases <= quantiAvilableAsCase && avilbleActives >  requiredActives)
						{
								System.out.println("case3 --["+(requiredCases <= quantiAvilableAsCase && avilbleActives >  requiredActives)+"]");
								if((requiredCases + 1 ) != quantiAvilableAsCase)
								{
									
									System.out.println("case3.4 --["+((requiredCases + 1 ) != quantiAvilableAsCase)+"]");
									
									qtyAvailAlloc = quantiAvilableAsCase * packSizeActive;
								}
						}
						*/
						
						
						
						

					}
				}
				
				
				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
					
					if((invStat.equalsIgnoreCase(resrvLoc) || invStat.equalsIgnoreCase(deepStoreLoc)) && (lotQtyToBeAllocated > packSizeActive) && "Y".equalsIgnoreCase(isStockToDockChecked))
					{
						
						//Changed By Pragyan 03-JUL-14 Issue Tracker No(401) not to create Stock To Dock if allocation is present in stock.start
						////Changed By Pragyan 06-DEC-13 to get Stock alloc quantity exist then stock to dock should not be considered as per KB sir.start
						//changed by sankara on 03/01/14 as suggested by pragyan start.
						//isStockToDock = true;
						if(stkAllocQty > 0)
						{
							isStockToDock = false;
						}
						else
						{
							isStockToDock = true;
						}
						//changed by sankara on 03/01/14 as suggested by pragyan end.
						//Changed By Pragyan 06-DEC-13 to get Stock alloc quantity then stock to dock should not be considered as per KB sir.start
						//Changed By Pragyan 03-JUL-14 Issue Tracker No(401) not to create Stock To Dock if allocation is present in stock.end
					}
					//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);	
				//	
				
				System.out.println("Stock To Dock change["+isStockToDock+"]");
								
				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
		                	{	
		                		if("N".equalsIgnoreCase(isActivePickChecked))
		                		{
		                			tempMapReplenishment.put("QTY_AVAIL",qtyAvailAlloc);
		                		}
		                		else
		                		{
		                			double avilbleActives = qtyAvailAlloc % packSizeActive;
		    						double quantiAvilableAsCase = Math.floor(qtyAvailAlloc/packSizeActive) * packSizeActive;
		    						double requiredCases = Math.floor(lotQtyToBeAllocated/packSizeActive) * packSizeActive;
		    						double requiredActives = lotQtyToBeAllocated % packSizeActive;
		    						
		    						System.out.println("From Stock Avilable Actives["+avilbleActives+"]");
		    						System.out.println("From Stock quantiAvilableAsCase["+quantiAvilableAsCase+"]");
		    						
		    						System.out.println("Required Actives ["+requiredActives+"]");
		    						System.out.println("Required Cases ["+requiredCases+"]");
		    						
		    						if( avilbleActives > 0)
		    						{	    						
		    							qtyAvailAlloc = quantiAvilableAsCase;
		    							System.out.println("Quantity avilable sets on ifblock"+quantiAvilableAsCase+"]");
		    							
		    						}
		    						/*else
		    						{
		    							qtyAvailAlloc = quantiAvilableAsCase - packSizeActive;
		    						}*/
		    						
		    						//tempMapReplenishment.put("QTY_AVAIL",qtyAvailAlloc);
		                		}
		                	}
		                	
		                	double stkQuantity = getStockQuantity(itemCode,siteCode,locCode,lotNo,lotSl,0.0,conn);
		                	
		                	if(!invStat.equalsIgnoreCase(partialResrvLoc))
		                	{
		                		stkQuantity = Math.floor(stkQuantity/packSizeActive) * packSizeActive;
		                	}
		                	System.out.println("stkQuantity["+stkQuantity+"]");
		    				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);
		    				//Changed By Pragyan 12-apr-14 to set the actual stock quantity stkQuantity
		    				//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);
		    				tempMapReplenishment.put("QTY_AVAIL",stkQuantity);
		    				tempMapReplenishment.put("STOCK_QTY",stkQuantity);
		    				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+"]");
		                }
					//Changed By Pragyan 16-APR-14 To store the active Repl Qty and  in same wave [taro live issue].start
					}
					else
					{
						
						Map tempMapActiveRepl = null;
						if((invStat.equalsIgnoreCase(resrvLoc) || invStat.equalsIgnoreCase(deepStoreLoc)) && (lotQtyToBeAllocated < packSizeActive) && !(itemInfoMapForRepl.containsKey(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode)))
						{
							double totalCaseQty = 0.0,totalPickQty = 0.0,stkActReplQty = 0.0;
							if(itemQtyMapForActiveRepl.containsKey(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode))
							{
								tempMapActiveRepl = (HashMap)itemQtyMapForActiveRepl.get(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode);
								totalCaseQty = (Double)tempMapActiveRepl.get("ACTIVE_REPL_QTY");
								totalPickQty = (Double)tempMapActiveRepl.get("REPL_PICK_QTY");
								stkActReplQty= (Double)tempMapActiveRepl.get("REPL_STK_QTY");
								
								if((totalPickQty + lotQtyToBeAllocated) > totalCaseQty)
								{
									totalCaseQty = totalCaseQty + packSizeActive;
								}
								
							}
							else
							{
								tempMapActiveRepl = new HashMap();
								totalCaseQty = packSizeActive;
								stkActReplQty = stkAllocQty;
							}
							
							totalPickQty = totalPickQty + lotQtyToBeAllocated;
							
							tempMapActiveRepl.put("ACTIVE_REPL_QTY",totalCaseQty);
							tempMapActiveRepl.put("REPL_PICK_QTY",totalPickQty);
							tempMapActiveRepl.put("REPL_STK_QTY",stkActReplQty);
							itemQtyMapForActiveRepl.put(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode, tempMapActiveRepl);
							System.out.println("itemQtyMapForActiveRepl Present In Normal>>>>>>>>>>"+itemQtyMapForActiveRepl.toString()+"]");
						}
						
					}
					//Changed By Pragyan 16-APR-14 To store the active Repl Qty and  in same wave [taro live issue].end
										
					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;
						}
					}*/
					
					System.out.println("To allocate ::: " + strAllocate.toString()+"]lotQtyToBeAllocated["+lotQtyToBeAllocated+"]");
					
					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(tempList != null)
					{
						 System.out.println("Before Sor tempList["+tempList.size()+"]data["+tempList.toString()+"]");
					}
					
					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);
                    System.out.println("CHECKING FOR THE WRONG PACK SIZE2["+packSize+"]itemCode ["+itemCode+"]locCode["+locCode+"]");
                    //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);
                    tempMap.put("ship_type", shipTypeLine);
                    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()+"]");
                    System.out.println("tempList["+tempList.size()+"]data["+tempList.toString()+"]");
                    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 pragyan on 14/08/14 for tran_code and loc type argumnet.
		String tranCodeInput = "";
		//changed by pragyan on 25/08/14 for tran_code and loc type argumnet.
		String locTypeParentInput = "";
		//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 = "";
		String sitCodeWave = "";
		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;
		ArrayList sordkeyList = new ArrayList();
		String frmDomMasterPackAllow = "";
		String frmDomParcelPackAllow = "";
		//Changed By sankara 17/05/14 for added remarks in wave proccess screen
	    String remarks = "";
		//chnaged by pragyan on 15/10/14 for cold chain	
	    String locTypeParent = "";
	  //Changes by Dadaso pawar on 17/03/15 [Start]
	   //String consoliRepl = "";
	  //Changes by Dadaso pawar on 17/03/15 [End]
	    
		try
		{
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId");
			sitCodeWave = genericUtility.getColumnValue("site_code",headerDom);
			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);
			//changed by pragyan on 14/08/14 for tran_code and loc type argumnet.
			tranCodeInput = genericUtility.getColumnValue("tran_code",headerDom);
			//changed by pragyan on 25/08/14 for tran_code and loc type argumnet.
			locTypeParentInput = genericUtility.getColumnValue("loc_type__parent",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";*/
			// Changed by Megha on 22/01/2015 :D14JSUN007  batch_id for back order processing.
			batchID = genericUtility.getColumnValue("batch_id",headerDom);
						
			frmDomMasterPackAllow = checkNull(genericUtility.getColumnValue("master_pack_allow",headerDom));
			frmDomParcelPackAllow = checkNull(genericUtility.getColumnValue("parcelpack_allow",headerDom));
			//Changed By sankara 17/05/14 for added remarks in wave proccess screen
			remarks = checkNull(genericUtility.getColumnValue("remarks",headerDom));
			System.out.println("wavetaskinsert::::::::"+remarks);		
			/*//Changes by Dadaso pawar on 17/03/15 [Start]
			consoliRepl = checkNull(genericUtility.getColumnValue("consolidate_repl",headerDom));
			consoliRepl = consoliRepl.trim();
			System.out.println("consoliRepl::::::::["+consoliRepl+"]");	*/
			//Changes by Dadaso pawar on 17/03/15 [End]
			/*
			if("Y".equalsIgnoreCase(frmDomMasterPackAllow))
			{
				pickType = "M";
			}
			else if("Y".equalsIgnoreCase(frmDomParcelPackAllow))
			{
				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 = "";
				pickType = "";
				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 Megha on 22/01/2015 :D14JSUN007  batch_id for back order processing.
						//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)" +
						//Changed By sankara 17/05/14 for added remarks in wave proccess screen
						//"CUST_CODE__TO,	DUE_DATE__FROM, DUE_DATE__TO, CHG_USER, CHG_TERM, CHG_DATE,HOLD_STATUS,CANCEL,SITE_CODE)" +
						//"CUST_CODE__TO,	DUE_DATE__FROM, DUE_DATE__TO, CHG_USER, CHG_TERM, CHG_DATE,HOLD_STATUS,CANCEL,SITE_CODE,REMARKS)" +
						//"CUST_CODE__TO,	DUE_DATE__FROM, DUE_DATE__TO, CHG_USER, CHG_TERM, CHG_DATE,HOLD_STATUS,CANCEL,SITE_CODE,REMARKS,TRAN_CODE,LOC_TYPE__PARENT)" +
						"CUST_CODE__TO,	DUE_DATE__FROM, DUE_DATE__TO, CHG_USER, CHG_TERM, CHG_DATE,HOLD_STATUS,CANCEL,SITE_CODE,REMARKS,TRAN_CODE,LOC_TYPE__PARENT,BATCH_ID " +
						// Changed by Megha on 22/01/2015 :D14JSUN007  batch_id for back order processing.
						//Changes by Dadaso pawar on 17/03/15 [Start]
						//",CONSOLIDATE_REPL "+
						//Changes by Dadaso pawar on 17/03/15 [End]
						//"VALUES (?,?,?,?,?,?,?,?,?,?,?)";
						//"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
						//Changed By sankara 17/05/14 for added remarks in wave proccess screen
						//"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				         // "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				         //changed by pragyan on 25/08/14 for tran_code and loc type argumnet.
				         //"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");
				//Changed By Pragyan 28/feb/13
				pstmt.setString(14,sitCodeWave); 
				//Changed By sankara 17/05/14 for added remarks in wave proccess screen
				pstmt.setString(15,remarks); 
				//changed by pragyan on 25/08/14 for tran_code and loc type argumnet.
				pstmt.setString(16,tranCodeInput); 
				pstmt.setString(17,locTypeParentInput); 
				// Changed by Megha on 22/01/2015 :D14JSUN007  batch_id for back order processing.
				pstmt.setString(18,batchID);
				//Changes by Dadaso pawar on 17/03/15 [Start]
			//	pstmt.setString(19,consoliRepl);
				//Changes by Dadaso pawar on 17/03/15 [End]
				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();
					sordkeyList.add(sorderKey);
					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())
				
				
				Collections.sort(sordkeyList);
				int sordKeyLen = sordkeyList.size();
				
				for(int srCtrr = 0 ; srCtrr < sordKeyLen; srCtrr ++)
				{
						
					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)sordkeyList.get(srCtrr);//(String)it.next();
					System.out.println("EACH Sale Order Key for repl-------------------["+sorderKey+"]");
					
					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+"]");
					//chnaged by pragyan on 15/10/14 for cold chain
					locTypeParent = sorderKey.substring(sorderKey.indexOf(":") + 1);
					int itemMapListLen = itemMapList.size();
					System.out.println("Current Sorder No :["+sorderKey+"]Map Length["+itemMapListLen+"]");
					//Changed By Pragyan to pass the orderinfos
					sordMapInfoMap = getSordInfo(saleOrder, conn);
					//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();
					double currentCaseCount = 0.0;
					double currentCaseWeight = 0.0;
					double currentActWeight = 0.0;
					double currentCaseVolume = 0.0;
					double currentActVolume = 0.0;
					String tmpSorder = "";
					
					for(int cCgt = 0;cCgt < dataListlen;cCgt++)
					{
						HashMap sordMap = (HashMap)dataList.get(cCgt);
						
						System.out.println("Current Sord Map"+sordMap.toString()+"]sorder["+saleOrder+"]Case Count["+(Double)sordMap.get("no_art_order")+"]");
						
						tmpSorder = (String)sordMap.get("sale_order");
						tmpSorder = tmpSorder.substring(0,tmpSorder.indexOf(":"));
						System.out.println("Current Temp Order "+tmpSorder+"]");
						if(saleOrder.equalsIgnoreCase(tmpSorder))
						{
							currentCaseCount = (Double)sordMap.get("no_art_order");
							currentCaseWeight = (Double)sordMap.get("tot_case_weight");
							currentActWeight = (Double)sordMap.get("tot_act_weight");
							currentCaseVolume =(Double)sordMap.get("tot_case_volume");
							currentActVolume = (Double)sordMap.get("tot_act_volume");
						}
						
						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);	
							frmDomMasterPackAllow  = (String)loadMap.get("master_pack");
							frmDomParcelPackAllow  = (String)loadMap.get("parcel_pick");
							shipType  = (String)loadMap.get("ship_type");
							locCode = (String)loadMap.get("sugg_loc");
							hazardous = (String)loadMap.get("hazard");
							
							//if(sLocCode.equalsIgnoreCase(locCode))
							System.out.println("Current Master Flag"+frmDomMasterPackAllow+"]Current Parcel Flag"+frmDomMasterPackAllow+"]Current Ship Flag["+shipType+"]");
							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);
					//Changed By Pragyan recursive call if master pack yes and as well as parcel pick yes.start			
					//Changed By Pragyan 14-AUG-14.start
					HashMap transPorterInfoMap = null;
					//Changed By Pragyan 25-aug-14 changed logic for getting transporter.
					/*if( tranCodeInput == null || tranCodeInput.trim().length() <= 0 )
					{*/

						if("Y".equalsIgnoreCase(frmDomMasterPackAllow))
						{
							pickType = "M";
						}
						else if("Y".equalsIgnoreCase(frmDomParcelPackAllow))
						{
							pickType = "P";
						}
						System.out.println("Final Master Flag"+frmDomMasterPackAllow+"]Final Parcel Flag"+frmDomMasterPackAllow+"]Final Ship Flag["+shipType+"]pickType["+pickType+"]");
						
						//HashMap transPorterInfoMap = null;
						if("Y".equalsIgnoreCase(frmDomMasterPackAllow) && "Y".equalsIgnoreCase(frmDomParcelPackAllow))
						{
							pickType = "P";
							//chnaged by pragyan on 15/10/14 for cold chain
							//transPorterInfoMap = getTransporterInfoMap(saleOrder,totalWeightCurrentshipment,totCaseCount,pickType,shipType, conn);
							transPorterInfoMap = getTransporterInfoMap(saleOrder,totalWeightCurrentshipment,totCaseCount,pickType,shipType,locTypeParent, conn);
							if(!pickType.equalsIgnoreCase((String)transPorterInfoMap.get("SHIP_TYPE")))
							{
								pickType = "M";
								//chnaged by pragyan on 15/10/14 for cold chain
								//transPorterInfoMap = getTransporterInfoMap(saleOrder,totalWeightCurrentshipment,totCaseCount,pickType,shipType, conn);
								transPorterInfoMap = getTransporterInfoMap(saleOrder,totalWeightCurrentshipment,totCaseCount,pickType,shipType,locTypeParent, conn);
							}
						}
						else
						{
						    //chnaged by pragyan on 15/10/14 for cold chain
							//transPorterInfoMap = getTransporterInfoMap(saleOrder,totalWeightCurrentshipment,totCaseCount,pickType,shipType, conn);
							transPorterInfoMap = getTransporterInfoMap(saleOrder,totalWeightCurrentshipment,totCaseCount,pickType,shipType,locTypeParent, conn);
						}
						
						if(transPorterInfoMap != null & transPorterInfoMap.size() > 0)
						{
						    //chnaged by pragyan on 15/10/14 for cold chain
							String strgCondn = (String)transPorterInfoMap.get("IS_STORAGE_CONDN"); //IS_STORAGE_CONDN
							System.out.println("Storage Condition  ["+strgCondn+"]");
							if("M".equalsIgnoreCase((String)transPorterInfoMap.get("SHIP_TYPE")) && currentCaseCount < 2 && "N".equalsIgnoreCase(strgCondn) )
							{
								System.out.println("totalWeightCurrentshipment AFTER currentCaseWeight"+(currentCaseWeight + currentActWeight)+"]");
								System.out.println("currentCaseVolume AFTER"+currentCaseVolume+"]");
								System.out.println("currentCaseWeight AFTER"+currentCaseWeight+"]");
								System.out.println("currentActVolume AFTER"+currentActVolume+"]");
								System.out.println("currentActWeight AFTER"+currentActWeight+"]");
								System.out.println("currentCaseCount AFTER"+currentCaseCount+"]");			
								
								if("M".equalsIgnoreCase(shipType))
								{
									shipType = "P";
								}
								//chnaged by pragyan on 15/10/14 for cold chain							
								//transPorterInfoMap = getTransporterInfoMap(saleOrder,(currentCaseWeight + currentActWeight),currentCaseCount,"P",shipType, conn);
								transPorterInfoMap = getTransporterInfoMap(saleOrder,(currentCaseWeight + currentActWeight),currentCaseCount,"P",shipType,locTypeParent, conn);
								
								if(transPorterInfoMap != null & transPorterInfoMap.size() > 0)
								{
									tranCode = (String)transPorterInfoMap.get("TRAN_CODE");
									transMode = (String)transPorterInfoMap.get("TRANS_MODE");
									
									System.out.println("current transPorter Now AFTER"+tranCode+"]Ship type["+(String)transPorterInfoMap.get("SHIP_TYPE")+"]");	
									totalWeightCurrentshipment = (currentCaseWeight + currentActWeight);
									totActVolume = currentActVolume;
									totCaseVolume = currentCaseVolume;
									totCaseWeight = currentCaseWeight;
									totActWeight =currentActWeight;
									totCaseCount = currentCaseCount;
									
								}
								else
								{
									tranCode = "";
									transMode = "";
								}
							}
							else
							{
								tranCode = (String)transPorterInfoMap.get("TRAN_CODE");
								transMode = (String)transPorterInfoMap.get("TRANS_MODE");
							}
							String mShipType = (String)transPorterInfoMap.get("SHIP_TYPE");
							if("N".equalsIgnoreCase(frmDomMasterPackAllow) && "N".equalsIgnoreCase(frmDomParcelPackAllow) && ("P".equalsIgnoreCase(mShipType) || "M".equalsIgnoreCase(mShipType)) )
							{
								return errString = getError(saleOrder,"VTNOTPARCT",conn);
							}		
						}
						else
						{
							tranCode = "";
							transMode = "";
						}
						
					//Changed By Pragyan 26/aug/14
					//Changed By Pragyan 25-aug-14 changed logic for getting transporter.start
					//}
					//else
					//if( tranCodeInput != null && tranCodeInput.trim().length() > 0  && transPorterInfoMap != null & transPorterInfoMap.size() > 0)
					if( tranCodeInput != null && tranCodeInput.trim().length() > 0  && transPorterInfoMap != null & transPorterInfoMap.size() > 0 &&  tranCode.length() > 0)
					{
		
				
						String chkDistADSIFlag = "",chkDistADSIFlagIn = "",distShipType = "",newServiceCode  ="";
						System.out.println("Transporter Info from dist Route1 ["+transPorterInfoMap.toString()+"]");
						
						chkDistADSIFlag = (String)transPorterInfoMap.get("ADSI_FLAG");
						distShipType = (String)transPorterInfoMap.get("SHIP_TYPE");
						
						HashMap tempTtransPorterInfoMap = getArgTransporterInfoMap(saleOrder,totalWeightCurrentshipment,totCaseCount,pickType,shipType,tranCodeInput, conn);
						
						System.out.println("Transporter Info from dist Route2 ["+tempTtransPorterInfoMap.toString()+"]");
						
						chkDistADSIFlagIn = (String)tempTtransPorterInfoMap.get("ADSI_FLAG");
						
						tranCode = (String)tempTtransPorterInfoMap.get("TRAN_CODE");
						transMode = (String)tempTtransPorterInfoMap.get("TRANS_MODE");
						newServiceCode = (String)tempTtransPorterInfoMap.get("SERVICE_CODE");
						
						System.out.println("chkDistADSIFlagIn1 ["+chkDistADSIFlagIn+"]");
						chkDistADSIFlagIn = chkDistADSIFlagIn != null && chkDistADSIFlagIn.trim().length() > 0 ?chkDistADSIFlagIn:"N";
						System.out.println("chkDistADSIFlagIn1 ["+chkDistADSIFlagIn+"]");
						
						if(("M".equalsIgnoreCase(distShipType) || "P".equalsIgnoreCase(distShipType)) && "N".equalsIgnoreCase(chkDistADSIFlagIn))
						{
							return errString = getError(saleOrder,"VTNOTPARCT",conn); 
						}
						
						if(("L".equalsIgnoreCase(distShipType)) && "Y".equalsIgnoreCase(chkDistADSIFlagIn))
						{
							return errString = getError(saleOrder,"VTNOTLTLT",conn);
						}
						
						if(tranCode != null && tranCode.length() > 0)
						{
							transPorterInfoMap.put("TRAN_CODE", tranCode);
						}
						
						if(transMode != null && transMode.length() > 0)
						{
							transPorterInfoMap.put("TRAN_MODE", transMode);
						}
						if(newServiceCode != null && newServiceCode.length() > 0)
						{
							transPorterInfoMap.put("SERVICE_CODE", newServiceCode);
						}
						
					}
					//Changed By Pragyan 25-aug-14 changed logic for getting transporter.end
					
					//Changed By Pragyan recursive call if master pack yes and as well as parcel pick yes.end	
					
					
					
					
					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 14/08/14 for tran_code and loc_type_parent start.
					if(transMode == null || transMode.length() <= 0)
					{
						return errString = itmDBAccessEJB.getErrorString("","NVLTRANMOD","","",conn);						
					}
					//Changed By Pragyan 14/08/14 for tran_code and loc_type_parent end.
					//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);
						
						//Changed by Rohan on 21-06-13 for bug fixing of return string.start
						/*
						if(itemSortList.size() > 0)
						{
							return errString = updatePickOrder(headerDom, detailDom,waveId, siteCode,saleOrder ,xtraParams, itemSortList,ptcnID,transPorterInfoMap,totActVolume,totActWeight,totCaseVolume,totCaseWeight,totCaseCount, conn);
						}
						
						if(itemHazSortList.size() > 0)
						{
							return errString = updatePickOrder(headerDom, detailDom,waveId, siteCode,saleOrder ,xtraParams, itemHazSortList,ptcnID,transPorterInfoMap,totActHazVolume,totActHazWeight,totCaseHazVolume,totCaseHazWeight,totHazCaseCount, conn);
						}
						*/
						if(itemSortList.size() > 0)
						{
							long startTime9 = System.currentTimeMillis();
							errString = updatePickOrder(headerDom, detailDom,waveId, siteCode,saleOrder ,xtraParams, itemSortList,ptcnID,transPorterInfoMap,totActVolume,totActWeight,totCaseVolume,totCaseWeight,totCaseCount, conn);
							long endTime9 = System.currentTimeMillis();
							System.out.println("DIFFERANCE IN TIME FOR UPDATE PICK ORDER SQL IN SECONDS:::["+(endTime9-startTime9)/1000+"]");
							//changed by Rohan on 20-06-13 for return errorstring
							//return errString;
							
						}
						
						if(errString == null || errString.trim().length() == 0)
						{
						
							if(itemHazSortList.size() > 0)
							{
								long startTime10 = System.currentTimeMillis();
								errString = updatePickOrder(headerDom, detailDom,waveId, siteCode,saleOrder ,xtraParams, itemHazSortList,ptcnID,transPorterInfoMap,totActHazVolume,totActHazWeight,totCaseHazVolume,totCaseHazWeight,totHazCaseCount, conn);
								long endTime10 = System.currentTimeMillis();
								System.out.println("DIFFERANCE IN TIME FOR UPDATE PICK ORDER OF HAZARDOUS ITEM SQL IN SECONDS:::["+(endTime10-startTime10)/1000+"]");
								//changed by Rohan on 20-06-13 for return errorstring
								
							}
						}
						else
						{
							return errString;
						}
						//Changed by Rohan on 21-06-13 for bug fixing of return string.end
						//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);*/
						
						
						//Changed by Pragyan 26-dec-13 as it required to update despatch hader values from ADSI.start
						/*if(errString == null || errString.trim().length() == 0)
						{
						
							//"Y".equalsIgnoreCase(isADSIConnReq) 
							//if(shipment2 != null && shipment2.getPackages2() != null)
							if("Y".equalsIgnoreCase(isADSIConnReq) && shipment2 != null && shipment2.getPackages2() != null)
							{
									//if("P".equalsIgnoreCase(waveMode))
									//{
										errString = updateTRackingNo(saleOrder, ptcnID, waveId, tranCode, conn);
									//}
									
									shipment2 = null;									
							}
						}
						else
						{
							return errString;
						}*/
						
						//Changed by Pragyan 26-dec-13 as it required to update despatch hader values from ADSI.end
						if (errString == null || errString.trim().length() == 0)
						{
							String dspRefId = updateWaveTaskDet(waveId,4,saleOrder,"","",ptcnID,conn);
							//errString = updateShipment(headerDom, detailDom,waveId,ptcnID,saleOrder,dspRefId,tranCode,transMode, xtraParams, conn);
							errString = updateShipment(headerDom, detailDom,waveId,ptcnID,saleOrder,dspRefId,tranCode,transMode, xtraParams,sordMapInfoMap, conn);
							//Changed by Dhanraj on 19-SEP-14  [W14FSUN003]	
							if (errString == null || errString.trim().length() == 0)
							{
								 System.out.println("Call updatedespatch Method ptcnID== "+ptcnID);
								errString=updatedespatch(ptcnID,conn);
							}
							
						}
						else
						{
							return errString;
						}
						
						if(errString == null || errString.trim().length() == 0)
						{
						
							//"Y".equalsIgnoreCase(isADSIConnReq) 
							//if(shipment2 != null && shipment2.getPackages2() != null)
							if("Y".equalsIgnoreCase(isADSIConnReq) && shipment2 != null && shipment2.getPackages2() != null)
							{
									//if("P".equalsIgnoreCase(waveMode))
									//{
										errString = updateTRackingNo(saleOrder, ptcnID, waveId, tranCode,sordMapInfoMap, conn);
									//}
									
									shipment2 = null;
									
									if(errString != null && errString.trim().length() > 0)
									{
										return errString;
									}
							}
						}
						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.
				}//for(int srCtrr = 0 ; srCtrr < sordKeyLen; srCtrr ++)
			}
			
			//if(errString == null && !(errString.trim().length() > 0))
			//Chnaged By Rohan on 21-06-13 for bug fixing.start
			/*
			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;
			}
			*/
			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);
				//changed by Rohan on 20-06-13 for return errorstring
				return errString;
			}
			else
			{
				return errString;
			}
			//Chnaged By Rohan on 21-06-13 for bug fixing.end
		}
		catch(Exception e)
		{
			System.out.println("Exception :updateWaveTask :"  + insertSql + "\n" +e.getMessage());
			e.printStackTrace();
			//Changed by Rohan on 21-06-13 to  throw item exception.strat.start
			/*
			errString = e.getMessage();
			throw e;
			*/
			throw new ITMException(e);
			//Changed by Rohan on 20-06-13 to  throw item exception.strat.start
		}
		finally
		{
			try
			{
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}			
			}
			catch(Exception e)
			{
				e.printStackTrace();
				//Changed by Rohan on 21-06-13 to  throw item exception.strat.start
				/*
				errString = e.getMessage();
				throw e;
				*/
				throw new ITMException(e);
				//Changed by Rohan on 20-06-13 to  throw item exception.end
			}
		}
		//Changed by Rohan on 21-06-13 for retun errorstring above in code
		//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
	{
		long startTime21 = System.currentTimeMillis();	
		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;
			}
		}
		long endTime21 = System.currentTimeMillis();
		System.out.println("DIFFERANCE IN TIME FOR UPDATE WAVE TASK DET IN SECONDS:::["+(endTime21-startTime21)/1000+"]");
		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="";
		//Cold Chain Point Add By Pragyan 19-SEP-14   [W14FSUN003]	
		String locTypeParent = "";
		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 pstmtCart = 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 sankara on 15/07/14 update status in pick ord det.
		PreparedStatement pstmtPickDet = null;
		PreparedStatement pstmtInsertData = null;
		PreparedStatement pstmtInsertData1 = null;
		PreparedStatement pstmtInsertTran = null;
		PreparedStatement pstmtDt = null;
		ResultSet rsD = null;
		
		ResultSet resSet = null ;
		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;
		masterOrParclNoList = new ArrayList();
		//ArrayList allParcelList=new ArrayList();	
		
		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;
		//Changed By Pragyan 14/08/14 to set input transporter
		String isTrancodeInput = "";
				
		/* 
		 * 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 = "";
		//hanged by sankara on 17/09/14 for direct pick loc insert emp code
		String loginEmpCode = "";
		/*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 = "";
		//changed by sankara on 15/07/14 for update sql
		String sSQLIssHdr = "",sSQLIssDet = "",sSQlUpdWave = "",sSQLUpdPkHdr = "",sSQLUpdPkDet = "";
		String shipType = "",sugPalletNo = "";
		//Changed By Pragyan 13/03/13  for Haz Items.start
		String hazardous = "",sugCode = "",transMode = "";
		//Changed By Pragyan for Cold Chain project on 19-SEP-14.   [W14FSUN003]	
		String facilityCode = "";
		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;
		//Changed By Pragyan 26/04/13 to store actve maps.start
		TreeMap activeListItemWizMap = new TreeMap<String, ArrayList<HashMap>>();
		ArrayList newTempActPickList = null;
		//Changed By Rekha WM3BSUN006 20/05/13 To get the SOAP connection.start
		/*ADSIShippingLocator locator = null;
		ADSIShippingSoap  soap = null;*/
		//Shipment2 shipment2 = null;
		Address recipient = null;
		Package2 pkg2 = null;
		CommodityInfo comInfo = null;
		Package2[] packgeList = null;
		ArrayList<CommodityInfo> comodityInfoList = new ArrayList<CommodityInfo>();
		String imagePath =null;
		String adsiShippingURL = "";
		String  siteCodeShip = "",stateCodeDlv = ""
			,custName="",custShName = "",shipCity="",shipCountry = "",shipAdd1 = "",shipAdd2 = "",
			shipAdd3 = "",shipPh="",shipFax ="",shipMailId = "",custPord = "",harmonizCode = "",harmonizDescr="",originCountry ="",serviceCode="",pin ="",shipmentType = "";
		double unitValue = 0.0;
		LinkedHashMap<String , Double> actCartonWeightMap = new LinkedHashMap<String , Double>();
		//Changed By Rekha WM3BSUN006 20/05/13 To get the SOAP connection.end
		//chnaged by pragyan on 15/10/14 for cold chain
		String strgCondn = "N";
		
		try
		{
			
			loginEmpCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			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");
			//changed by sankara on 22/09/14 for site transporter
			siteCodeShip = (String)transportInfoMap.get("SHIP_CODE");
			transMode = (String)transportInfoMap.get("TRANS_MODE");
			transMode = transMode != null?transMode.trim():transMode;
			isADSIConnReq = (String)transportInfoMap.get("ADSI_FLAG");
			isADSIConnReq = isADSIConnReq != null?isADSIConnReq:"N";
			//changed by pragyan on 14/08/14 trancode and loc type parent start.
			isTrancodeInput = (String)transportInfoMap.get("IS_DIRECT_TRANSPORTER");
			//chnaged by pragyan on 15/10/14 for cold chain
			strgCondn = (String)transportInfoMap.get("IS_STORAGE_CONDN");
			//docLoc = getDocLoc(tranCode, conn);
			//changed by pragyan on 22/09/14 for site transporter
			docLoc = getDocLoc(tranCode,siteCodeShip, conn);
			//Changed By Pragyan for Cold Chain project on 19-SEP-14   [W14FSUN003]	
			facilityCode = commonWmsUtility.getFacilityCode(siteCode, conn);
			System.out.println("Found Facility Code As ["+facilityCode+"]");
			
			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];
				
				//Changed By Pragyan for cold Chain on 19-SEP-14   [W14FSUN003]	
				//String itemVolumeWeight = getPackItemVolumeWeight(totActWeight , totActVolume, "A", conn);
				String itemVolumeWeight = getPackItemVolumeWeight(totActWeight , totActVolume, "A",facilityCode, 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(dbShipType)))
			{
				masterPackAllow = true;
				if(totCaseWeight < masterPackWeight)
				{
					masterPackWeight = totCaseWeight;
				}
				
				String[] itmWeightVol = new String[3];
				//Changed By Pragyan for cold Chain on 19-SEP-14   [W14FSUN003]	
				//String itemVolumeWeight = getPackItemVolumeWeight(masterPackWeight , totCaseVolume, "M", conn);
				String itemVolumeWeight = getPackItemVolumeWeight(masterPackWeight , totCaseVolume, "M",facilityCode, 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+"]");
			long startTime11 = System.currentTimeMillis();			
			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+"]");
				//Changed By Pragyan 25/08/14 tran code input start.
				//Changed By Pragyan 14/08/14 tran code input start.
				/*if("N".equalsIgnoreCase(isTrancodeInput))
				{
					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.........");
					}
				}
				else
				{
					if(!masterPackAllow)
					{
						mPackAllow = "N";
						System.out.println("Master Pack will not generate.........");
					}
				}*/
				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/08/14 tran code input end.
				//Changed By Pragyan 14/08/14 tran code input end.
				//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)))
				if(!invStat.equalsIgnoreCase(activePickInv) && ("Y".equalsIgnoreCase(mPackAllow) || "Y".equalsIgnoreCase(pPickAllow)) && quantity >= packSize && ("N".equalsIgnoreCase(stockToDock)))
				{
					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)
						System.out.println("MASTER PACK Storage Condition["+strgCondn+"]");
						
						//Changed By Pragyan 15/10/14 for cold chain
						if(totCaseCount >= 2 || "Y".equalsIgnoreCase(pPickAllow)  || "Y".equalsIgnoreCase(strgCondn))
						//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();
									System.out.println("length of masterlistlen is"+allMasterListlen);
									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);
																				
																				System.out.println("casetobestore is :"+Math.floor(remainingWeight / caseWeight));
																				System.out.println("caseToBeStore1 is :"+Math.floor(remainingVolume / caseVolume));
																				System.out.println("casetobestore in round :"+Math.round(remainingWeight / caseWeight));
																				System.out.println("casetobestore in round :"+Math.round(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)))
				if(!invStat.equalsIgnoreCase(activePickInv) && ("N".equalsIgnoreCase(mPackAllow)) && ("N".equalsIgnoreCase(pPickAllow)) && (quantity >= packSize || "N".equalsIgnoreCase(aPickAllow)) && ("N".equalsIgnoreCase(stockToDock)))
				{
					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))
				if((quantity < packSize || activeCount > 0) &&  ("N".equalsIgnoreCase(stockToDock)) && "Y".equalsIgnoreCase(aPickAllow))
				{
					System.out.println("--INSIDE ACTIVE PICK BLOCK--");
					if(activeCount > 0)
					{
						quantity = activeCount;
					}
					HashMap activeTempMap = (HashMap)dataMap.clone();
					activeTempMap.put("no_art", "1");
					activeTempMap.put("alloc_qty", quantity);
					
					if(activeListItemWizMap.containsKey(itemCode))
					{
							activeTempPickList = (ArrayList)activeListItemWizMap.get(itemCode);
					}
					else
					{
						activeTempPickList = new ArrayList(); 
					}
					activeTempPickList.add(activeTempMap);
					activeListItemWizMap.put(itemCode, activeTempPickList);
					
					/*//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
		
			}
			long endTime11 = System.currentTimeMillis();
			System.out.println("DIFFERANCE IN TIME FOR GENERATING CASPK,ACTPK,MASTER PACK MAP IN SECONDS:::["+(endTime11-startTime11)/1000+"]");
			System.out.println("parcel pack value is :"+pPickAllow);
			System.out.println("master pack value is :"+mPackAllow);
			//Changed By Rekha WM3BSUN006 20/05/13 To get the SOAP connection  Iff parcel pick 'Y' or Master Pack 'Y'.start
			//if("Y".equalsIgnoreCase(mPackAllow) || "Y".equalsIgnoreCase(pPickAllow))
			if( ("Y".equalsIgnoreCase(mPackAllow) || "Y".equalsIgnoreCase(pPickAllow)))
			{
				
				if("Y".equalsIgnoreCase(isADSIConnReq))
				{
				
					long timeBefore = System.currentTimeMillis();
					if(soap == null)
					{
						adsiShippingURL = discommon.getDisparams("999999","WMS_ADSI_SOAP_URL",conn);
						locator = new ADSIShippingLocator();
						soap = locator.getADSIShippingSoap(new URL(adsiShippingURL));
					}
		    		long timeAfter = System.currentTimeMillis();
		    		String defPh="";
		    		System.out.println("Differance In Tme for connecting to ADSI Server time differance in seconds["+(timeAfter-timeBefore)/1000+"]");
		    		
		    		if(soap.testADSIServer())
		    		{
				    			System.out.println("---ADSI Server Connected---"); 
				    			//imagePath = discommon.getDisparams("999999","SHIP_WITH_PATH",conn);
				    			//File file = new File(imagePath+ File.separator+"Ship_Label"+File.separator+ ptcn + File.separator + ptcn+"_"+"Ship"+".ser" );
					    		if(shipment2 != null)
								{
					    			/*FileInputStream fis = new FileInputStream(imagePath+ File.separator+"Ship_Label"+File.separator+ ptcn + File.separator + ptcn+"_"+"Ship"+".ser" );
									ObjectInputStream ois = new ObjectInputStream(fis);
									System.out.println(" file loaded ");
									shipment2 = (Shipment2) ois.readObject();   	    */
									System.out.println("Existing Package Returned Length ["+shipment2.getPackages2().length+"]" );
								}			
					    		else
					    		{
					    			shipment2 = new Shipment2();	
					        		recipient = new Address();//To set the Address
					        		custName = (String)transportInfoMap.get("CUST_NAME");
					        		custShName = (String)transportInfoMap.get("SH_NAME");
					        		//Changed by Rohan on 22-08-13 for checking null address.start
					        		/*
					        		shipAdd1 = (String)transportInfoMap.get("ADDR1");
					        		shipAdd2 = (String)transportInfoMap.get("ADDR2");
					        		shipAdd3 = (String)transportInfoMap.get("ADDR3");
					        		*/
					        		shipAdd1 = checkNull((String)transportInfoMap.get("ADDR1")).trim();
					        		shipAdd2 = checkNull((String)transportInfoMap.get("ADDR2")).trim();
					        		shipAdd3 = checkNull((String)transportInfoMap.get("ADDR3")).trim();
					        		
					        		//Changed by Rohan on 22-08-13 for checking null address.end
					        		shipCity = (String)transportInfoMap.get("CITY");
					        		stateCodeDlv = (String)transportInfoMap.get("STATE_DLV");
					        		shipCountry = (String)transportInfoMap.get("COUNT_CODE");	
					        		shipPh = (String)transportInfoMap.get("PHONE");	
					        		shipMailId = (String)transportInfoMap.get("EMAIL_ID");	
					        		shipFax = (String)transportInfoMap.get("FAX");	
					        		custPord = (String)transportInfoMap.get("CUST_PORD");	
					        		serviceCode = (String)transportInfoMap.get("SERVICE_CODE");
					        		//pin = (String)transportInfoMap.get("PIN");
					        		pin = (String)transportInfoMap.get("DLV_PIN");
					        		shipmentType =  (String)transportInfoMap.get("SHIPMENT_TYPE");
					        		//Setting Shipment ID 
					    			shipment2.setID(waveId);
					    			recipient.setID(custCodeDlv);//Customer Code
					    			recipient.setContact(custName);//Customer Name
					    			//Chnaged by Rohan on 20-08-13 for set company blank.
					    			//recipient.setCompany(custShName);//Customer Company Name
					    			recipient.setCompany("");//Customer Company Name
					    			//Chnaged by Rohan on 21-08-13 for shipAddrs 3 is blank then set address 2.start
					    			/*
					    			recipient.setAddress1(shipAdd3);//Customer Adress1
					    			recipient.setAddress2(shipAdd2);//Customer Adress2
					    			recipient.setAddress3(shipAdd1);//Customer Adress3
					    			*/
					    			if(!"".equalsIgnoreCase(shipAdd3) && shipAdd3.length() > 0)
					    			{
					    				recipient.setAddress1(shipAdd3);//Customer Adress1
						    			recipient.setAddress2(shipAdd2);//Customer Adress2
						    			recipient.setAddress3(shipAdd1);//Customer Adress3
					    			}
					    			else if(!"".equalsIgnoreCase(shipAdd2) && shipAdd2.length() > 0)
					    			{
					    				recipient.setAddress1(shipAdd2);//Customer Adress1
						    			recipient.setAddress2(shipAdd1);//Customer Adress2
						    			recipient.setAddress3("");
					    			}
					    			else
					    			{
					    				recipient.setAddress1(shipAdd1);//Customer Adress1
						    			recipient.setAddress2("");//Customer Adress2
						    			recipient.setAddress3("");
					    			}
					    			//Chnaged by Rohan on 21-08-13 for shipAddrs 3 is blank then set address 2.end
					    			recipient.setCity(shipCity);//Customer Adress City
					    			recipient.setState(stateCodeDlv);//Customer Adress State
					    			//Changed By Pragyan to overcome from postal code error
					    			shipCountry = shipCountry!=null?shipCountry.trim():"";
					    			Country country = soap.getCountry("ISO3", shipCountry).getResponseCountry();
					    			recipient.setCountry(country);//Customer Adress Country
					    			
					    			defPh = discommon.getDisparams("999999","SHIPPER_DEFAULT_PH",conn);
					    			if(shipPh == null || shipPh.trim().length()== 0)
					    			{
					    				recipient.setPhone(defPh);
					    			}
					    			else
					    			{
					    				recipient.setPhone(shipPh);
					    			}
					    			
					    			System.out.println("phone no is: "+recipient.getPhone());
					    			recipient.setEMail(shipMailId);
					    			recipient.setFax(shipFax);
					    			recipient.setPostalCode(pin);
					    			System.out.println("pin code is :"+recipient.getPostalCode());
					    			shipment2.setRecipient(recipient);
					    			System.out.println("service code "+serviceCode);
					    			//HardCoded valus needs to be change later.
					    			com.adsionline.ADSIShippingWS.Service service = new com.adsionline.ADSIShippingWS.Service();
					    			//service.setFriendlyName(serviceCode);
					    			service.setFriendlyName(serviceCode);
					    			
					    			//service.setSymbol(serviceCode);	
					    			//System.out.println("Service symbol  is :"+service.getSymbol());
					    			shipment2.setService(service);
					    			System.out.println("Service name is :"+shipment2.getService());
					    			System.out.println("Service code is :"+serviceCode);
					    			
					    			shipment2.setTerms(EnumTerms.trmSHIPPER);
					    			//HardCoded valus needs to be change later.
					    			
					    			
					    			shipment2.setSignatureReleaseFlag(false);//false  As per Taro
					    			shipment2.setSignatureRequiredFlag(false);//true Required As per Taro
					    			shipment2.setSaturdayDeliveryFlag(false);// Taro Need To clerify "what is based on service level?"
					    	    			
					    			java.util.Date date = new java.util.Date();
					        		Calendar calendar = Calendar.getInstance();
					        		calendar.setTime(date);
					        		shipment2.setShipDate(calendar);
				
					        		shipment2.setConsigneeAccount("");//Not Required As per Taro
					        		shipment2.setThirdPartyBillingFlag(false);//Not Required As per Taro
					        		shipment2.setThirdPartyBillingAccount("");//Not Required As per Taro
					        		Address addrs = new Address();//Need to capture if required
					        		shipment2.setThirdPartyBillingAddress(addrs);//Not Required As per Taro
					    			
					        		shipment2.setHALFlag(false);//Need clarification from Taro
					        		shipment2.setHALAddress(addrs);//Need clarification from Taro
					        		
					        		shipment2.setManifestAction(EnumManifestAction.maRELEASE);//As per taro by default its maRELEASE
					        		
					        		
					        		shipment2.setConsigneeBillingFlag(false);//As per Taro Not Required
					        		shipment2.setConsigneeBillingFlag(false);//As per Taro Not Required
					        		shipment2.setShipperReference(ptcn);//As per Taro use PTCN(Pick Ticket Control No)
					        		shipment2.setConsigneeReference(custPord);//As per Taro it is sorder.cust_pord
					        		
					        		if(shipmentType != null && shipmentType.trim().length() > 0)
					        		{
					        			shipment2.setShipperName(shipmentType);
					        		}
					        		else
					        		{
					        			shipment2.setShipperName("Taro Commercial");//Needs to change after clarity
					        		}
					        		
					        		shipment2.setTimeInTransit(EnumTimeInTransit.tntFOREVER);//As per taro its tntFOREVER
					        		shipment2.setSaturdayDeliveryFlag(false);//Need to discuss with Taro
					    		}
				        		
				    		}
				    		else
				    		{
				    			System.out.println("---ADSI Server Not Connected throw error---");
				    			errString = itmDBAccessEJB.getErrorString("","ADSISRVERR","","",conn);
				    			return errString;
			
				    		}
				}//if("Y".equalsIgnoreCase(isADSIConnReq))
			}
			//Changed By Rekha WM3BSUN006 20/05/13 To get the SOAP connection  Iff parcel pick 'Y' or Master Pack 'Y'.end
			
			
			////
			long startTime12 = System.currentTimeMillis();
			if(activeListItemWizMap.size() > 0)
			{
				double quantityPerPallet =0.0;
				double quantityPerPalletWeight = 0.0;
				double totQtyPerPallet = 0.0;
				double renCtr = 0;
				double volumeRmaining = 0.0;
				Set itemKeySet = activeListItemWizMap.keySet();
				
					
				System.out.println("packetMaxWeightActive:"+packetMaxWeightActive+"packetMaxVolumeActive:"+packetMaxVolumeActive);			
				 
				for (Iterator actItemsIterator = itemKeySet.iterator();actItemsIterator.hasNext(); )
				{
					
			 		itemCode =(String)actItemsIterator.next();
					ArrayList<HashMap> tempActList = (ArrayList)activeListItemWizMap.get(itemCode);
					int  tempActListLen = tempActList.size();
					itmVolumeMap = getItemVoumeMap(itemCode,"",conn);
					perItemVolume = (Double)itmVolumeMap.get("ITEM_SIZE");
					caseVolume = (Double)itmVolumeMap.get("LOT_SIZE");
					caseWeight = (Double)itmVolumeMap.get("PACK_WEIGHT");
					itemWeight = (Double)itmVolumeMap.get("ITEM_WEIGHT");
					
					
					for(HashMap actDataMap : tempActList)
					{
						
						//Changed by Rohan on 01-07-13 for consderation of active weight and volume.start
						/*
						 quantity = (Double)actDataMap.get("alloc_qty");
						lotNo = (String)actDataMap.get("lot_no");
						quantityPerPallet = Math.floor(  (quantity * perItemVolume)/packetMaxVolumeActive);
						totQtyPerPallet = Math.floor(packetMaxVolumeActive/perItemVolume);
						renCtr = 0;
						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)actDataMap.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)actDataMap.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+"]");
													//Changed By Pragyan 13-may-13 to round the value up to decimal calculation 
													//double remain_quantity = 	Math.floor(reqVolumeToStore/perItemVolume);		
													double remain_quantity = 	Math.round(reqVolumeToStore/perItemVolume);
													System.out.println("ON ACTIVE remain_quantity ["+remain_quantity+"]");
													activeTempPickList = new ArrayList();
													HashMap activeTempMap1 = (HashMap)actDataMap.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)actDataMap.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)actDataMap.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)actDataMap.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+"]");
								}
								
								if(volumeRmaining == 0.0)
								{
									break;
								}
							}						
							renCtr ++ ;
		
						}
						while(renCtr <= quantityPerPallet);
					    */
						quantity = (Double)actDataMap.get("alloc_qty");
						lotNo = (String)actDataMap.get("lot_no");
						
						if(allActivesList.size() > 0)
						{
							if(quantity > 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_WEIGHT") && tempMap.containsKey("LAST_PACK_VOLUME"))
								{
									double lastPackWeight = (Double)tempMap.get("LAST_PACK_WEIGHT");
									double lastPackVolume = (Double)tempMap.get("LAST_PACK_VOLUME");
									System.out.println("Last Pack Volume#############["+tempMap.get("LAST_PACK_VOLUME")+"]");
									System.out.println("Last Pack Weight#############["+tempMap.get("LAST_PACK_WEIGHT")+"]");
									
									double remainingWeight = packetMaxWeightActive - lastPackWeight;
									double remainingVolume = packetMaxVolumeActive  - 	lastPackVolume;	
									System.out.println("remainingWeight"+remainingWeight+"remainingVolume"+remainingVolume);
									
									if(remainingWeight >= itemWeight && remainingVolume >= perItemVolume )//&& lastPackCount < masterPackCount)
									{
										
											double requiredQuantityToStoreWeight = Math.round(remainingWeight / itemWeight);	
											double requiredQuantityToStore = Math.round(remainingVolume / perItemVolume);
											
										    System.out.println("requiredQuantityToStoreWeight"+requiredQuantityToStoreWeight+"requiredQuantityToStore"+requiredQuantityToStore);
											if(requiredQuantityToStoreWeight > requiredQuantityToStore)
											{
												requiredQuantityToStoreWeight = requiredQuantityToStore;
											}
											
											if(requiredQuantityToStoreWeight > quantity)
											{
												requiredQuantityToStoreWeight = quantity;
											}
											
											
											HashMap activeTempMap = (HashMap)actDataMap.clone();	
											activeTempMap.put("no_art", "1");
											activeTempMap.put("alloc_qty", requiredQuantityToStoreWeight );
											activeTempMap.put("LAST_PACK_WEIGHT",lastPackWeight + Math.round((requiredQuantityToStoreWeight * itemWeight)));
											activeTempMap.put("LAST_PACK_VOLUME", Math.round((requiredQuantityToStoreWeight * perItemVolume)) + lastPackVolume);
											activeTempPickList.add(activeTempMap);
											quantity = quantity - requiredQuantityToStoreWeight;
											allActivesList.set(allActiveListLen-1,activeTempPickList);
											
									}
								}
							}
							else
							{
								break;
							}
					
						 }//ACTIVEQTYqTY> O
						
							
							
						if(quantity <= 0)
						{
							continue;
						}
						quantityPerPallet = Math.ceil(  (quantity * perItemVolume)/packetMaxVolumeActive);
						quantityPerPalletWeight = Math.ceil(  (quantity * itemWeight)/packetMaxWeightActive);
						
						double totalQtyOnPallet = 0.0;
						double activeCounter = 0.0;
						int counter = 0;
						
						if(quantityPerPallet < quantityPerPalletWeight)
						{
							
							activeCounter = quantityPerPalletWeight;
							totalQtyOnPallet = Math.floor(packetMaxWeightActive/itemWeight);
							System.out.println("Total qty per pallet weight wise"+totalQtyOnPallet);
						}					
						else
						{	
							activeCounter = quantityPerPallet;
							totalQtyOnPallet = Math.floor(packetMaxVolumeActive/perItemVolume);
							System.out.println("Total qty per pallet volume wise"+totalQtyOnPallet);
							
						}
						
						if(totalQtyOnPallet > quantity)
						{
							totalQtyOnPallet = quantity;
						}
						double packetMaxWeightActiveCount = Math.round((packetMaxWeightActive/itemWeight));
						double packetMaxVolumeActiveCount = Math.floor(packetMaxVolumeActive/perItemVolume);
						
						if(packetMaxWeightActiveCount > packetMaxVolumeActiveCount)
						{
							packetMaxWeightActiveCount = packetMaxVolumeActiveCount;
						}
						
						double remainingWeight = 0.0;
						double remainingVolume = 0.0;
						do
						{
							double currentActiveCount = 	totalQtyOnPallet;			
							
							System.out.println("totalQtyOnPallet ["+totalQtyOnPallet+"]");
							double ActiveWeightCount = Math.round(currentActiveCount/packetMaxWeightActiveCount);
							double ActiveVolumeCount = Math.round(currentActiveCount/packetMaxVolumeActiveCount);
							if(ActiveWeightCount > ActiveVolumeCount)
							{
								ActiveWeightCount = ActiveVolumeCount;
							}
							System.out.println("ActiveWeightCount["+ActiveWeightCount+"]"+"ActiveVolumeCount"+ActiveVolumeCount);
															
							double wCounter = 0;
							
							if(packetMaxWeightActiveCount > currentActiveCount)
							{
								packetMaxWeightActiveCount = currentActiveCount;
							}
							
							do
							{
								
								if(allActivesList.size() > 0)
								{
										int allListLen = allActivesList.size();
										activeTempPickList = (ArrayList)allActivesList.get(allListLen -1);
										int innerListLen = activeTempPickList.size();
										Map tempMap = (HashMap)activeTempPickList.get(innerListLen -1);							
									
										if(tempMap.containsKey("LAST_PACK_WEIGHT") && tempMap.containsKey("LAST_PACK_VOLUME"))// && tempMap.containsKey("LAST_PACK_COUNT"))
										{		
												
												double lastPackWeight = (Double)tempMap.get("LAST_PACK_WEIGHT");
												double lastPackVolume = (Double)tempMap.get("LAST_PACK_VOLUME");
								
												System.out.println("LAST PACK WEIGHT FROM THE MAP["+lastPackWeight+"]");
												System.out.println("LAST PACK VOLUME FROM THE MAP>>>>>>>>>>>>["+lastPackVolume+"]");
												
												double currentWeight = packetMaxWeightActiveCount * itemWeight;
												double currentCaseVolume = packetMaxWeightActiveCount * perItemVolume;
												
												System.out.println("CURRENT WEIGHT TO STORE["+currentWeight+"]");
												System.out.println("CURRENT VOLUME TO STORE["+currentCaseVolume+"]");
												
												if(lastPackWeight < packetMaxWeightActive && lastPackVolume < packetMaxVolumeActive )
												{
													remainingWeight = packetMaxWeightActive - lastPackWeight;
													remainingVolume = packetMaxVolumeActive  - 	lastPackVolume;	
													
													System.out.println("REMAINING WEIGHT TO STORE ["+remainingWeight+"]");
													System.out.println("REMAINING VOLUME TO STORE ["+remainingVolume+"]");
													
													if(remainingWeight >= itemWeight && remainingVolume >= perItemVolume )
													{
														
														if(remainingWeight >= currentWeight && remainingVolume >= currentCaseVolume )//&& (lastPackCount + packetMaxWeightActiveCount) <= masterPackCount)
														{
															
															HashMap activeTempMap = (HashMap)actDataMap.clone();			
															activeTempMap.put("no_art", "1");
															activeTempMap.put("alloc_qty", packetMaxWeightActiveCount);
															activeTempMap.put("LAST_PACK_WEIGHT", lastPackWeight + Math.round((packetMaxWeightActiveCount * itemWeight)));
															activeTempMap.put("LAST_PACK_VOLUME", (currentCaseVolume + lastPackVolume));
															activeTempPickList.add(activeTempMap);
															int updLen = allActivesList.size()-1;
															allActivesList.set(updLen,activeTempPickList);
															
														}
														else
														{
																			
															double requiredQuantityToStoreWeight = Math.round(remainingWeight / itemWeight);	
															double requiredQuantityToStore = Math.round(remainingVolume / perItemVolume);	
															
															
															if(requiredQuantityToStoreWeight > requiredQuantityToStore)
															{
																requiredQuantityToStoreWeight = requiredQuantityToStore;
															}
														
															HashMap activeTempMap = (HashMap)actDataMap.clone();	
															activeTempMap.put("no_art", "1");
															activeTempMap.put("alloc_qty", requiredQuantityToStoreWeight);
															activeTempMap.put("LAST_PACK_WEIGHT",lastPackWeight + Math.round((requiredQuantityToStoreWeight * itemWeight)));
															activeTempMap.put("LAST_PACK_VOLUME", Math.round((requiredQuantityToStoreWeight * perItemVolume)) + lastPackVolume);	
															activeTempPickList.add(activeTempMap);
															
															lastPackWeight = lastPackWeight + Math.round((requiredQuantityToStoreWeight * itemWeight));
															lastPackVolume = lastPackVolume + Math.round((requiredQuantityToStoreWeight * perItemVolume));
															
															double requiredVolumeToStore = currentCaseVolume - Math.round((requiredQuantityToStoreWeight * perItemVolume));
															double requiredWeightToStore = currentWeight - Math.round((requiredQuantityToStoreWeight * itemWeight));
															
															
															if(requiredWeightToStore == 0 || requiredVolumeToStore == 0)
															{
																requiredQuantityToStoreWeight = packetMaxWeightActiveCount - requiredQuantityToStoreWeight;
																
															}
															else
															{
																System.out.println("Quantity requiredVolumeToStore["+requiredVolumeToStore+"]");
																System.out.println("Quantity requiredVolumeToStore["+requiredWeightToStore+"]");
																
																requiredQuantityToStore = Math.round((requiredVolumeToStore /perItemVolume));
																requiredQuantityToStoreWeight = Math.round((requiredWeightToStore /itemWeight));
																
																activeTempPickList = new ArrayList();
																HashMap activeTempMap1 = (HashMap)actDataMap.clone();	
																
																if(requiredQuantityToStore > requiredQuantityToStoreWeight)
																{
																	requiredQuantityToStore = requiredQuantityToStoreWeight;
																}
															}
															
														
															HashMap activeTempMap1 = (HashMap)actDataMap.clone();	
															if(requiredQuantityToStore > 0)
															{
																activeTempMap1.put("no_art","1");
																activeTempMap1.put("alloc_qty", requiredQuantityToStore );
															}
															
															
															System.out.println("Required Volume to be stored  %%%%%%%%%%%%%%%%%%%%%%["+requiredVolumeToStore+"]");
															System.out.println("Required Weight to be stored  %%%%%%%%%%%%%%%%%%%%%%["+requiredWeightToStore+"]");
															System.out.println("Quantity Stored as %%%%%%%%%%%%%%%%%%%%%%["+requiredQuantityToStore+"]");
															
															if((requiredWeightToStore + lastPackWeight) > packetMaxWeightActive)
															{
																activeTempMap1.put("LAST_PACK_WEIGHT", requiredWeightToStore);
															}
															else
															{
																activeTempMap1.put("LAST_PACK_WEIGHT", (requiredWeightToStore + lastPackWeight));
															}
															
															if((requiredVolumeToStore + lastPackVolume) > packetMaxVolumeActive)
															{
																activeTempMap1.put("LAST_PACK_VOLUME", requiredVolumeToStore);
														
															}
															else
															{
																activeTempMap1.put("LAST_PACK_VOLUME", requiredVolumeToStore + lastPackVolume);
															
															}		
															
															activeTempPickList.add(activeTempMap1);
															int updLen1 = activeTempPickList.size()-1;
															allActivesList.add(activeTempPickList);
															
														}
													}
													else
													{
														activeTempPickList = new ArrayList();
														HashMap activeTempMap = (HashMap)actDataMap.clone();	
														activeTempMap.put("no_art", "1");
														activeTempMap.put("alloc_qty", packetMaxWeightActiveCount );
														
														lastPackWeight = Math.round(packetMaxWeightActiveCount * itemWeight);
														lastPackVolume = Math.round(packetMaxWeightActiveCount * perItemVolume);
														activeTempMap.put("LAST_PACK_WEIGHT", lastPackWeight);
														activeTempMap.put("LAST_PACK_VOLUME", lastPackVolume);
														activeTempPickList.add(activeTempMap);
														allActivesList.add(activeTempPickList);
													}
												}
												else
												{
													activeTempPickList = new ArrayList();
													HashMap activeTempMap = (HashMap)actDataMap.clone();	
													activeTempMap.put("no_art", "1");
													activeTempMap.put("alloc_qty", packetMaxWeightActiveCount );
													
													lastPackWeight = Math.round(packetMaxWeightActiveCount * itemWeight);
													lastPackVolume = Math.round(packetMaxWeightActiveCount * perItemVolume);
															
													activeTempMap.put("LAST_PACK_VOLUME",lastPackVolume);
													activeTempMap.put("LAST_PACK_WEIGHT",lastPackWeight);		
													activeTempPickList.add(activeTempMap);
													allActivesList.add(activeTempPickList);
				
												}
										}
									
								}
								else
								{
									
									
									System.out.println("### Active PICK MAP Doesn't Exist.......");
									activeTempPickList = new ArrayList();
									HashMap activeTempMap = (HashMap)actDataMap.clone();			
									activeTempMap.put("no_art", "1");
									activeTempMap.put("alloc_qty", packetMaxWeightActiveCount);
									
									double lastPackWeight = Math.round(packetMaxWeightActiveCount * itemWeight);
									double lastPackVolume = Math.round(packetMaxWeightActiveCount * perItemVolume);
									
									activeTempMap.put("LAST_PACK_WEIGHT", lastPackWeight);
									activeTempMap.put("LAST_PACK_VOLUME", lastPackVolume);
									activeTempPickList.add(activeTempMap);
									allActivesList.add(activeTempPickList);									
								}
																
								currentActiveCount = currentActiveCount - packetMaxWeightActiveCount;
				
								if((currentActiveCount /packetMaxWeightActiveCount) < 1)
								{						
									System.out.println("packetMaxWeightActiveCount**************["+packetMaxWeightActiveCount+"]");
									
									packetMaxWeightActiveCount = currentActiveCount;
								}
				
								if(currentActiveCount <= 0)
								{
									System.out.println("currentActiveCount===============["+currentActiveCount+"]");
									break;
								}
								
								if(packetMaxWeightActiveCount <= 0)
								{
									System.out.println("packetMaxWeightActiveCount===============["+packetMaxWeightActiveCount+"]");
									break;
								}
				
								wCounter++;
								
							}		
							while(wCounter <= ActiveWeightCount);
							
							packetMaxWeightActiveCount = Math.floor(packetMaxWeightActive/itemWeight);
							packetMaxVolumeActiveCount = Math.floor(packetMaxVolumeActive/perItemVolume);
							
							if(packetMaxWeightActiveCount > packetMaxVolumeActiveCount)
							{
								totalQtyOnPallet = packetMaxVolumeActiveCount;
							}
							else
							{
								totalQtyOnPallet = packetMaxWeightActiveCount;
							}
							quantity = quantity - totalQtyOnPallet;
							
							if(totalQtyOnPallet > quantity )
							{	
								totalQtyOnPallet = quantity;
							}
							
							if(totalQtyOnPallet <=0)
							{
								break;
							}
							
							counter++;
							System.out.println("REMAINING CASE COUNT["+quantity+"]"+"totalQtyOnPallet"+totalQtyOnPallet);
							System.out.println("CURRENT PACKET COUNTER"+activeCounter+"]COUNT["+counter+"]");
				
					    }		
					    while(counter < activeCounter);
						
					}		
				 }
			  }			
			  long endTime12 = System.currentTimeMillis();
			  System.out.println("DIFFERANCE IN TIME FOR activeListItemWizMapL IN SECONDS:::["+(endTime12-startTime12)/1000+"]");
				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 = ?";
				//changed by sankara on 15/07/14 update status in pick order det
				sSQLUpdPkDet = " UPDATE PICK_ORD_DET 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);
				long startTime13 = System.currentTimeMillis();
				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");
							//Cold Chain changed by Pragyan on 19-SEP-14   [W14FSUN003]	
							locTypeParent = (String)tempMap.get("loc_type_parent");
							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();

				}
				long endTime13 = System.currentTimeMillis();
				
				System.out.println("DIFFERANCE IN TIME FOR REPL AND PICK FOR STOCK TO DOCK IN SECONDS:::["+(endTime13-startTime13)/1000+"]");
				
				int allCasePickListLen = allCasePickList.size();
				System.out.println("allCasePickList-=-=-=-=-===>"+allCasePickList.toString());
				long startTime14 = System.currentTimeMillis();
				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");
							//Cold Chain changed by Pragyan on 19-SEP-14   [W14FSUN003]	
							locTypeParent = (String)tempMap.get("loc_type_parent");
							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))
								{
									//^^^^^^^
									////updateStkReplQty(locCode, itemCode, lotNo, lotSl, Double.parseDouble(replQuantity), conn);
									
									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));
									if(!( Double.parseDouble(replQuantity) < packSizeCase))
									{
										pstmtRplDet.setDouble(11, Double.parseDouble(replQuantity));//Changes Done By Ashish
									}
									else
									{
										errString = itmDBAccessEJB.getErrorString("","VTREPLQUAN","","",conn);
										return errString;
										
									}
									/*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);
						}		
			
					}
			
				}
				long endTime14 = System.currentTimeMillis();
				System.out.println("DIFFERANCE IN TIME FOR REPL AND PICK ORDER FOR CASE PICKING IN SECONDS:::["+(endTime14-startTime14)/1000+"]");		
				int lengthOfMaster = allMasterPackList.size();
				long startTime15 = System.currentTimeMillis();
				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");
							//Cold Chain changed by Pragyan on 19-SEP-14   [W14FSUN003]	
							locTypeParent = (String)tempMap.get("loc_type_parent");
							//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);
										//changed by sankara on 17/09/14 for direct pick loc insert emp code
										//pstmtIssHdr.setString(7,chgUser);
										pstmtIssHdr.setString(7,loginEmpCode);
										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))
								{
									//^^^^^^^^^^^^
									///updateStkReplQty(locCode, itemCode, lotNo, lotSl, Double.parseDouble(replQuantity), conn);
									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));
									if(!( Double.parseDouble(replQuantity) < packSizeCase))
									{
										pstmtRplDet.setDouble(11, Double.parseDouble(replQuantity));
									}
									else
									{
										errString = itmDBAccessEJB.getErrorString("","VTREPLQUAN","","",conn);
										return errString;
									}
									/*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
							{
								//Changed By Pragyan 28/aug/13 at USA.start
								/*if("0".equalsIgnoreCase(prvPickOrd))
								{
									pstmtDet.setString(14, "");
									
								}
								else
								{
									pstmtDet.setString(14, prvPickOrd);
								}
								pstmtDet.setInt(15, prvPickLineNo);*/
								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);
								}
								//Changed By Pragyan 28/aug/13 at USA.end
								
							}
							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 sankara on 15/07/14 for update pick ord det status.
								pstmtPickDet = conn.prepareStatement(sSQLUpdPkDet);	
								pstmtPickDet.setString(1, pickRefId);
								pstmtPickDet.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);
								
								//Changed By Pragyan 12/12/14 To fix the bug master pack generated wrong same item in diffrent sord line item.start
								System.out.println("STORING PICK ORDER["+pickRefId+"]pickCtr["+pickCtr+"]noArt["+noArt+"]sordLineNo["+sordLineNo+"]");
								/*if(mapItemPick.containsKey(itemCode + ":"+ lotSl))
								{
									allItemPickkList = (ArrayList)mapItemPick.get(itemCode+":"+lotSl);
									allItemPickkList.add(tempPickMap);
									mapItemPick.put(itemCode, allItemPickkList);
								}
								else
								{								
									allItemPickkList = new ArrayList();
									allItemPickkList.add(tempPickMap);
									mapItemPick.put(itemCode + ":"+ lotSl, allItemPickkList);
								}*/
								if(mapItemPick.containsKey(itemCode + ":"+ lotSl+":"+sordLineNo))
								{
									allItemPickkList = (ArrayList)mapItemPick.get(itemCode + ":"+ lotSl+":"+sordLineNo);
									allItemPickkList.add(tempPickMap);
									mapItemPick.put(itemCode + ":"+ lotSl+":"+sordLineNo, allItemPickkList);
								}
								else
								{								
									allItemPickkList = new ArrayList();
									allItemPickkList.add(tempPickMap);
									mapItemPick.put(itemCode + ":"+ lotSl+":"+sordLineNo, allItemPickkList);
								}
								
								System.out.println("mapItemPick["+mapItemPick.toString()+"]");
								
								//Changed By Pragyan 12/12/14 To fix the bug master pack generated wrong same item in diffrent sord line item.end
							}
							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)))
						{	
							//Changed By Pragyan for cold chain on 19-SEP-14   [W14FSUN003]	
							//updateCartonMaster(pickRefId, cCTR + 1,Double.parseDouble("1"),ptcn,"M-PACK", xtraParams, conn,caseWeightTotal,caseVolumeTotal,pickType,"");
							updateCartonMaster(pickRefId, cCTR + 1,Double.parseDouble("1"),ptcn,"M-PACK", xtraParams, conn,caseWeightTotal,caseVolumeTotal,pickType,"",facilityCode,locTypeParent);
							System.out.println("updateCartonMaster M-PACK 6");
						}			
						
						ctrMaster++;
					}
					String nafFlag ="";
					if((!"Y".equalsIgnoreCase(pPickAllow)))
					{
						int allMasterListlen = allMasterList.size();
						String masterCartonNo = "";
						//Change For ADSI
						CommodityInfo[] infoCom = null;
						String itmLen = null;
						String itmWidth= null;
						String itmHeight = null;
						PreparedStatement pstmt2 = null;
						ResultSet rs2 = null;;
						String sqlSize=null;
						nafFlag = discommon.getDisparams("999999","NAFTA_FLAG_COUNT",conn);
						double slength = 0;
						double  width =0;
						double height=0;
						//Cold Chain changed by Pragyan on 19-SEP-14   [W14FSUN003]	
						double tareWt = 0.0;
						double fillerWt = 0.0; 
						int existPackageLen = 0;
						//Change For ADSI.start
						if("Y".equalsIgnoreCase(isADSIConnReq))
						{
							//packgeList = new Package2[allMasterListlen];
							if(shipment2.getPackages2() != null)
							{
								existPackageLen = shipment2.getPackages2().length;
							}	
			
							if(existPackageLen > 0)
							{
								System.out.println("Existing packages1["+existPackageLen+"]");
								
								Package2[] existPack2 = shipment2.getPackages2();
								packgeList = new Package2[allMasterListlen + existPackageLen];
								for(int pCtr = 0;pCtr < existPackageLen ;pCtr ++)
								{
									System.out.println("Existing ID["+existPack2[pCtr].getID()+"]pCtr["+pCtr+"]");
									packgeList[pCtr] = existPack2[pCtr];
								}
								
							}
							else
							{
								
								System.out.println("Existing packages2["+existPackageLen+"]");
								packgeList = new Package2[allMasterListlen];
							}
						}
						
						//Changed for Cold Chain changed by Pragyan on 19-SEP-14   [W14FSUN003]	
						//sqlSize = "SELECT LENGTH , WIDTH , HEIGHT FROM PACKING WHERE PACK_CODE = (SELECT PACK_CODE FROM CARTON_MASTER WHERE CARTON_NO = ? )";
						sqlSize = "SELECT C.PACK_CODE,C.TARE_WEIGHT,C.FILLER_WEIGHT, P.LENGTH , P.WIDTH , P.HEIGHT " 
								+" FROM CARTON_MASTER C,PACKING P WHERE C.PACK_CODE = P.PACK_CODE AND C.CARTON_NO  = ? ";
						pstmt2 = conn.prepareStatement(sqlSize);
						
						System.out.println("Started len["+existPackageLen+"]total length ["+allMasterListlen + existPackageLen+"]master len["+allMasterListlen+"]");
						for(int j = 0 ;j < allMasterListlen ; j++)
						{
							
							//isADSIConnReq
							//pkg2 =  new Package2();
							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+"]");
							
							//Changed for Cold Chain changed by Pragyan on 19-SEP-14   [W14FSUN003]	
							//masterCartonNo = updateCartonMaster(packRefId, j + 1,Double.parseDouble("1"),ptcn,"M-PACK", xtraParams, conn,caseWeightTotal,caseVolumeTotal,pickType,"");
							masterCartonNo = updateCartonMaster(packRefId, j + 1,Double.parseDouble("1"),ptcn,"M-PACK", xtraParams, conn,caseWeightTotal,caseVolumeTotal,pickType,"",facilityCode,locTypeParent);
							//Change For ADSI.start
							if("Y".equalsIgnoreCase(isADSIConnReq))
							{
									pkg2 =  new Package2();
									NameValuePair[] additionalFields = new NameValuePair[1];
									additionalFields[0] = new NameValuePair("carton_no", masterCartonNo);
									//CHANGE BY REKHA ON 23-05-13
									masterOrParclNoList.add(masterCartonNo);
							       //Changed by Pragyan on 19-SEP-14   [W14FSUN003]	
									/*pkg2.setID(masterCartonNo);
									pkg2.setWeight(caseWeightTotal);*/
									
									pstmt2.setString(1, masterCartonNo);
									rs2 = pstmt2.executeQuery();
									
									if(rs2.next())
									{
										slength =rs2.getDouble("LENGTH");																					
										width = rs2.getDouble("WIDTH");
										height =rs2.getDouble("HEIGHT");
										//Cold Chain changed by Pragyan on 19-SEP-14   [W14FSUN003]	
										tareWt  = rs2.getDouble("TARE_WEIGHT");
										fillerWt  = rs2.getDouble("FILLER_WEIGHT");
									}										
									pstmt2.clearParameters();
									//Changed by pragyan on 19-SEP-14   [W14FSUN003]	
									pkg2.setID(masterCartonNo);
									System.out.println("masterCartonNo["+masterCartonNo+"]case weight["+caseWeightTotal+"]tare weight["+tareWt+"]Filler Weight["+fillerWt+"]Total["+(caseWeightTotal+tareWt+fillerWt)+"]");
									pkg2.setWeight(caseWeightTotal+tareWt+fillerWt);
									
									String strlen = ""+slength;
									String widthStr = ""+width;
									String heightStr = ""+height;
									strlen = Double.toString(slength);
									widthStr=Double.toString(width);
									heightStr = Double.toString(height);
									/*itmLen = rs.getDouble("ITEM_LEN");
									itmWidth = rs.getDouble("ITEM_WID");
									itmHeight = rs.getDouble("ITEM_HEIGHT");*/
									pkg2.setDimension(slength+"x"+widthStr+"x"+heightStr);	
									System.out.println("Dimension of master package :"+pkg2.getDimension());
									//pkg2.setTrackingNumber("");//Not Required Optional
									pkg2.setDescription("Pharmaceuticals");//As per Taro 
									pkg2.setOversizeFlag(false);//As per Taro 
									pkg2.setDeclaredValueFlag(false);//As per Taro 
									pkg2.setDeclaredValueAmount(0.0);//As per Taro not required
									pkg2.setDeclaredValueCustoms(0.0);//As per Taro not required
									pkg2.setBillOfLadingComment("");//As per Taro not required
									pkg2.setAdditionalHandlingFlag(false);//As per Taro false
									pkg2.setPackaging(EnumPackageType.pkgCUSTOM);//As per Taro default pkgCUSTOM
									pkg2.setCODFlag(false);//As per Taro false
									pkg2.setCODAmount(0.0);//As per Taro not required 
									pkg2.setCODPaymentType(0);//As per Taro not required 
									Address addr = new Address();
									pkg2.setCODReturnAddress(addr);//As per Taro not required 
									pkg2.setAdditionalFields(additionalFields);
									infoCom = new CommodityInfo[tempList.size()];
							}//if("Y".equalsIgnoreCase(isADSIConnReq))
							
							
							//Change For ADSI.end
							//isADSIConnReq
							//infoCom = new CommodityInfo[tempList.size()];
							for(int k =0 ; k < tempList.size() ; k++)
							{
								
								HashMap tempMap = (HashMap)tempList.get(k);
								itemCode = (String)tempMap.get("item_code");
								lotNo = (String)tempMap.get("lot_no");
								noArt = (String)tempMap.get("no_art");
								lotSl = (String)tempMap.get("lot_sl");
								System.out.println("Item Name["+itemCode+"]");
								System.out.println("Lot Sl------------["+lotSl+"]------------");
								System.out.println("No Of Art["+noArt+"]");
								System.out.println("Alloc Qty["+tempMap.get("alloc_qty")+"]");
								itmVolumeMap = getItemVoumeMap(itemCode,"",conn);
								packSizeCase = (Double)itmVolumeMap.get("PACK_SIZE");
								perItemVolume = (Double)itmVolumeMap.get("ITEM_SIZE");
								caseVolume = (Double)itmVolumeMap.get("LOT_SIZE");
								caseWeight = (Double)itmVolumeMap.get("PACK_WEIGHT");
								itemWeight = (Double)itmVolumeMap.get("ITEM_WEIGHT");
								hazardous = (String)itmVolumeMap.get("HAZARDOUS");
								harmonizCode = (String)itmVolumeMap.get("HARMONIZATION_NO");
								harmonizDescr = (String)itmVolumeMap.get("HARMONIZATION_DESCR");
								originCountry = (String)itmVolumeMap.get("ORIGIN_COUNTRY");
								/*itmLen = itmVolumeMap.get("ITEM_LEN").toString();
								itmWidth = (String)itmVolumeMap.get("ITEM_WID").toString();
								itmHeight = (String)itmVolumeMap.get("ITEM_HEIGHT").toString();*/	
								unitValue = getRateStdoum(saleOrder, itemCode, conn);
								//Changed By Pragyan 12/12/14 To fix the bug master pack generated wrong same item in diffrent sord line item
								//ArrayList valList = (ArrayList)mapItemPick.get(itemCode + ":" + lotSl);
								ArrayList valList = (ArrayList)mapItemPick.get(itemCode + ":" + lotSl + ":" +((String)tempMap.get("sord_lineNo")));
								int valListLen = valList.size();
								
								//isADSIConnReq
								if("Y".equalsIgnoreCase(isADSIConnReq))
								{
									//if("Y".equalsIgnoreCase(hazardous))
									if("Y".equalsIgnoreCase(hazardous) && "A".equalsIgnoreCase(transMode))
									{
										System.out.println("HAZARDOUS AND TRAN MODE AIR");
										pkg2.setHazmatFlag(true);
									}
									else
									{
										System.out.println("MAY HAZARDOUS AND TRAN MODE NOT AIR["+hazardous+"]");
										pkg2.setHazmatFlag(false);
									}
									comInfo = new CommodityInfo();
									
									comInfo.setDescription(harmonizDescr);//As per taro Harmonization description
									comInfo.setQuantity(Double.parseDouble(noArt) * packSizeCase);
									//comInfo.setQuantity();
									comInfo.setHarmonizedCode(harmonizCode);//As per Taro Haromonization code
									comInfo.setUnitValue(unitValue);
									comInfo.setUnitWeight(caseWeight);
									originCountry = originCountry!=null?originCountry.trim():"";
									Country originCountryMfg = soap.getCountry("ISO3", originCountry).getResponseCountry();
									comInfo.setOriginCountry(originCountryMfg);
									//change by rekha on 31-05-13 start
									System.out.println("VALUES IN NAFTA VALUES "+nafFlag);
									
									
									if(nafFlag.indexOf(shipCountry) != -1)
									{
										comInfo.setNaftaFlag(true);
										System.out.println("available in disparm");
									}
									else
									{
										System.out.println("not in disparm");
										comInfo.setNaftaFlag(false);//False as Per Taro Need To change canda/Mexico as true.
									}
									
									
									
									Calendar calendar = Calendar.getInstance();
									comInfo.setExportNumberExpireDate(calendar);
									comInfo.setUnitOfMeasure(EnumUnitOfMeasure.uomPCS);
									infoCom[k] = comInfo;
									comodityInfoList.add(comInfo);
									System.out.println("Commodity Info List"+infoCom.toString());
								}//if("Y".equalsIgnoreCase(isADSIConnReq))
								
								int pickCtr =0;
								for(int vCtr = 0; vCtr < valListLen;vCtr++)
								{
									HashMap vMap = (HashMap)valList.get(vCtr);
									double currentnoArt = (Double)vMap.get("no_art");
									System.out.println("Current No Of Article--["+currentnoArt+"]---["+vCtr+"]");
									
									if(currentnoArt <= 0.0)
									{
										continue;
									}
									
									pickRefId = (String)vMap.get("pick_order");
									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);
									System.out.println("Setting back  the no art --["+(currentnoArt - Double.parseDouble(noArt))+"]---");
									vMap.put("no_art", currentnoArt - Double.parseDouble(noArt));
								}
								
								//updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"M-PICK", xtraParams,masterCartonNo,itemCode, conn);
								//isADSIConnReq
								//comodityInfoList.add(comInfo);
								
							}
							//System.out.println("Commodity Info List"+infoCom.toString());
							//CommodityInfo[] infoCom = (CommodityInfo[])comodityInfoList.toArray();
							
							//infoCom[0] = comInfo;
							//if("Y".equalsIgnoreCase(isADSIConnReq))
							if("Y".equalsIgnoreCase(isADSIConnReq))
							{
								pkg2.setCommodityInfos(infoCom);
								packgeList[j + existPackageLen] = pkg2;
							}
							
						}
						
						if(directPickLoc != null && directPickLoc.length() > 0)
						{
							updatePalletNo(ptcn, palletNo, conn);
						}
						
						if(pstmt2 != null)
						{
							pstmt2.close();
							pstmt2 = null;
						}
						
						if(rs2 != null)
						{
							rs2.close();
							rs2 = null;
						}
						
						
					}
					else
					{
						//Change by rekha on 21-05-13 start
						
						System.out.println("parcel pick value is :"+pPickAllow);
						String sqlQuery = "";
						double rateStdOum = 0.0;
						PreparedStatement pstmt1 = null;
						ResultSet rs = null;
						String lotLen=null; 
						String lotWidth=null; 
						String lotHeight  = null; 
						TreeMap<String, String>  tempMap = new TreeMap<String, String> ();
						System.out.println("parcel pick value is in try :"+pPickAllow);
						
						sqlQuery = "SELECT ITEM_CODE,CARTON_NO FROM CARTON_MASTER WHERE PTCN = ? AND CARTON_TYPE ='P' AND PICK_ORDER = ? ORDER BY CARTON_NO";
						pstmt1 = conn.prepareStatement(sqlQuery);
						pstmt1.setString(1, ptcn);
						pstmt1.setString(2, pickRefId);
						
						rs = pstmt1.executeQuery();
						
						while(rs.next())
						{
							
							String cartonNo = rs.getString("CARTON_NO");																							
							itemCode = rs.getString("ITEM_CODE");
							tempMap.put(cartonNo, itemCode);	
						}	
						
						if(pstmt1 != null)
						{
							pstmt1.close();
							pstmt1 = null;
						}
						
						if(rs != null)
						{
							rs.close();
							rs = null;
						}
						
						Set keySetCarton = tempMap.keySet();
						Iterator itemIterator= keySetCarton.iterator();			
						
						int n=tempMap.size();	
						

						
						int existPackageLen = 0;
						System.out.println("temp map Size"+n+"[["+tempMap.toString()+"]");
						
						if("Y".equalsIgnoreCase(isADSIConnReq))
						{
							//packgeList = new Package2[allMasterListlen];
							if(shipment2.getPackages2() != null)
							{
								existPackageLen = shipment2.getPackages2().length;
							}	
							//packgeList = new Package2[n];
							if(existPackageLen > 0)
							{
								System.out.println("Existing packages1["+existPackageLen+"]"+"N length"+n);
								
								Package2[] existPack2 = shipment2.getPackages2();
								packgeList = new Package2[n + existPackageLen];
								for(int pCtr = 0;pCtr < existPackageLen ;pCtr ++)
								{
									System.out.println("Existing ID["+existPack2[pCtr].getID()+"]pCtr["+pCtr+"]");
									packgeList[pCtr] = existPack2[pCtr];
								}
								
							}
							else
							{
								
								System.out.println("Existing packages2["+existPackageLen+"]"+"N lenght"+n);
								packgeList = new Package2[n];
							}
						}//if("Y".equalsIgnoreCase(isADSIConnReq))
							
						String masterCartonNo = "";
							
						int Ctr=0;
						String tempItem = "";
						String tempKey = "";
						String tempValue = "";
						int cnt=0;
						//Changed by Rohan on 25-07-13 for bug fixing.start
						while(itemIterator.hasNext())
						{
							System.out.println("Ctr=================="+Ctr);
							tempKey = (String)itemIterator.next();							
							tempValue =(String)tempMap.get(tempKey);
							System.out.println("parcel pick value is in while :"+tempKey+"]["+tempValue+"ctr:::::"+Ctr);
				
							if(!tempItem.equalsIgnoreCase(tempValue))
							{
								System.out.println("tempKey  value is in tempValue :"+tempKey);
								tempItem = tempValue;
								itmVolumeMap = getItemVoumeMap(tempValue,"",conn);
								packSizeCase = (Double)itmVolumeMap.get("PACK_SIZE");
								caseWeight = (Double)itmVolumeMap.get("PACK_WEIGHT");
								itemWeight = (Double)itmVolumeMap.get("ITEM_WEIGHT");
								hazardous = (String)itmVolumeMap.get("HAZARDOUS");
								harmonizCode = (String)itmVolumeMap.get("HARMONIZATION_NO");
								harmonizDescr = (String)itmVolumeMap.get("HARMONIZATION_DESCR");
								originCountry = (String)itmVolumeMap.get("ORIGIN_COUNTRY");											
								lotLen = itmVolumeMap.get("LITEM_LEN").toString();
								lotWidth = (String)itmVolumeMap.get("LITEM_WID").toString();
								lotHeight = (String)itmVolumeMap.get("LITEM_HEIGHT").toString();
								
								unitValue = getRateStdoum(saleOrder, tempValue, conn);
							}
							//if("Y".equalsIgnoreCase(isADSIConnReq))
							/*NameValuePair[] additionalFields = new NameValuePair[1];
							additionalFields[0] = new NameValuePair("carton_no", tempKey);*/
						
							masterOrParclNoList.add(tempKey);
							if("Y".equalsIgnoreCase(isADSIConnReq))
							{
								NameValuePair[] additionalFields = new NameValuePair[1];
								additionalFields[0] = new NameValuePair("carton_no", tempKey);
								pkg2 =new Package2();
								pkg2.setID(tempKey);
								pkg2.setWeight(caseWeight);
								//pkg2.setDimension("10x10x10");//Hard Coded Need to change.
								
								/*lotLen = ""+rs.getDouble("LITEM_LEN");
								lotWidth = ""+rs.getDouble("LITEM_WID");
								lotHeight = ""+rs.getDouble("LITEM_HEIGHT");*/
								pkg2.setDimension(lotLen+"x"+lotWidth+"x"+lotHeight);										
								//pkg2.setDimension(lotLen+""+lotWidth*lotHeight);
								//pkg2.setDimension(String("lotLen") "x" String("lotWidth") "x" String("lotHeight"));
								System.out.println("Dimension of package in parcel:"+pkg2.getDimension());
								pkg2.setDescription("Pharmaceuticals");//As per Taro 
								pkg2.setOversizeFlag(false);//As per Taro 
								pkg2.setDeclaredValueFlag(false);//As per Taro 
								pkg2.setDeclaredValueAmount(0.0);//As per Taro not required
								pkg2.setDeclaredValueCustoms(0.0);//As per Taro not required
								pkg2.setBillOfLadingComment("");//As per Taro not required
								pkg2.setAdditionalHandlingFlag(false);//As per Taro false
								pkg2.setPackaging(EnumPackageType.pkgCUSTOM);//As per Taro default pkgCUSTOM
								pkg2.setCODFlag(false);//As per Taro false
								pkg2.setCODAmount(0.0);//As per Taro not required 
								pkg2.setCODPaymentType(0);//As per Taro not required 
								pkg2.setAdditionalFields(additionalFields);
								//Changed By Pragyan 29-mar-14 as per (Ashish) allow haz in case only if tarns mode is AIR
								//if("Y".equalsIgnoreCase(hazardous))
								if("Y".equalsIgnoreCase(hazardous) && "A".equalsIgnoreCase(transMode))
								{
									System.out.println("HAZARDOUS AND TRAN MODE AIR");
									pkg2.setHazmatFlag(true);
								}
								else
								{
									System.out.println("MAY HAZARDOUS AND TRAN MODE NOT AIR["+hazardous+"]");
									pkg2.setHazmatFlag(false);
								}
								Address addr = new Address();
								pkg2.setCODReturnAddress(addr);//As per Taro not required	NAFTA_FLAG_COUNT
								nafFlag = discommon.getDisparams("999999","NAFTA_FLAG_COUNT",conn);
								CommodityInfo[] infoCom1 = new CommodityInfo[1] ;
								comInfo = new CommodityInfo();
								comInfo.setDescription(harmonizDescr);
								comInfo.setQuantity(Double.parseDouble(noArt) * packSizeCase);
								comInfo.setHarmonizedCode(harmonizCode);//As per Taro Haromonization code
								comInfo.setUnitValue(unitValue);
								comInfo.setUnitWeight(itemWeight);
								originCountry = originCountry!=null?originCountry.trim():"";
								Country originCountryMfg = soap.getCountry("ISO3", originCountry).getResponseCountry();
								comInfo.setOriginCountry(originCountryMfg);
								
								if(nafFlag.indexOf(shipCountry) != -1)
								{
									comInfo.setNaftaFlag(true);
									System.out.println("available in disparm");
								}
								else
								{
									System.out.println("not in disparm");
									comInfo.setNaftaFlag(false);//False as Per Taro Need To change canda/Mexico as true.
									
								}
								
								Calendar calendar = Calendar.getInstance();
								comInfo.setExportNumberExpireDate(calendar);
								//Changed By Pragyan 21-Oct-13 to fix the bog for unit as Pices for Parcel
								//comInfo.setUnitOfMeasure(EnumUnitOfMeasure.uomLB);
								comInfo.setUnitOfMeasure(EnumUnitOfMeasure.uomPCS);
								infoCom1[0] = comInfo;
								pkg2.setCommodityInfos(infoCom1);
								System.out.println("Ctr"+Ctr+"existPackageLen"+existPackageLen+"]");
								packgeList[Ctr + existPackageLen]=pkg2;	
								//Changed by Rohan on 25-07-13 for bug fixing.start
							}//if("Y".equalsIgnoreCase(isADSIConnReq))
							Ctr++;
							System.out.println("going for nex for loop====>"+Ctr+"]");
						}
						//Ctr = Ctr - 1;										
						System.out.println("parcel pick value is in next while"+(Ctr));
					}
					//Change by rekha on 21-05-13 end
					
					///if("Y".equalsIgnoreCase(isADSIConnReq))
					//if(packgeList != null && packgeList.length > 0)
					if("Y".equalsIgnoreCase(isADSIConnReq) && packgeList != null && packgeList.length > 0)
					{
						System.out.println("Setting Packages To Shipment In Master/Parcel["+packgeList.length+"]");
						shipment2.setPackages2(packgeList);
					}
					
				}
				long endTime15 = System.currentTimeMillis();
				System.out.println("DIFFERANCE IN TIME FOR REPL AND PICK ORDER FOR CASE PICKING IN SECONDS:::["+(endTime15-startTime15)/1000+"]");		
				System.out.println("allActivesListLen::::"+allActivesList.toString());
				int allActivesListLen = allActivesList.size();
				long startTime16 = System.currentTimeMillis();
				if(allActivesListLen > 0)
				{
					int pickCtr =  1;
					double packSizeCase = 0;
					int cnt = 0;
					String activeCartonNo = "";
					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;
					//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam.start
					String activeReplSplitCnt = discommon.getDisparams("999999","ACTIVE_REPL_SPILT_COUNT",conn);
					//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam.start
                    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 = "";
								locCode = (String)tempMap.get("loc_code");
								System.out.println("Item CODEEEE====>"+itemCode+"location code"+locCode);
								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");
								//Cold Chain changed by Pragyan on 19-SEP-14   [W14FSUN003]	
								locTypeParent = (String)tempMap.get("loc_type_parent");
								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"));
								//itemVolume = Math.round((Double)mapItemVolume.get("ITEM_SIZE"));
								//double itemWeight= Math.floor((Double)mapItemVolume.get("ITEM_WEIGHT"));
								itemWeight = Math.floor((Double)mapItemVolume.get("ITEM_WEIGHT"));
								//itemWeight= Math.round((Double)mapItemVolume.get("ITEM_WEIGHT"));
								packSizeCase = (Double)mapItemVolume.get("PACK_SIZE");
								System.out.println("CHECKING FOR THE WRONG PACK SIZE3 casePackSize["+casePackSize+"]packSizeCase["+packSizeCase+"]itemCode["+itemCode+"]locCode["+locCode+"]");
								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));
								if(!(casePackSize < packSizeCase))
								{
									pstmtRplDet.setDouble(11, casePackSize);
								}
								else
								{
									System.out.println("CHECKING FOR THE WRONG PACK SIZE4 casePackSize["+casePackSize+"]packSizeCase["+packSizeCase+"]itemCode["+itemCode+"]locCode["+locCode+"]locInvStat["+locInvStat+"]");
									errString = itmDBAccessEJB.getErrorString("","VTREPLQUAN","","",conn);
									return errString;
								}
							
								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 && tempCaseReplList.size() == 0)
									 {
										 tempCaseReplList = getActiveCaseReplMap("X",locInvStat,invPndReserve,invDeepReserve,invReserve, itemCode, siteCode, locCode, lotNo, lotSl, quantity, conn);
									 }
									 //Changes by Dadaso pawar on 11/02/15 [Start] Resolved Multiple active Repl. from same case pick location.  
									 if(tempReplList.size() == 0 && tempCaseReplList.size() == 0)
									 {
										 tempReplList = getActiveCaseReplMap("Q",locInvStat,invPndReserve,invDeepReserve,invReserve, itemCode, siteCode, locCode, lotNo, lotSl, quantity, conn);
									 }
									 //Changes by Dadaso pawar on 11/02/15 [End] Resolved Multiple active Repl. from same case pick location.
								}					
								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(activePickInv.equalsIgnoreCase(getInventoryStatus(locCodeCase, conn)))
																{
																	errString = getError(saleOrder+":"+lotNo+":"+lotSl+":"+locCodeCase,"VTREPLFRMA",conn);
																	return errString;
																}
																
																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 04-07-13 for split active replanishment task based on configuration of disparam.
																caspkLocationset.add(locCodeCase);
																//Changed by Rohan on 08-02-13 to insert 1 case into Quantity block
																//pstmtRplDet.setDouble(11, pendActQty);
																if(!(casePackSize < packSizeCase))
																{
																	pstmtRplDet.setDouble(11, packSizeCase);
																}
																else
																{
																	errString = itmDBAccessEJB.getErrorString("","VTREPLQUAN","","",conn);
																	return errString;
																}
																
																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...");
														//Changed By Pragyan 14-MAR-14 to check a validation if  replenishment is from active location.start
														if(!locInvStat.equalsIgnoreCase(activePickInv) && !(directPickLoc != null && directPickLoc.length() > 0))
														{
															if(activePickInv.equalsIgnoreCase(getInventoryStatus(locCodeCase, conn)))
															{
																errString = getError(saleOrder+":"+lotNo+":"+lotSl+":"+locCodeCase,"VTREPLFRMA",conn);
																return errString;
															}
															//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);
															//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
															caspkLocationset.add(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;
															}
															//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
															caspkLocationset.add(locCode);
															
														}
														
														
														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+"]");
															}
															//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
															dsoLocationset.add(locCode);
															
														}
														
														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;
															}
															//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
															psoLocationset.add(locCode);
															
														}
														
														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;
															}
															//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
															prsvLocationset.add(locCode);
															
														}
														
																							
														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);
															//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam.
															
															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);
														//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
														pndLocationset.add(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++;
													}
													
													
													if(activePickInv.equalsIgnoreCase(getInventoryStatus(locCodeCase, conn)))
													{
														errString = getError(saleOrder+":"+lotNo+":"+lotSl+":"+locCodeCase,"VTREPLFRMA",conn);
														return errString;
													}
												
													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 04-07-13 for split active replanishment task based on configuration of disparam
													caspkLocationset.add(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");
											System.out.println("oh new change..["+locCodeCase+"]org location["+locCode+"]");
											if(activePickInv.equalsIgnoreCase(getInventoryStatus(locCodeCase, conn)))
											{
												System.out.println("Falling in Replenishment not exist and creating new replenishment..["+locCode+"]");
												//Changed By Pragyan To check and create another replenishment from the location
												/*errString = getError(saleOrder+":"+lotNo+":"+lotSl+":"+locCodeCase,"VTREPLFRMA",conn);
												return errString;.start*/
												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;
														}
														//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
														caspkLocationset.add(locCode);
														
													}
													
													
													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+"]");
														}
														//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
														dsoLocationset.add(locCode);
														
													}
													
													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;
														}
														//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
														psoLocationset.add(locCode);
														
													}
													
													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;
														}
														//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
														prsvLocationset.add(locCode);
														
													}
													
																						
													pstmtRplDet.setString(1,replRefDeepId);
													pstmtRplDet.setInt(2,refCtr);
													pstmtRplDet.setString(12,"");
													//replCnt++;
													pstmtRplDet.setInt(13,0);
													
													if(locInvStat.equalsIgnoreCase(partialResrvLoc))
													{
														//Changed By Pragyan 21-may-14 to get stock quantity.start
														//double stkQty = getStockQty(itemCode, siteCode, lotNo, lotSl, locCode);
														double stkQty = getStockQuantity(itemCode, siteCode, locCode, lotNo, lotSl, 0.0, conn) ;
														System.out.println("Stock Quantity for prsv"+stkQty);
														
														if(stkQty > 0)
														{
															
															packSizeCase = stkQty;
															pstmtRplDet.setDouble(11, stkQty);
														}
														else
														{
															
																errString = itmDBAccessEJB.getErrorString("","VTREPLQUAN","","",conn);
																return errString;
														}
														//Changed By Pragyan 21-may-14 to get stock quantity.end
														
													}
													
													if(locInvStat.equalsIgnoreCase(invDeepReserve))
													{
														pndLoc = getAvilablePickLocation("N", conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
														if(pndLoc != null && pndLoc.length() > 0)
						                                {
															//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam.
															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);
													//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
													pndLocationset.add(pndLoc);
													//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam.start
													pndLocationset.add(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;
												/*End*/
											}
											//Changed By  Pragyan 06-AUG-14.start
											else
											{
											//Changed By  Pragyan 06-AUG-14.end
												
												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 04-07-13 for split active replanishment task based on configuration of disparam
												caspkLocationset.add(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...");
									//Changed By Pragyan 21-may-14
									//double stkQty = getStockQty(itemCode, siteCode, lotNo, lotSl, locCode);
									
								
									//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;
											}
											//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
											caspkLocationset.add(locCode);
											
										}
										
										
										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+"]");
											}
											//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
											dsoLocationset.add(locCode);
											
										}
										
										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;
											}
											//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
											psoLocationset.add(locCode);
											
										}
										
										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;
											}
											//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
											prsvLocationset.add(locCode);
											
										}
										
																			
										pstmtRplDet.setString(1,replRefDeepId);
										pstmtRplDet.setInt(2,refCtr);
										pstmtRplDet.setString(12,"");
										//replCnt++;
										pstmtRplDet.setInt(13,0);
										
										if(locInvStat.equalsIgnoreCase(partialResrvLoc))
										{
											//Changed By Pragyan 21-may-14 to get stock quantity.start
											//double stkQty = getStockQty(itemCode, siteCode, lotNo, lotSl, locCode);
											double stkQty = getStockQuantity(itemCode, siteCode, locCode, lotNo, lotSl, 0.0, conn) ;
											System.out.println("Stock Quantity for prsv"+stkQty);
											
											if(stkQty > 0)
											{
												
												packSizeCase = stkQty;
												pstmtRplDet.setDouble(11, stkQty);
											}
											else
											{
												
													errString = itmDBAccessEJB.getErrorString("","VTREPLQUAN","","",conn);
													return errString;
											}
											//Changed By Pragyan 21-may-14 to get stock quantity.end
											
										}
										
										if(locInvStat.equalsIgnoreCase(invDeepReserve))
										{
											pndLoc = getAvilablePickLocation("N", conn, itemLocType,locZonePref,locCode,itemCode,siteCode,lotNo,lotSl);
											if(pndLoc != null && pndLoc.length() > 0)
			                                {
												//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam.
												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);
										//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam
										pndLocationset.add(pndLoc);
										//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam.start
										pndLocationset.add(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);
								}
								//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam.start
								if(dsoLocationset.size() >= Integer.parseInt(activeReplSplitCnt))
								{
									System.out.println("DSO exceed...");
									isReplHdrDSO = false;
									dsoLocationset.clear();
									//Changed By Pragyan 12/JUN/14 To re assign the line no 
									rplCntDSO = 1;
								}
								if(pndLocationset.size() >= Integer.parseInt(activeReplSplitCnt))
								{
									System.out.println("pnd exceed...");
									isReplHdrPND = false;
									pndLocationset.clear();
									//Changed By Pragyan 12/JUN/14 To re assign the line no 
									rplCntPND = 1;
								}
								if(caspkLocationset.size() >= Integer.parseInt(activeReplSplitCnt))
								{
									System.out.println("caspk exceed....");
									isReplHdr = false;
									caspkLocationset.clear();
									//Changed By Pragyan 12/JUN/14 To re assign the line no 
									replCnt = 1;
								}
								if(psoLocationset.size() >= Integer.parseInt(activeReplSplitCnt))
								{
									System.out.println("pso exceed...");
									isReplHdrPSO = false;
									psoLocationset.clear();
									//Changed By Pragyan 12/JUN/14 To re assign the line no 
									rplCntPSO = 1;
								}
								if(prsvLocationset.size() >= Integer.parseInt(activeReplSplitCnt))
								{
									System.out.println("prsv exceed....");
									isReplHdrRSV = false;
									prsvLocationset.clear();
									//Changed By Pragyan 12/JUN/14 To re assign the line no 
									rplCntRSV = 1;		
								}

								
								//Changed by Rohan on 04-07-13 for split active replanishment task based on configuration of disparam.end
						}
						
						//////////////////////To add Carton no generation for Actives Hear///////////////////////////////////////
						System.out.println("Finally ["+itemWeightTotal+"]Finally itemVolumeTotal["+itemVolumeTotal+"]");
						//Changed for Cold chain by Pragyan on 19-SEP-14   [W14FSUN003]	
						//activeCartonNo =  updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"A-PICK", xtraParams, conn,itemWeightTotal,itemVolumeTotal,pickType,"");
						activeCartonNo =  updateCartonMaster(pickRefId, pickCtr,Double.parseDouble(noArt),ptcn,"A-PICK", xtraParams, conn,itemWeightTotal,itemVolumeTotal,pickType,"",facilityCode,locTypeParent);
						
						actCartonWeightMap.put(activeCartonNo, itemWeightTotal);
						//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
					}
					
					//"Y".equalsIgnoreCase(isADSIConnReq)
					//if(actCartonWeightMap.size() > 0 && ("Y".equalsIgnoreCase(pPickAllow) || "Y".equalsIgnoreCase(mPackAllow)))
					if("Y".equalsIgnoreCase(isADSIConnReq) && actCartonWeightMap.size() > 0 && ("Y".equalsIgnoreCase(pPickAllow) || "Y".equalsIgnoreCase(mPackAllow)))
					{
						CommodityInfo[] infoCom = null;
						String nafFlag = discommon.getDisparams("999999","NAFTA_FLAG_COUNT",conn);
						String sqlQuery = "",sqlSize = "";
						double rateStdOum = 0.0;
						double shipedQty = 0.0;
						double actWeight = 0.0;
						double slength = 0;
						double  width =0;
						double height=0;
						//Cold Chain changed by Pragyan on 19-SEP-14   [W14FSUN003]	
						double tareWt = 0.0;
						double fillerWt = 0.0; 
						PreparedStatement pstmt1 = null, pstmt2 = null;
						ResultSet rs = null,rs2 = null;
						String lotLen=null; 
						String lotWidth=null; 
						String lotHeight  = null; 
						int actPkgSize = actCartonWeightMap.size();
						int existPackageLen = 0;
						Set keySet = actCartonWeightMap.keySet();
						Iterator<String> actIteraotor = keySet.iterator();
						int Ctr = 0;
						
						sqlQuery = "SELECT ITEM_CODE,SUM(QUANTITY) AS QTY FROM PICK_ORD_DET WHERE CARTON_NO = ? GROUP BY ITEM_CODE";
						pstmt1 = conn.prepareStatement(sqlQuery);
						//Changed by Pragyan on 19-SEP-14   [W14FSUN003]	
						//sqlSize = "SELECT LENGTH , WIDTH , HEIGHT FROM PACKING WHERE PACK_CODE = (SELECT PACK_CODE FROM CARTON_MASTER WHERE CARTON_NO = ? )";
						
						sqlSize = " SELECT C.PACK_CODE,C.TARE_WEIGHT,C.FILLER_WEIGHT, P.LENGTH , P.WIDTH , P.HEIGHT " 
								+" FROM CARTON_MASTER C,PACKING P WHERE C.PACK_CODE = P.PACK_CODE AND C.CARTON_NO  = ? ";
						pstmt2 = conn.prepareStatement(sqlSize);
										
					
						System.out.println("actPkgSize"+actPkgSize+"[["+actCartonWeightMap.toString()+"]");
						//packgeList = new Package2[allMasterListlen];
						if(shipment2.getPackages2() != null)
						{
							existPackageLen = shipment2.getPackages2().length;
						}	
						//packgeList = new Package2[n];
						if(existPackageLen > 0)
						{
							System.out.println("Existing packages1["+existPackageLen+"]"+"N length"+actPkgSize);
							
							Package2[] existPack2 = shipment2.getPackages2();
							packgeList = new Package2[actPkgSize + existPackageLen];
							for(int pCtr = 0;pCtr < existPackageLen ;pCtr ++)
							{
								System.out.println("Existing ID["+existPack2[pCtr].getID()+"]pCtr["+pCtr+"]");
								packgeList[pCtr] = existPack2[pCtr];
							}
							
						}
						else
						{
							
							System.out.println("Existing packages2["+existPackageLen+"]"+"N lenght"+actPkgSize);
							packgeList = new Package2[actPkgSize];
						}

						while(actIteraotor.hasNext())
						{
							activeCartonNo = actIteraotor.next();
							
							actWeight = 0.0;
							//actWeight = actCartonWeightMap.get(activeCartonNo);
							NameValuePair[] additionalFields = new NameValuePair[1];
							additionalFields[0] = new NameValuePair("carton_no", activeCartonNo);
							
							pkg2 =  new Package2();
							pkg2.setID(activeCartonNo);
							//pkg2.setWeight(actWeight);
							pstmt2.setString(1, activeCartonNo);
							rs2 = pstmt2.executeQuery();
							
							if(rs2.next())
							{
								slength =rs2.getDouble("LENGTH");																					
								width = rs2.getDouble("WIDTH");
								height =rs2.getDouble("HEIGHT");
								//Cold Chain changed by Pragyan on 19-SEP-14   [W14FSUN003]	
								tareWt  = rs2.getDouble("TARE_WEIGHT");
								fillerWt  = rs2.getDouble("FILLER_WEIGHT");
							}										
							pstmt2.clearParameters();
							
							String strlen = ""+slength;
							String widthStr = ""+width;
							String heightStr = ""+height;
							strlen = Double.toString(slength);
							widthStr=Double.toString(width);
							heightStr = Double.toString(height);
							pkg2.setDimension(slength+"x"+widthStr+"x"+heightStr);	
							System.out.println("Dimension of master package :"+pkg2.getDimension());
							//pkg2.setTrackingNumber("");//Not Required Optional
							pkg2.setDescription("Pharmaceuticals");//As per Taro 
							pkg2.setOversizeFlag(false);//As per Taro 
							pkg2.setDeclaredValueFlag(false);//As per Taro 
							pkg2.setDeclaredValueAmount(0.0);//As per Taro not required
							pkg2.setDeclaredValueCustoms(0.0);//As per Taro not required
							pkg2.setBillOfLadingComment("");//As per Taro not required
							pkg2.setAdditionalHandlingFlag(false);//As per Taro false
							pkg2.setPackaging(EnumPackageType.pkgCUSTOM);//As per Taro default pkgCUSTOM
							pkg2.setCODFlag(false);//As per Taro false
							pkg2.setCODAmount(0.0);//As per Taro not required 
							pkg2.setCODPaymentType(0);//As per Taro not required 
							Address addr = new Address();
							pkg2.setCODReturnAddress(addr);//As per Taro not required 
							pkg2.setAdditionalFields(additionalFields);
							
							pstmt1.setString(1, activeCartonNo);
							rs = pstmt1.executeQuery();
							
							HashMap tempImap = new HashMap();
							
							while(rs.next())
							{																						
								itemCode = rs.getString("ITEM_CODE");
								shipedQty = rs.getDouble("QTY");
								tempImap.put(itemCode, shipedQty);
							}
							
							int tempSize = tempImap.size();
							infoCom = new CommodityInfo[tempSize];
							Iterator itM = tempImap.keySet().iterator();
							int commCtr = 0;
							
							while(itM.hasNext())
							{
								
								itemCode = (String)itM.next();
								shipedQty = (Double)tempImap.get(itemCode);
								itmVolumeMap = getItemVoumeMap(itemCode,"",conn);
								packSizeCase = (Double)itmVolumeMap.get("PACK_SIZE");
								perItemVolume = (Double)itmVolumeMap.get("ITEM_SIZE");
								caseVolume = (Double)itmVolumeMap.get("LOT_SIZE");
								caseWeight = (Double)itmVolumeMap.get("PACK_WEIGHT");
								itemWeight = (Double)itmVolumeMap.get("ITEM_WEIGHT");
								hazardous = (String)itmVolumeMap.get("HAZARDOUS");
								harmonizCode = (String)itmVolumeMap.get("HARMONIZATION_NO");
								harmonizDescr = (String)itmVolumeMap.get("HARMONIZATION_DESCR");
								originCountry = (String)itmVolumeMap.get("ORIGIN_COUNTRY");
								unitValue = getRateStdoum(saleOrder, itemCode, conn);
								System.out.println("shipedQty["+shipedQty+"]");
								actWeight = actWeight + itemWeight * shipedQty;
								
								if("Y".equalsIgnoreCase(hazardous))
								{
									pkg2.setHazmatFlag(true);
								}
								else
								{
									pkg2.setHazmatFlag(false);
								}
								
								comInfo = new CommodityInfo();
								
								comInfo.setDescription(harmonizDescr);//As per taro Harmonization description
								comInfo.setQuantity(shipedQty);
								comInfo.setHarmonizedCode(harmonizCode);//As per Taro Haromonization code
								comInfo.setUnitValue(unitValue);
								comInfo.setUnitWeight(itemWeight);
								originCountry = originCountry!=null?originCountry.trim():"";
								Country originCountryMfg = soap.getCountry("ISO3", originCountry).getResponseCountry();
								comInfo.setOriginCountry(originCountryMfg);
								System.out.println("VALUES IN NAFTA VALUES "+nafFlag);
								
								
								if(nafFlag.indexOf(shipCountry) != -1)
								{
									comInfo.setNaftaFlag(true);
									System.out.println("available in disparm");
								}
								else
								{
									System.out.println("not in disparm");
									comInfo.setNaftaFlag(false);//False as Per Taro Need To change canda/Mexico as true.
								}
								
								Calendar calendar = Calendar.getInstance();
								comInfo.setExportNumberExpireDate(calendar);
								comInfo.setUnitOfMeasure(EnumUnitOfMeasure.uomPCS);
								infoCom[commCtr] = comInfo;
								commCtr++;
							}
							System.out.println("Total Active Weight ["+actWeight+"]");
                             //Changed by Pragyan on 19-SEP-14   [W14FSUN003]	
							System.out.println("ActiveCartonNo["+activeCartonNo+"]act weight["+actWeight+"]tare weight["+tareWt+"]Filler Weight["+fillerWt+"]Total active["+(actWeight+tareWt+fillerWt)+"]");
							pkg2.setWeight(actWeight+tareWt+fillerWt);
							//pkg2.setWeight(actWeight);
							
							
							pkg2.setCommodityInfos(infoCom);
							System.out.println("Ctr"+Ctr+"existPackageLen"+existPackageLen+"]");
							packgeList[Ctr + existPackageLen] = pkg2;	
							Ctr++;
						}
						
						
						if(pstmt1 != null)
						{
							pstmt1.close();
							pstmt1 = null;
						}
						
						if(rs != null)
						{
							rs.close();
							rs = null;
						}
						
						if(pstmt2 != null)
						{
							pstmt2.close();
							pstmt2 = null;
						}
						
						if(rs2 != null)
						{
							rs2.close();
							rs2 = null;
						}
					}
					
					//"Y".equalsIgnoreCase(isADSIConnReq)
					//if(packgeList != null && packgeList.length > 0)
					if("Y".equalsIgnoreCase(isADSIConnReq) && packgeList != null && packgeList.length > 0)
					{
						System.out.println("Setting Packages To Shipment In actives["+packgeList.length +"]");
						shipment2.setPackages2(packgeList);
					}
					
				}
				long endTime16 = System.currentTimeMillis();
				System.out.println("DIFFERANCE IN TIME FOR REPL AND PICK ORDER FOR ACTIVE PICKING IN SECONDS:::["+(endTime16-startTime16)/1000+"]");
				//change by rekha on 23-05-13 start
				//if(packgeList.length != 0  || packgeList.length > 0)
				//if("P".equalsIgnoreCase(waveMode) && packgeList != null && packgeList.length > 0)
				//if(packgeList != null && packgeList.length > 0)
				//{
					/*System.out.println("Setting Packages To Shipment Finally["+packgeList.toString()+"]["+packgeList.length+"]");
					shipment2.setPackages2(packgeList);*/
					/*BASE64Decoder decoder = new BASE64Decoder();
					Timestamp currDate = new Timestamp(System.currentTimeMillis());
					
					//Changed By Pragyan as 11-jul-13 suggested by brian change it to default rotation
					//ShipmentResultReturn2 objReturn2 = soap.shipWithLabel(shipment2, ShipWithLabelType.PNG, ImageRotation.Rotation_180);
					ShipmentResultReturn2 objReturn2 = soap.shipWithLabel(shipment2, ShipWithLabelType.PNG, ImageRotation.Rotation_Default);
		    		System.out.println("Is successfully Executed ["+objReturn2.isSuccess()+"]");
		    		System.out.println("Message String ["+objReturn2.getMessage()+"]");
		    		
		    		if(!objReturn2.isSuccess())
		    		{
		    			errString = getError(saleOrder + "[" + objReturn2.getMessage() +"]", "ADSISRVERR", conn);
		    			return errString;
		    		}
		    		else
		    		{
		    			//Updating ADSI getting the images.start
		    			String serviceSymbol = "";
			   	    	String carrierSymbol = "";
			   	    	String carrierFriendlyName = "";
						ShipmentResult2 objShipResult = objReturn2.getShipmentResultResponse2();
						int  lenPacakges =  objShipResult.getPackageResults2().length;
						String value = "";
						String pckgId = "";
						String trackNo="";
						double msnNo=0.0;
						ResultSet rs = null ;
						
						serviceSymbol = objShipResult.getServiceSymbol();
						System.out.println("serviceSymbol["+serviceSymbol+"]");
						carrierSymbol = serviceSymbol.substring(0,serviceSymbol.lastIndexOf(".") );
			   	    	System.out.println("Carrier Symbol ["+carrierSymbol+"]");
						
						Carrier[] carr = soap.getCarriers().getCarrierList();
		             	for(int j = 0;j<carr.length;j++)
		             	{
		             		Carrier carr1 = carr[j];
		             		System.out.println("Carrier Symbol["+carr1.getSymbol());
		             		System.out.println("Friendly Name["+carr1.getFriendlyName());
		             		System.out.println("Short Name["+carr1.getShortName());
		             		
		             		if(carr1.getSymbol().equalsIgnoreCase(carrierSymbol))
		             		{
		             			carrierFriendlyName = carr1.getFriendlyName();
		             			break;
		             		}
		        

		             	}
		             	System.out.println("Carrier Symbol ["+carrierFriendlyName+"]");
		             	String cnumber = "";
						//imagePath = discommon.getDisparams("999999","SHIP_WITH_PATH",conn);
		             	String addName = "";
		             	String addValue = "";
		             	
						for(int pCtr=0;pCtr < lenPacakges;pCtr++)
						{
							PackageResult2 pkg2frm =  (PackageResult2)objShipResult.getPackageResults2()[pCtr];	
							value = pkg2frm.getBase64Label();
							pckgId = pkg2frm.getPackageID();
							//change by rekha on 23-05-13.start
							pkg2frm.getAdditionalFields();
							trackNo = pkg2frm.getTrackingNumber();			
							cnumber = "";
							for(int Cadd=0;Cadd<pkg2frm.getAdditionalFields().length;Cadd++)
							{
								addName = pkg2frm.getAdditionalFields()[Cadd].getName();
								addValue = pkg2frm.getAdditionalFields()[Cadd].getValue();
								System.out.println("additional fields are Name:"+addName);
								System.out.println("additional fields are Value:"+addValue);
								
								if(addName.equalsIgnoreCase("carton_no"))
								{
									cnumber = addValue;
								}
								
							}
							//change by rekha on 23-05-13. end
							//String cnumber = (String) masterOrParclNoList.get(pCtr);
							
							System.out.println("cnumber is :"+cnumber);
							System.out.println("Package ID["+pckgId+"]");
							System.out.println("Tracking No ["+pkg2frm.getTrackingNumber()+"]");
							System.out.println("BASE64lABEL Length["+value.length()+"]");
							 
							System.out.println("Package id for carton no is :[" +decoder.decodeBuffer(pckgId) +"]");
							msnNo = pkg2frm.getMSN();
							
							System.out.println("MSN NO IN EACH PACKAGE IS :" +msnNo);
							byte[] imgBytes = decoder.decodeBuffer(value);    
							System.out.println("IMAGE Byte Length ["+imgBytes.length+"]");
							BufferedImage bufImg = ImageIO.read(new ByteArrayInputStream(imgBytes));  
							
							File imgOutFile = new File(imagePath+ File.separator+"Ship_Label"+File.separator+ ptcn + File.separator + ptcn+"_"+cnumber +".png");
							
							String path = imgOutFile.getPath();
							System.out.println("Get Path ["+path+"]");
							//path = path.substring(0,path.lastIndexOf(File.separator));
							//System.out.println("after Path ["+path+"]");
							File createFolder = new File(path);
							if(!createFolder.exists())
							{
								createFolder.mkdirs();
							}
							//UPDATE CARTON MASTER TRACKING NO , IMAGENAME PATH,
							
							sql = "UPDATE CARTON_MASTER SET TRACKING_NO = ?  , SHIP_LABEL= ? , MSN_NO =?"
									+ " WHERE CARTON_NO = ?";		
							sql = "UPDATE CARTON_MASTER SET TRACKING_NO = ?  , SHIP_LABEL= ? , MSN_NO =?,CARRIER_SYMBOL = ? , CARRIER_FRIENDLYNAME = ?"
								+ " WHERE CARTON_NO = ?";		
							pstmtCart = conn.prepareStatement(sql);
							pstmtCart.setString(1, trackNo);
							pstmtCart.setString(2, path );
							pstmtCart.setDouble(3, msnNo);
							pstmtCart.setString(4, carrierSymbol);
							pstmtCart.setString(5, carrierFriendlyName);
							pstmtCart.setString(6, cnumber);
							System.out.println("carton number in for loop: "+cnumber);
							System.out.println("msn no for pkg result is :" +msnNo);
							int test = pstmtCart.executeUpdate();
							System.out.println("update statement is :"+test);
							if(test==1)
							{
								System.out.println("updated");
								
							}
							else    
							{
								System.out.println("not updated");
							}
								
							imgOutFile.createNewFile();
							ImageIO.write(bufImg, "png", imgOutFile);
							System.out.println("Write File Complete----");
										
						}
						
						if( pstmt != null )
						{
							pstmt.close();
							pstmt = null;
						}
						OutputStream file = new FileOutputStream(imagePath+ File.separator+"Ship_Label"+File.separator+ ptcn + File.separator + ptcn+"_"+"Ship"+".ser" );
			    	    OutputStream buffer = new BufferedOutputStream( file );
			    	    ObjectOutput output = new ObjectOutputStream( buffer );
			   	        output.writeObject(shipment2);
			   	        output.flush();
			   	        output.close();  
			   	        file = new FileOutputStream( imagePath+ File.separator+"Ship_Label"+File.separator+ ptcn + File.separator + ptcn+"_"+"ShipRslt"+".ser" );
			   	        buffer = new BufferedOutputStream( file );
			    	    output = new ObjectOutputStream( buffer );
			   	        output.writeObject(objReturn2);
			   	        output.flush();
			   	        output.close();  
			   
			   	     if("Y".equalsIgnoreCase(mPackAllow) || "Y".equalsIgnoreCase(pPickAllow))
			   	     {
			   	    	//String windowName="w_wave_stat_org"; 
			   	    	String tranId="";
			   	    	String sqlInsertDt=null;
			   	    	int lineNo = 1;
			   	    	
						
						String cartonNo = "";
						String pickOrder = "";
						String refSer = "";
						String refId = "";
						String cartonType = "";
						String packCode = "";
						String masterCarton = "";
						String itmCode = "";
						String weight = "";
						String trackingNo = ""; 
						String shipLabel = "";
						String lineNoPick = "";
						String new_trackingNo = "";
						String  new_shipLabel = "";
					
			   	    	
			   	    	
						tranId = getTranId("w_wave_stat_org", conn);
						serviceSymbol = objShipResult.getServiceSymbol();
						System.out.println("serviceSymbol["+serviceSymbol+"]");
						carrierSymbol = serviceSymbol.substring(0,serviceSymbol.lastIndexOf(".") );
			   	    	System.out.println("Carrier Symbol ["+carrierSymbol+"]");
			   	    	
			   	    	Carrier[] carr = soap.getCarriers().getCarrierList();
		             	
		             	
		             	for(int j = 0;j<carr.length;j++)
		             	{
		             		Carrier carr1 = carr[j];
		             		System.out.println("Carrier Symbol["+carr1.getSymbol());
		             		System.out.println("Friendly Name["+carr1.getFriendlyName());
		             		System.out.println("Short Name["+carr1.getShortName());
		             		
		             		if(carr1.getSymbol().equalsIgnoreCase(carrierSymbol))
		             		{
		             			carrierFriendlyName = carr1.getFriendlyName();
		             			break;
		             		}
		        

		             	}
			   	    	
		             	
		             	
			   	    	//sqlInsertData = "INSERT INTO WAVE_STATUS_ORG (TRAN_ID, WAVE_ID,TRAN_CODE,PTCN,CHG_USER,CHG_DATE,CHG_TERM,PRINT_STATUS)"+						
						//		" VALUES (?,?,?,?,?,?,?,?)";
		             	sqlInsertData = "INSERT INTO WAVE_STATUS_ORG (TRAN_ID, WAVE_ID,TRAN_CODE,PTCN,CHG_USER,CHG_DATE,CHG_TERM,PRINT_STATUS,CARRIER_SYMBOL,CARRIER_FRIENDLYNAME)"+						
						" VALUES (?,?,?,?,?,?,?,?,?,?)";
			   	    	pstmtInsertData = conn.prepareStatement(sqlInsertData);
			   	    	
			   	    	pstmtInsertData.setString(1,tranId);
			   	    	pstmtInsertData.setString(2,waveID);
						pstmtInsertData.setString(3,tranCode);
						pstmtInsertData.setString(4,ptcn);
						pstmtInsertData.setString(5,chgUser);
						pstmtInsertData.setTimestamp(6,currDate);
						pstmtInsertData.setString(7,chgTerm);
						pstmtInsertData.setString(8,"Y");
						pstmtInsertData.setString(9,carrierSymbol);
						pstmtInsertData.setString(10,carrierFriendlyName);
						//Chnaged by sumit on 03/04/12
						
						
						pstmtInsertData.addBatch();								
						
						sqlInsertDt = "SELECT CARTON_NO,PICK_ORDER,LINE_NO__PICK,CARTON_TYPE,PACK_CODE,MASTER_CARTON,ITEM_CODE,TRACKING_NO,SHIP_LABEL  FROM CARTON_MASTER WHERE PTCN = ?  ORDER BY ITEM_CODE";
						
						sqlInsertData1 = "INSERT INTO WAVE_STATUS_ORG_DET (TRAN_ID, LINE_NO,PTCN,CARTON_NO," +
								" PICK_ORDER,	LINE_NO__PICK	,REF_SER,	REF_ID,	" +
								"	CARTON_TYPE,PACK_CODE,MASTER_CARTON,ITEM_CODE, " +
								"WEIGHT,TRACKING_NO,	SHIP_LABEL	)"+				
								" VALUES (?,?,	?,?,	?,?,	?,?,	?,?,	?,?	,	?,?,	?)";
			   	    	pstmtInsertData1 = conn.prepareStatement(sqlInsertData1);
						
						pstmtDt = conn.prepareStatement(sqlInsertDt);
						
						pstmtDt.setString(1, ptcn);
						rsD = pstmtDt.executeQuery();
						ArrayList test = new ArrayList();
						String tempItem = "";
							while(rsD.next())
							{
																
								//tranId =rsD.getString("TRAN_ID");																					
								//lineNo = rsD.getInt("LINE_NO");
								cartonNo = rsD.getString("CARTON_NO");
								pickOrder = rsD.getString("PICK_ORDER");
								 lineNoPick = rsD.getString("LINE_NO__PICK");
								// refSer = rsD.getString("REF_SER");
								// refId = rsD.getString("REF_ID");
								 cartonType = rsD.getString("CARTON_TYPE");
								 packCode = rsD.getString("PACK_CODE");
								 masterCarton = rsD.getString("MASTER_CARTON");
								 itmCode=rsD.getString("ITEM_CODE");
								 //weight = rsD.getString("WEIGHT");
								new_trackingNo = rsD.getString("TRACKING_NO");
								if(itmCode != null && !tempItem.equalsIgnoreCase(itmCode))
								{
										tempItem = itmCode;
										itmVolumeMap = getItemVoumeMap(itmCode,"",conn);
										caseWeight = (Double)itmVolumeMap.get("PACK_WEIGHT");
										itemWeight = (Double)itmVolumeMap.get("ITEM_WEIGHT");
								}
								 
								 new_shipLabel = rsD.getString("SHIP_LABEL");
								 System.out.println("carton no in while loop :" +cartonNo);
								 System.out.println("tracking no in while loop :"+new_trackingNo);
								 System.out.println("ship_label in while loop :"+new_shipLabel);															 
								 pstmtInsertData1.setString(1,tranId);
								 pstmtInsertData1.setInt(2,lineNo);
								 pstmtInsertData1.setString(3,ptcn);
								 pstmtInsertData1.setString(4,cartonNo);
								 pstmtInsertData1.setString(5,pickOrder);
								 pstmtInsertData1.setString(6,lineNoPick);
								 pstmtInsertData1.setString(7,refSer);
								 pstmtInsertData1.setString(8,refId);
								 pstmtInsertData1.setString(9,cartonType);
								 pstmtInsertData1.setString(10,packCode);
								 pstmtInsertData1.setString(11,masterCarton);
								 pstmtInsertData1.setString(12,itmCode);							
																																
								if(new_trackingNo == null || new_trackingNo.trim().length()==0)
								{
									pstmtInsertData1.setDouble(13,caseWeight);
									pstmtInsertData1.setString(14,"");
									pstmtInsertData1.setString(15,"");
								}
								else
								{
									pstmtInsertData1.setDouble(13,0.0);
									pstmtInsertData1.setString(14,new_trackingNo);
									pstmtInsertData1.setString(15,new_shipLabel);
								}
													
								pstmtInsertData1.addBatch();
								 lineNo++;
								
							}
						
			   	     } 
			   	        
			   		pstmtInsertData.executeBatch();
					pstmtInsertData1.executeBatch();
					pstmtInsertData.clearParameters();
					pstmtInsertData1.clearParameters();
					
					if( pstmtInsertData != null)
					{
						pstmtInsertData.close();
						pstmtInsertData = null;
					}
					
					if( pstmtInsertData1 != null)
					{
						pstmtInsertData1.close();
						pstmtInsertData1 = null;
					} 
			   	        
			   	  // change by rekha on 29-05-13 end
			   	 
		    		}*/
		    		
				//}
				
				//change by rekha on 23-05-13 end
				
				
				//Updating ADSI getting the images.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;
				
				}
				//changed by sankara on 15/07/14 closed prepares stements start.
				if(pstmtIssHdr != null)
				{
					pstmtIssHdr.close();
					pstmtIssHdr = null;		
				}
				if(pstmtIssDet != null)
				{
					pstmtIssDet.close();
					pstmtIssDet = null;		
				}
				if(pstmtPickDet != null)
				{
					pstmtPickDet.close();
					pstmtPickDet = null;		
				}
				//changed by sankara on 15/07/14 closed prepares stements end.			
		}
			
		
		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();
				}
				//changed by sankara on 15/07/14 closed prepares stements start.
				if(pstmtIssHdr != null)
				{
					pstmtIssHdr.close();
					pstmtIssHdr = null;		
				}
				if(pstmtIssDet != null)
				{
					pstmtIssDet.close();
					pstmtIssDet = null;		
				}
				if(pstmtPickDet != null)
				{
					pstmtPickDet.close();
					pstmtPickDet = null;		
				}
				//changed by sankara on 15/07/14 closed prepares stements end.			
			}
			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.
	
	
	private String updateTRackingNo(String saleOrder,String ptcn,String waveID,String tranCode,HashMap sordMap,Connection conn)throws Exception
	{
		
		String errString = "";
		String imagePath = "";
		String tranId="";
	    String sqlInsertDt = null;
	    int lineNo = 1;
		String cartonNo = "";
		String pickOrder = "";
		String refSer = "";
		String refId = "";
		String cartonType = "";
		String packCode = "";
		String masterCarton = "";
		String itmCode = "";
		String weight = "";
		String trackingNo = ""; 
		String shipLabel = "";
		String lineNoPick = "";
		String new_trackingNo = "";
		String  new_shipLabel = "";
		String cnumber = "";
     	String addName = "";
     	String addValue = "";
     	String serviceSymbol = "";
	    String carrierSymbol = "";
	    String carrierFriendlyName = "";
		
		
		String value = "";
		String pckgId = "";
		String trackNo="";
		String frtTerm = "",sSQL = "";
		double msnNo=0.0;
		double itemWeight = 0.0,caseWeight = 0.0;
		double totalFrtAmt = 0.0;
		PreparedStatement pstmt = null;
		PreparedStatement pstmtCart = null;
		PreparedStatement pstmtInsertData = null;
		PreparedStatement pstmtInsertData1 = null;
		PreparedStatement pstmtInsertTran = null;
		PreparedStatement pstmtDt = null;
		PreparedStatement pstmtDesp = null;
		ResultSet rsD = null;
		ResultSet rs = null ;
		
		HashMap itmVolumeMap = null;
		
		try
		{
			
			
			Timestamp currDate = new Timestamp(System.currentTimeMillis());
			tranId = getTranId("w_wave_stat_org", conn);
	       /*	sqlInsertData = "INSERT INTO WAVE_STATUS_ORG (TRAN_ID, WAVE_ID,TRAN_CODE,PTCN,CHG_USER,CHG_DATE,CHG_TERM,PRINT_STATUS,CARRIER_SYMBOL,CARRIER_FRIENDLYNAME)"+						
			" VALUES (?,?,?,?,?,?,?,?,?,?)";*/
			sqlInsertData = "INSERT INTO WAVE_STATUS_ORG (TRAN_ID, WAVE_ID,TRAN_CODE,PTCN,CHG_USER,CHG_DATE,CHG_TERM,PRINT_STATUS,CARRIER_SYMBOL,CARRIER_FRIENDLYNAME,TRAN_CODE__NEW)"+						
					" VALUES (?,?,?,?,?,?,?,?,?,?,?)";
   	    	pstmtInsertData = conn.prepareStatement(sqlInsertData);
   	    	
   	    	pstmtInsertData.setString(1,tranId);
   	    	pstmtInsertData.setString(2,waveID);
			pstmtInsertData.setString(3,tranCode);
			pstmtInsertData.setString(4,ptcn);
			pstmtInsertData.setString(5,chgUser);
			pstmtInsertData.setTimestamp(6,currDate);
			pstmtInsertData.setString(7,chgTerm);
			pstmtInsertData.setString(8,"Y");
			pstmtInsertData.setString(9,carrierSymbol);
			pstmtInsertData.setString(10,carrierFriendlyName);
			pstmtInsertData.setString(11,tranCode);
			//Chnaged by sumit on 03/04/12
			
			
			pstmtInsertData.addBatch();				
			pstmtInsertData.executeBatch();
			
			//"Y".equalsIgnoreCase(isADSIConnReq)
			if("P".equalsIgnoreCase(waveMode))
			{
				imagePath = discommon.getDisparams("999999","SHIP_WITH_PATH",conn);
				BASE64Decoder decoder = new BASE64Decoder();
				//Timestamp currDate = new Timestamp(System.currentTimeMillis());
				ShipmentResultReturn2 objReturn2 = soap.shipWithLabel(shipment2, ShipWithLabelType.PNG, ImageRotation.Rotation_Default);
				ShipmentResult2 objShipResult = objReturn2.getShipmentResultResponse2();
				System.out.println("Is successfully Executed ["+objReturn2.isSuccess()+"]");
	    		System.out.println("Message String ["+objReturn2.getMessage()+"]");
				
	    		
	    		if(!objReturn2.isSuccess())
	    		{
	    			errString = getError(saleOrder + "[" + objReturn2.getMessage() +"]", "ADSISRVERR", conn);
	    			return errString;
	    		}
	    		else
	    		{
	    				frtTerm = (String)sordMap.get("FRT_TERM");
	    				totalFrtAmt = objShipResult.getTotal();
	    				System.out.println("Update in desp update freight Amt totalFrtAmt ["+totalFrtAmt+"] For frtTerm["+frtTerm+"]");
	    				
	    				if("B".equalsIgnoreCase(frtTerm))
	    				{
	    					sSQL = "UPDATE DESPATCH SET FREIGHT_AMT_ADD = ? WHERE PTCN = ?";
	    					pstmtDesp = conn.prepareStatement(sSQL);
	    					pstmtDesp.setDouble(1, totalFrtAmt);
	    					pstmtDesp.setString(2, ptcn);
	    					int pUpd = pstmtDesp.executeUpdate();
	    					
	    					System.out.println("Update in desp update freight Amt upd ["+pUpd+"] For");
	    				}
	    				   				
	    				
	    				System.out.println("Total Amount Of  ["+totalFrtAmt+"]");
	    				int  lenPacakges =  objShipResult.getPackageResults2().length;
						serviceSymbol = objShipResult.getServiceSymbol();
						System.out.println("serviceSymbol["+serviceSymbol+"]");
						carrierSymbol = serviceSymbol.substring(0,serviceSymbol.lastIndexOf(".") );
			   	    	System.out.println("Carrier Symbol ["+carrierSymbol+"]");
						Carrier[] carr = soap.getCarriers().getCarrierList();
						
		             	for(int j = 0;j<carr.length;j++)
		             	{
		             		Carrier carr1 = carr[j];
		             		System.out.println("Carrier Symbol["+carr1.getSymbol());
		             		System.out.println("Friendly Name["+carr1.getFriendlyName());
		             		System.out.println("Short Name["+carr1.getShortName());
		             		
		             		if(carr1.getSymbol().equalsIgnoreCase(carrierSymbol))
		             		{
		             			carrierFriendlyName = carr1.getFriendlyName();
		             			break;
		             		}
		        
	
		             	}
		             	System.out.println("Carrier Symbol ["+carrierFriendlyName+"]");
		             			             	
						for(int pCtr=0;pCtr < lenPacakges;pCtr++)
						{
							PackageResult2 pkg2frm =  (PackageResult2)objShipResult.getPackageResults2()[pCtr];	
							value = pkg2frm.getBase64Label();
							pckgId = pkg2frm.getPackageID();
							//change by rekha on 23-05-13.start
							pkg2frm.getAdditionalFields();
							trackNo = pkg2frm.getTrackingNumber();			
							cnumber = "";
							for(int Cadd=0;Cadd<pkg2frm.getAdditionalFields().length;Cadd++)
							{
								addName = pkg2frm.getAdditionalFields()[Cadd].getName();
								addValue = pkg2frm.getAdditionalFields()[Cadd].getValue();
								System.out.println("additional fields are Name:"+addName);
								System.out.println("additional fields are Value:"+addValue);
								
								if(addName.equalsIgnoreCase("carton_no"))
								{
									cnumber = addValue;
								}
								
							}
							
							
							System.out.println("cnumber is :"+cnumber);
							System.out.println("Package ID["+pckgId+"]");
							System.out.println("Tracking No ["+pkg2frm.getTrackingNumber()+"]");
							System.out.println("BASE64lABEL Length["+value.length()+"]");
							 
							System.out.println("Package id for carton no is :[" +decoder.decodeBuffer(pckgId) +"]");
							msnNo = pkg2frm.getMSN();
							
							System.out.println("MSN NO IN EACH PACKAGE IS :" +msnNo);
							byte[] imgBytes = decoder.decodeBuffer(value);    
							System.out.println("IMAGE Byte Length ["+imgBytes.length+"]");
							BufferedImage bufImg = ImageIO.read(new ByteArrayInputStream(imgBytes));  
							
							File imgOutFile = new File(imagePath+ File.separator+"Ship_Label"+File.separator+ ptcn + File.separator + ptcn+"_"+cnumber +".png");
							String path = imgOutFile.getPath();
							System.out.println("Get Path ["+path+"]");
							File createFolder = new File(path);
							
							if(!createFolder.exists())
							{
								createFolder.mkdirs();
							}
			
							sql = "UPDATE CARTON_MASTER SET TRACKING_NO = ?  , SHIP_LABEL= ? , MSN_NO =?,CARRIER_SYMBOL = ? , CARRIER_FRIENDLYNAME = ?"
								+ " WHERE CARTON_NO = ?";		
							pstmtCart = conn.prepareStatement(sql);
							pstmtCart.setString(1, trackNo);
							pstmtCart.setString(2, path );
							pstmtCart.setDouble(3, msnNo);
							pstmtCart.setString(4, carrierSymbol);
							pstmtCart.setString(5, carrierFriendlyName);
							pstmtCart.setString(6, cnumber);
							System.out.println("carton number in for loop: "+cnumber);
							System.out.println("msn no for pkg result is :" +msnNo);
							int test = pstmtCart.executeUpdate();
							System.out.println("update statement is :"+test);
							if(test==1)
							{
								System.out.println("updated");
								
							}
							else    
							{
								System.out.println("not updated");
							}
								
							imgOutFile.createNewFile();
							ImageIO.write(bufImg, "png", imgOutFile);
							System.out.println("Write File Complete----");
										
						}
						
						if( pstmt != null )
						{
							pstmt.close();
							pstmt = null;
						}
						OutputStream file = new FileOutputStream(imagePath+ File.separator+"Ship_Label"+File.separator+ ptcn + File.separator + ptcn+"_"+"Ship"+".ser" );
			    	    OutputStream buffer = new BufferedOutputStream( file );
			    	    ObjectOutput output = new ObjectOutputStream( buffer );
			   	        output.writeObject(shipment2);
			   	        output.flush();
			   	        output.close();  
			   	        file = new FileOutputStream( imagePath+ File.separator+"Ship_Label"+File.separator+ ptcn + File.separator + ptcn+"_"+"ShipRslt"+".ser" );
			   	        buffer = new BufferedOutputStream( file );
			    	    output = new ObjectOutputStream( buffer );
			   	        output.writeObject(objReturn2);
			   	        output.flush();
			   	        output.close();  
			   
			   	     
			   	    	//String windowName="w_wave_stat_org"; 
			   	    	
						/*tranId = getTranId("w_wave_stat_org", conn);
				       	sqlInsertData = "INSERT INTO WAVE_STATUS_ORG (TRAN_ID, WAVE_ID,TRAN_CODE,PTCN,CHG_USER,CHG_DATE,CHG_TERM,PRINT_STATUS,CARRIER_SYMBOL,CARRIER_FRIENDLYNAME)"+						
						" VALUES (?,?,?,?,?,?,?,?,?,?)";
			   	    	pstmtInsertData = conn.prepareStatement(sqlInsertData);
			   	    	
			   	    	pstmtInsertData.setString(1,tranId);
			   	    	pstmtInsertData.setString(2,waveID);
						pstmtInsertData.setString(3,tranCode);
						pstmtInsertData.setString(4,ptcn);
						pstmtInsertData.setString(5,chgUser);
						pstmtInsertData.setTimestamp(6,currDate);
						pstmtInsertData.setString(7,chgTerm);
						pstmtInsertData.setString(8,"Y");
						pstmtInsertData.setString(9,carrierSymbol);
						pstmtInsertData.setString(10,carrierFriendlyName);
						//Chnaged by sumit on 03/04/12
						
						
						pstmtInsertData.addBatch();				*/				
						
						sqlInsertDt = "SELECT CARTON_NO,PICK_ORDER,LINE_NO__PICK,CARTON_TYPE,PACK_CODE,MASTER_CARTON,ITEM_CODE,TRACKING_NO,SHIP_LABEL  FROM CARTON_MASTER WHERE PTCN = ?  ORDER BY ITEM_CODE";
						
						sqlInsertData1 = "INSERT INTO WAVE_STATUS_ORG_DET (TRAN_ID, LINE_NO,PTCN,CARTON_NO," +
								" PICK_ORDER,	LINE_NO__PICK	,REF_SER,	REF_ID,	" +
								"	CARTON_TYPE,PACK_CODE,MASTER_CARTON,ITEM_CODE, " +
								"WEIGHT,TRACKING_NO,	SHIP_LABEL	)"+				
								" VALUES (?,?,	?,?,	?,?,	?,?,	?,?,	?,?	,	?,?,	?)";
			   	    	pstmtInsertData1 = conn.prepareStatement(sqlInsertData1);
						
						pstmtDt = conn.prepareStatement(sqlInsertDt);
						
						pstmtDt.setString(1, ptcn);
						rsD = pstmtDt.executeQuery();
						ArrayList test = new ArrayList();
						String tempItem = "";
						while(rsD.next())
						{
																
			
								cartonNo = rsD.getString("CARTON_NO");
								pickOrder = rsD.getString("PICK_ORDER");
								lineNoPick = rsD.getString("LINE_NO__PICK");
								cartonType = rsD.getString("CARTON_TYPE");
								packCode = rsD.getString("PACK_CODE");
								masterCarton = rsD.getString("MASTER_CARTON");
								itmCode = rsD.getString("ITEM_CODE");
								new_trackingNo = rsD.getString("TRACKING_NO");
								
								if(itmCode != null && !tempItem.equalsIgnoreCase(itmCode))
								{
										tempItem = itmCode;
										itmVolumeMap = getItemVoumeMap(itmCode,"",conn);
										caseWeight = (Double)itmVolumeMap.get("PACK_WEIGHT");
										itemWeight = (Double)itmVolumeMap.get("ITEM_WEIGHT");
								}
								 
								 new_shipLabel = rsD.getString("SHIP_LABEL");
								 System.out.println("carton no in while loop :" +cartonNo);
								 System.out.println("tracking no in while loop :"+new_trackingNo);
								 System.out.println("ship_label in while loop :"+new_shipLabel);															 
								 pstmtInsertData1.setString(1,tranId);
								 pstmtInsertData1.setInt(2,lineNo);
								 pstmtInsertData1.setString(3,ptcn);
								 pstmtInsertData1.setString(4,cartonNo);
								 pstmtInsertData1.setString(5,pickOrder);
								 pstmtInsertData1.setString(6,lineNoPick);
								 pstmtInsertData1.setString(7,refSer);
								 pstmtInsertData1.setString(8,refId);
								 pstmtInsertData1.setString(9,cartonType);
								 pstmtInsertData1.setString(10,packCode);
								 pstmtInsertData1.setString(11,masterCarton);
								 pstmtInsertData1.setString(12,itmCode);							
																																
								if(new_trackingNo == null || new_trackingNo.trim().length()==0)
								{
									pstmtInsertData1.setDouble(13,caseWeight);
									pstmtInsertData1.setString(14,"");
									pstmtInsertData1.setString(15,"");
								}
								else
								{
									pstmtInsertData1.setDouble(13,0.0);
									pstmtInsertData1.setString(14,new_trackingNo);
									pstmtInsertData1.setString(15,new_shipLabel);
								}
													
								pstmtInsertData1.addBatch();
								 lineNo++;
								
						}
						
			   	
			   	        
			   		//pstmtInsertData.executeBatch();
					pstmtInsertData1.executeBatch();
					pstmtInsertData.clearParameters();
					pstmtInsertData1.clearParameters();
					
					/*if( pstmtInsertData != null)
					{
						pstmtInsertData.close();
						pstmtInsertData = null;
					}*/
					
					if( pstmtInsertData1 != null)
					{
						pstmtInsertData1.close();
						pstmtInsertData1 = null;
					} 
	    		}
			}
			if( pstmtInsertData != null)
			{
				pstmtInsertData.close();
				pstmtInsertData = null;
			}
		
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		finally
		{
			try
			{
				if( pstmtInsertData != null)
				{
					pstmtInsertData.close();
					pstmtInsertData = null;
				}
				
				if( pstmtInsertData1 != null)
				{
					pstmtInsertData1.close();
					pstmtInsertData1 = null;
				} 
			}
			catch(Exception e)
			{
				e.printStackTrace();
				throw e;
			}
			
		}
		
		return errString;
	}
	
	
	
	
	
	
	//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 Pragyan for Cold Chain on 19-SEP-14   [W14FSUN003]	
	//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
	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,String facilityCode,String locTypeParent)throws Exception
	{
		String errString = "";		
		String sql = "",sqlInsert = "";
		//Changed by Pragyan on 19-SEP-14   [W14FSUN003]	
		//PreparedStatement pstmt = null,pstmtInsert = null,pstmtPacking = null;
		PreparedStatement pstmt = null,pstmtInsert = null,pstmtPacking = null,pstmtPackingFacility = null,pstmtPackingFiller = null;
		//ResultSet rs = null;
		ResultSet rs = null,rsFacility = null, rsFiller = null;
		String chgUser="",chgTerm="",windowName="",keyString="",tranIDCol="",refSer="";
		String xmlString="",tranIDSer="";
		int updCnt[] = null;
		String crtnType = "";
		double volumeItem=0.0;
		double weightItem=0.0;
		double tareWeight = 0.0; //add on 19-SEP-14 (Pragyan)   [W14FSUN003]	
		double fillerWeight = 0.0;//add on 19-SEP-14 (Pragyan)   [W14FSUN003]	
		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);
			
			
		    //Start Changed by Pragyan on 19-SEP-14	   [W14FSUN003]	
			sql =  "SELECT PACK_CODE,GROSS_WEIGHT,LENGTH*WIDTH*HEIGHT,TARE_WEIGHT "
				 	+" FROM PACKING_FACILITY WHERE " 
				 	+" FACILITY_CODE = ? AND LENGTH*WIDTH*HEIGHT> = ? and "
				 	+" GROSS_WEIGHT = ( SELECT MIN(GROSS_WEIGHT) " 
				 	+" FROM PACKING_FACILITY WHERE " 
				 	+" FACILITY_CODE = ? AND LENGTH*WIDTH*HEIGHT = (SELECT MIN(LENGTH*WIDTH*HEIGHT) "
				 	+" VOLUME FROM PACKING_FACILITY WHERE " 
				 	+" FACILITY_CODE = ? AND 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.setString(1, facilityCode);
			pstmtPacking.setDouble(2, volume);
			pstmtPacking.setString(3, facilityCode);
			pstmtPacking.setString(4, facilityCode);
			pstmtPacking.setDouble(5, weight);
			pstmtPacking.setDouble(6, volume);
			pstmtPacking.setString(7, packType);
			pstmtPacking.setString(8, packType);
			pstmtPacking.setString(9, packType);
			
			rs = pstmtPacking.executeQuery();
			
			if(rs.next())
			{
				packCode = rs.getString(1);
				weightItem = rs.getDouble(2);
				volumeItem = rs.getDouble(3);
				tareWeight = rs.getDouble(4);
			}
			else
			{
				
					if(pstmtPacking != null)
					{
						pstmtPacking.close();
						pstmtPacking =null;
					}
					
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
				
				
					//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,TARE_WEIGHT,TARE_WEIGHT "+
				 	"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);
						tareWeight = rs.getDouble(4);
					}
					
					System.out.println("packCode="+packCode);
					System.out.println("weightItem="+weightItem);
					System.out.println("volumeItem="+volumeItem);
			    //End Changed by Pragyan on 19-SEP-14   [W14FSUN003]		 		
						
			}
			
			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 (?,?,?,?,?,?,?,?,?,?,?,?) ";*/
			//Changed by Pragyan on 19-SEP-14   [W14FSUN003]	
			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 (?,?,?,?,?,?,?,?,?,?,?,?,?) ";
			+"PICK_ORDER, LINE_NO__PICK ,PTCN,REF_SER,CARTON_TYPE,PACK_CODE,MASTER_CARTON,ITEM_CODE,TARE_WEIGHT,FILLER_WEIGHT) " 
			+" 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);
				//Changed by Pragyan on 19-SEP-14   [W14FSUN003]	
				if(packCode != null && packCode.length() > 0)
				{
					fillerWeight = getFillerWeight(packCode,locTypeParent,tareWeight,volumeItem,conn);
					if((refSeries.startsWith("M-PACK")))
					{
						updatePacketWeigfhts(pickOrder,packCode,tareWeight,fillerWeight,weight,cartonNumber,conn);
					}
				
				}
				
				if((refSeries.startsWith("M-PACK")))
				{
					pstmtInsert.setString(12,cartonNumber);
				}
				else
				{
					pstmtInsert.setString(12,"");
				}
				
				pstmtInsert.setString(13,itemCode);  
				pstmtInsert.setDouble(14,tareWeight);     //Add on  19-SEP-14   [W14FSUN003]		
				pstmtInsert.setDouble(15,fillerWeight);   //Add on  19-SEP-14   [W14FSUN003]	 
				
				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 Pragyan To add PTCN 09-OCT-13 
	//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
	private String updateShipment(Document headerDom, Document detailDom,String waveID,String PTCN,String saleOrder,String refId,String tranCode,String transMode,String xtraParams,HashMap sordMap,  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
			//changed by sankara on 11/10/13 for getting licence_no and licence_date start.
			String licenceNo = "";
			java.sql.Date lincenceDate = null;
			String licenceNo2 = "";
			java.sql.Date lincenceDate2 = null;
			//changed by sankara on 11/10/13 for getting licence_no and licence_date end.			
			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 "
						+"(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				
				*/
				
				//changed by sankara on 11/10/13 for getting licence_no and licence_date start.
				//Changed By Pragyan pass the map once
				//HashMap sordMap = getSordInfo(saleOrder,conn);
				licenceNo = (String)sordMap.get("DRUG_LIC_NO_1");
				System.out.println("licenceNo:"+licenceNo);
				lincenceDate =(java.sql.Date)sordMap.get("DRUG_LICNO1_UPTO");
				System.out.println("lincenceDate:"+lincenceDate);
				licenceNo2 = (String)sordMap.get("DRUG_LIC_NO_2");
				lincenceDate2 =(java.sql.Date)sordMap.get("DRUG_LICNO2_UPTO");
				//changed by sankara on 11/10/13 for getting licence_no and licence_date end.
				
				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(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";*/
						//changed by sankara on 11/10/13 for insert licence_no and licence_date start.
						/*+ " CURR_CODE__FRT, EXCH_RATE__FRT, FREIGHT, CURR_CODE__INS, EXCH_RATE__INS, INSURANCE, CURR_CODE,GP_NO,PTCN )"
						+ " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";*/
						+ " CURR_CODE__FRT, EXCH_RATE__FRT, FREIGHT, CURR_CODE__INS, EXCH_RATE__INS, INSURANCE, CURR_CODE,GP_NO,PTCN,LICENCE_NO_1,LICENCE_DATE_1, " 
						+ " LICENCE_NO_2, LICENCE_DATE_2 )"
						+ " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? ) ";
				       //changed by sankara on 11/10/13 for insert licence_no and licence_date end.
				//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);
				System.out.println("PTCN "+PTCN);
				
				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");
				pstmt.setString(34,PTCN);
				//changed by sankara on 11/10/13 for insert licence_no_1, and licence_date_1,licence_no_2,licence_date_2 start.
				pstmt.setString(35,licenceNo);
				pstmt.setDate(36,lincenceDate);
				pstmt.setString(37,licenceNo2);
				pstmt.setDate(38,lincenceDate2);
				//changed by sankara on 11/10/13 for insert licence_no_1, and licence_date_1,licence_no_2,licence_date_2 end.
				//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 Dhanraj on 19-SEP-14  [W14FSUN003]	
	private String updatedespatch(String ptcn,Connection conn) throws Exception
	{  
		String errString = "";		
		String sql=null;
		double tareWt=0.0;
		double fillerWt=0.0;
		System.out.println("Call Despatch update method");
		PreparedStatement pstmt = null;
		ResultSet rSet = null ;
		try
		{
			sql = " SELECT SUM(NVL(FILLER_WEIGHT,0)) FILLER_WEIGHT , SUM(NVL(TARE_WEIGHT,0)) TARE_WEIGHT  FROM CARTON_MASTER "
				+" WHERE PTCN = ? AND (CARTON_TYPE = ? OR CARTON_TYPE = ? ) ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,ptcn);
			pstmt.setString(2,"M");
			pstmt.setString(3,"A");
			
			rSet = pstmt.executeQuery();
			
			if (rSet.next())
			{
				fillerWt = rSet.getDouble("FILLER_WEIGHT");
				tareWt = rSet.getDouble("TARE_WEIGHT");
			}
			System.out.println("Sum fillerWt"+fillerWt);
			System.out.println("sum tare wate "+tareWt);
			
			if( rSet != null)
			{
				rSet.close();
				rSet = null;
			}
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			
			sql = " UPDATE DESPATCH SET TARE_WEIGHT= ? ,FILLER_WEIGHT= ? WHERE PTCN= ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setDouble(1, tareWt);
			pstmt.setDouble(2, fillerWt);
			pstmt.setString(3, ptcn);
			int updateCnt=pstmt.executeUpdate();
		    
			if(updateCnt > 0){
				System.out.println("<============Updation done==========>");
			}
			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 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 +		"<order_date>" + currDateStr + "</order_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 = "";
		//Changed By Rekha To add columns required for ADSI
		String harmonizCode = "",harmonizDescr = "",originCountry = "";
		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 Rekha To add columns required for ADSI
			//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, "
			sql = "SELECT I.LENGTH ITEM_LEN,I.WIDTH ITEM_WID,I.HEIGHT ITEM_HEIGHT,I.GROSS_WEIGHT ITEM_WEIGHT,I.HAZARDOUS HAZARD, " 
				  +" I.HARMONIZATION_NO HARMONIZATION_NO,I.HARMONIZATION_DESCR HARMONIZATION_DESCR,I.COUNT_CODE__MFG ORIGIN_COUNTRY,"
				  +" 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
			{
				//Changed By Pragyan 05-DEC-13 as per KB sir in case of blank lot no take the data for max of lot_no__to.start
				/*pstmt.setString(1, "00");
				pstmt.setString(2, "ZZ");*/
				return dataVolumeMap = getItemVoumeMap(itemCode, con);
				//Changed By Pragyan 05-DEC-13 as per KB sir in case of blank lot no take the data for max of lot_no__to.end
			}
			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");
				harmonizCode = rs.getString("HARMONIZATION_NO");
				harmonizDescr = rs.getString("HARMONIZATION_DESCR");
				originCountry = rs.getString("ORIGIN_COUNTRY");
			}
			
			//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);
			dataVolumeMap.put("HARMONIZATION_NO", harmonizCode);
			dataVolumeMap.put("HARMONIZATION_DESCR", harmonizDescr);
			dataVolumeMap.put("ORIGIN_COUNTRY", originCountry);
			dataVolumeMap.put("ITEM_LEN", itmLen);
			dataVolumeMap.put("ITEM_WID", itmWidth);
			dataVolumeMap.put("ITEM_HEIGHT", itmHeight);
			dataVolumeMap.put("LITEM_LEN", lotLen);
			dataVolumeMap.put("LITEM_WID", lotWidth);
			dataVolumeMap.put("LITEM_HEIGHT", lotHeight);
		
			
			
			
			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;
	}
	
	//Changed By Pragyan 05-DEC-13 as per KB sir thr may be chance to have more then on lot no in item lot pack size.strat
	private HashMap getItemVoumeMap(String itemCode,Connection con)throws Exception
	{
		double packSize = 0,itemSize = 0,lotSize = 0;
		PreparedStatement pstmt = null;
		String sql="",hazardous = "";
		String harmonizCode = "",harmonizDescr = "",originCountry = "";
		ResultSet rs = null;
		double itmLen = 0,itmWidth = 0,itmHeight = 0,itemWeight = 0,lotLen = 0 ,lotHeight = 0,lotWidth = 0,lotWeight = 0;
		HashMap dataVolumeMap = new HashMap();
		
				System.out.println("As Lot No Passed as Blank Calling Override method for getItemVoumeMap");
		try {
			
			sql = "SELECT I.LENGTH ITEM_LEN,I.WIDTH ITEM_WID,I.HEIGHT ITEM_HEIGHT,I.GROSS_WEIGHT ITEM_WEIGHT,I.HAZARDOUS HAZARD, " 
				  +" I.HARMONIZATION_NO HARMONIZATION_NO,I.HARMONIZATION_DESCR HARMONIZATION_DESCR,I.COUNT_CODE__MFG ORIGIN_COUNTRY,"
				  +" 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__TO IN (SELECT MAX(LOT_NO__TO) FROM ITEM_LOT_PACKSIZE WHERE ITEM_CODE = ?)"
				  +" AND  I.ITEM_CODE = ?";
				  
			
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			pstmt.setString(2, 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");
				harmonizCode = rs.getString("HARMONIZATION_NO");
				harmonizDescr = rs.getString("HARMONIZATION_DESCR");
				originCountry = rs.getString("ORIGIN_COUNTRY");
			}
			itemSize = itmLen * itmWidth * itmHeight;
			lotSize = lotHeight * lotWidth * lotLen;
			
			dataVolumeMap.put("PACK_SIZE", packSize);
			dataVolumeMap.put("ITEM_SIZE", itemSize);
			dataVolumeMap.put("LOT_SIZE", lotSize);
			dataVolumeMap.put("HAZARDOUS", hazardous);
			dataVolumeMap.put("ITEM_WEIGHT", itemWeight);
			dataVolumeMap.put("PACK_WEIGHT", lotWeight);
			dataVolumeMap.put("HARMONIZATION_NO", harmonizCode);
			dataVolumeMap.put("HARMONIZATION_DESCR", harmonizDescr);
			dataVolumeMap.put("ORIGIN_COUNTRY", originCountry);
			dataVolumeMap.put("ITEM_LEN", itmLen);
			dataVolumeMap.put("ITEM_WID", itmWidth);
			dataVolumeMap.put("ITEM_HEIGHT", itmHeight);
			dataVolumeMap.put("LITEM_LEN", lotLen);
			dataVolumeMap.put("LITEM_WID", lotWidth);
			dataVolumeMap.put("LITEM_HEIGHT", lotHeight);
		
			
			
			
			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;
	}
	//Changed By Pragyan 05-DEC-13 as per KB sir thr may be chance to have more then on lot no in item lot pack size.end
	
	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
	{
		long startTime17 = System.currentTimeMillis();
		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;
				
				//Changed By Pragyan 11-AUG-14 To check and Facility Master implementation.start
				if(!commonWmsUtility.isValFacLocation(suggLocCode, siteCode, conn))
				{
					//Changed by Dhanraj on 13-AUG-14 In suggLocCode var store last location 
					suggLocCode="";
					continue;
				}
				//Changed By Pragyan 11-AUG-14 To check and Facility Master implementation.end
				
				/*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+"]");
	  long endTime17 = System.currentTimeMillis();
	  System.out.println("DIFFERANCE IN TIME FOR getAvilablePickLocation IN SECONDS:::["+(endTime17-startTime17)/1000+"]");
	 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
	{
		long startTime18 = System.currentTimeMillis();
		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;
				
				//Changed By Pragyan 11-AUG-14 To check and Facility Master implementation.start
				if(!commonWmsUtility.isValFacLocation(suggLocCode, siteCode, conn))
				{
					//Changed by Dhanraj on 13-AUG-14 In suggLocCode var store last location 
					suggLocCode="";
					continue;
				}
				//Changed By Pragyan 11-AUG-14 To check and Facility Master implementation.end
				
				
				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+"]");
	  long endTime18 = System.currentTimeMillis();
	  System.out.println("DIFFERANCE IN TIME FOR getAvilableCasePickLocation IN SECONDS:::["+(endTime18-startTime18)/1000+"]");
	 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
	//Changed by shankara on 13-06-13 for bug fixing.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 To Check Site Transporter on 19-SEP-14   [W14FSUN003]	
	//private HashMap getTransporterInfoMap(String saleOrder,double perShipWeight ,double noArt,String pickType , String shipType ,Connection conn) throws ITMException
	//chnaged by pragyan on 15/10/14 for cold chain
	//private HashMap getTransporterInfoMap(String saleOrder,double perShipWeight ,double noArt,String pickType , String shipType ,Connection conn) throws ITMException
	private HashMap getTransporterInfoMap(String saleOrder,double perShipWeight ,double noArt,String pickType , String shipType ,String locTypeParent ,Connection conn) throws ITMException
	{
		HashMap distRouteDataMap = null;
		String tranCode = "";
		//STORAGE_CONDN
		try
		{
		    //chnaged by pragyan on 15/10/14 for cold chain
			//distRouteDataMap = getTransporterInfoMap(saleOrder,perShipWeight ,noArt,pickType , shipType ,true, conn);
			distRouteDataMap = getTransporterInfoMap(saleOrder,perShipWeight ,noArt,pickType , shipType ,true,locTypeParent, conn);
			
			if(distRouteDataMap != null)
			{
				tranCode = (String)distRouteDataMap.get("TRAN_CODE");
				
				if(!(tranCode.length() > 0))				
				{
					//distRouteDataMap = getTransporterInfoMap(saleOrder,perShipWeight ,noArt,pickType , shipType ,false, conn);
					distRouteDataMap = getTransporterInfoMap(saleOrder,perShipWeight ,noArt,pickType , shipType ,true,"", conn);
				}
			}
			
			if(distRouteDataMap != null)
			{
				tranCode = (String)distRouteDataMap.get("TRAN_CODE");
				
				if(!(tranCode.length() > 0))				
				{
				    //chnaged by pragyan on 15/10/14 for cold chain
					//distRouteDataMap = getTransporterInfoMap(saleOrder,perShipWeight ,noArt,pickType , shipType ,false, conn);
					distRouteDataMap = getTransporterInfoMap(saleOrder,perShipWeight ,noArt,pickType , shipType ,false,locTypeParent, conn);
				}
				
				if(distRouteDataMap != null)
				{
					tranCode = (String)distRouteDataMap.get("TRAN_CODE");
					
					if(!(tranCode.length() > 0))				
					{
						//distRouteDataMap = getTransporterInfoMap(saleOrder,perShipWeight ,noArt,pickType , shipType ,false, conn);
						distRouteDataMap = getTransporterInfoMap(saleOrder,perShipWeight ,noArt,pickType , shipType ,false,"", conn);
					}
				}
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception in  == >"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{

			}
			catch (Exception e1)
			{
				throw new ITMException(e1);
			}
		}

		return distRouteDataMap;	
	}
	//chnaged by pragyan on 15/10/14 for cold chain
	private HashMap getTransporterInfoMap(String saleOrder,double perShipWeight ,double noArt,String pickType , String shipType ,boolean isSiteTransporter,String locTypeParent,Connection conn) throws ITMException
	//private HashMap getTransporterInfoMap(String saleOrder,double perShipWeight ,double noArt,String pickType , String shipType ,boolean isSiteTransporter,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 = "";
		String serviceCode = "";
		String shipmentType = "";
		//Changed By Pragyan 23-DEC-13 To check ADSI Connection is required.(KB/Ashish mail Dt.121413) 
		String adsiFlag = "";
		String sSQL = "";
		//chnaged by pragyan on 15/10/14 for cold chain
		boolean isStorageCondExist = false;
		
		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 sankara on 16/10/14 for dlv_pin
			//pinTo = (String)stationInfoMap.get("DLV_PIN");
			pinTo = (String)sordMap.get("DLV_PIN");
			//Changed by pragyan on 19-SEP-14  [W14FSUN003]	
			if(isSiteTransporter)
			{
				sSQL =  " SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE,A.SHIP_TYPE,T.TRAN_CODE AS TRAN_CODE,T.SERVICE_CODE AS SERVICE_CODE,T.SHIPMENT_TYPE AS SHIPMENT_TYPE,ADSI_FLAG AS ADSI_FLAG FROM DISTROUTEDET A,DISTROUTE B, SITE_TRANSPORTER T "  
						  + " WHERE T.SITE_CODE = '"+siteCodeShip+"' AND ( 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 (T.TRAN_CODE = A.TRAN_CODE) AND ";
				       //chnaged by pragyan on 15/10/14 for cold chain 
						if(locTypeParent != null && locTypeParent.trim().length() > 0)
						{
							sSQL = sSQL + "  A.STORAGE_CONDN = '"+locTypeParent+"' AND ";
							isStorageCondExist = true;
						}
						
			}
			else
			{
				sSQL =  " SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE,A.SHIP_TYPE,T.TRAN_CODE AS TRAN_CODE,T.SERVICE_CODE AS SERVICE_CODE,T.SHIPMENT_TYPE AS SHIPMENT_TYPE,ADSI_FLAG AS ADSI_FLAG FROM DISTROUTEDET A,DISTROUTE B, TRANSPORTER T "  
						  + " 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 (T.TRAN_CODE = A.TRAN_CODE) AND ";
				//chnaged by pragyan on 15/10/14 for cold chain
				if(locTypeParent != null && locTypeParent.trim().length() > 0)
				{
					sSQL = sSQL + "  A.STORAGE_CONDN = '"+locTypeParent+"' AND ";
					isStorageCondExist = true;
				}
				
			}
			
			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,T.TRAN_CODE AS TRAN_CODE,T.SERVICE_CODE AS SERVICE_CODE,T.SHIPMENT_TYPE AS SHIPMENT_TYPE FROM DISTROUTEDET A,DISTROUTE B, TRANSPORTER T "  
					  + " 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 ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' )  AND (A.DIST_ROUTE = B.DIST_ROUTE) AND (B.CUST_CODE = ?) AND ( SHIP_TYPE = ?) AND T.TRAN_CODE = A.TRAN_CODE " ;*/
				sql =  sSQL + " (B.CUST_CODE = ?) 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,T.TRAN_CODE AS TRAN_CODE,T.SERVICE_CODE AS SERVICE_CODE,T.SHIPMENT_TYPE AS SHIPMENT_TYPE FROM DISTROUTEDET A,DISTROUTE B , TRANSPORTER T"
					  + " 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 = ?";
					 +	" AND MIN_WEIGHT <= ? AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ?  AND SHIP_TYPE = ? AND T.TRAN_CODE = A.TRAN_CODE ";
					 */
				sql =  sSQL + " 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,T.SERVICE_CODE AS SERVICE_CODE , T.TRAN_CODE AS TRAN_CODE,T.SERVICE_CODE AS SERVICE_CODE,T.SHIPMENT_TYPE AS SHIPMENT_TYPE FROM DISTROUTEDET A,DISTROUTE B ,   TRANSPORTER T"
					  + " 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')";
					  +	" AND MIN_WEIGHT <= ? AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE NOT IN ('M','P') AND T.TRAN_CODE = A.TRAN_CODE";
					//AND ( SERVICE_CODE=? )";
					// + " AND ( A.TRAN_CODE= T.TRAN_CODE )";
				 */				
				
				sql =  sSQL + "  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.setString(8, serviceCode);
			/*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);
				//pstmt.setString(13,"");
			}
			
			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"));
				serviceCode = rs.getString("SERVICE_CODE");
				shipmentType = rs.getString("SHIPMENT_TYPE");
				//Changed By Pragyan 23-DEC-13 To check ADSI Connection is required.(KB/Ashish mail Dt.121413) 
				adsiFlag = rs.getString("ADSI_FLAG");
			}
			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,T.TRAN_CODE AS TRAN_CODE , T.SERVICE_CODE AS SERVICE_CODE,T.SHIPMENT_TYPE AS SHIPMENT_TYPE FROM DISTROUTEDET A,DISTROUTE B,TRANSPORTER T "
					  + " 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 <= ? "
					  //Changed By Pragyan 16JUL13 To pass the customer code is null
					 // +	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE= ? ";
				     // +	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE= ? AND T.TRAN_CODE = A.TRAN_CODE  ";
					  +	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE= ? AND T.TRAN_CODE = A.TRAN_CODE AND B.CUST_CODE IS NULL ";
				*/
				sql = sSQL + " MIN_WEIGHT <= ?  AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE= ? AND B.CUST_CODE IS NULL ";
				
				
				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"));
					serviceCode= rs.getString("SERVICE_CODE");
					shipmentType = rs.getString("SHIPMENT_TYPE");
					//Changed By Pragyan 23-DEC-13 To check ADSI Connection is required.(KB/Ashish mail Dt.121413) 
					adsiFlag = rs.getString("ADSI_FLAG");
					
				}
				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,T.TRAN_CODE AS TRAN_CODE , T.SERVICE_CODE AS SERVICE_CODE,T.SHIPMENT_TYPE AS SHIPMENT_TYPE FROM DISTROUTEDET A,DISTROUTE B ,TRANSPORTER T"
						  + " 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 = ?  "
						  //Changed By Pragyan 16JUL13 To pass the customer code is null
						 // +	" AND MIN_WEIGHT <= ? AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE NOT IN ('M','P')";
						 // +	" AND MIN_WEIGHT <= ? AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE NOT IN ('M','P') AND T.TRAN_CODE = A.TRAN_CODE ";
						  +	" AND MIN_WEIGHT <= ? AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE NOT IN ('M','P') AND T.TRAN_CODE = A.TRAN_CODE";
					*/
					sql =  sSQL + " 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"));
						// CHANGE BY REKHA ON 27-05-13 ADD SERVICE_CODE START
						serviceCode= rs.getString("SERVICE_CODE");
						// CHANGE BY REKHA ON 27-05-13 ADD SERVICE_CODE END
						shipmentType = rs.getString("SHIPMENT_TYPE");
						//Changed By Pragyan 23-DEC-13 To check ADSI Connection is required.(KB/Ashish mail Dt.121413) 
						adsiFlag = rs.getString("ADSI_FLAG");
					}
					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,T.TRAN_CODE AS TRAN_CODE , T.SERVICE_CODE AS SERVICE_CODE,T.SHIPMENT_TYPE AS SHIPMENT_TYPE FROM DISTROUTEDET A,DISTROUTE B,TRANSPORTER T "
							  + " 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 <= ? "
							  //Changed By Pragyan 16JUL13 To pass the customer code is null
							 // +	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE NOT IN ('M','P')";
							  //+	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE NOT IN ('M','P') AND T.TRAN_CODE = A.TRAN_CODE ";
							  +	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE NOT IN ('M','P') AND T.TRAN_CODE = A.TRAN_CODE AND B.CUST_CODE IS NULL ";
						*/
						sql = sSQL + " MIN_WEIGHT <= ? AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE NOT IN ('M','P') AND T.TRAN_CODE = A.TRAN_CODE AND B.CUST_CODE IS NULL ";
						
						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"));
							// CHANGE BY REKHA ON 27-05-13 ADD SERVICE_CODE START
							serviceCode=rs.getString("SERVICE_CODE");
							// CHANGE BY REKHA ON 27-05-13 ADD SERVICE_CODE END
							shipmentType = rs.getString("SHIPMENT_TYPE");
							//Changed By Pragyan 23-DEC-13 To check ADSI Connection is required.(KB/Ashish mail Dt.121413) 
							adsiFlag = rs.getString("ADSI_FLAG");
						}
						
						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 , T.TRAN_CODE AS TRAN_CODE , T.SERVICE_CODE AS SERVICE_CODE,T.SHIPMENT_TYPE AS SHIPMENT_TYPE FROM DISTROUTEDET A,DISTROUTE B , TRANSPORTER T"
							  + " 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  = ' ') "
							  //Changed By Pragyan 16JUL13 To pass the customer code is null
							 // + " AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' ) AND A.DIST_ROUTE = B.DIST_ROUTE AND SHIP_TYPE = ?";
							//  + " AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' ) AND A.DIST_ROUTE = B.DIST_ROUTE AND SHIP_TYPE = ? AND T.TRAN_CODE = A.TRAN_CODE ";
							  + " AND ( A.STATE_CODE__TO = ?  OR  A.STATE_CODE__TO = ' ' ) AND A.DIST_ROUTE = B.DIST_ROUTE AND SHIP_TYPE = ? AND T.TRAN_CODE = A.TRAN_CODE AND B.CUST_CODE IS NULL";
					*/
					sql =  sSQL + " SHIP_TYPE = ? AND  B.CUST_CODE IS NULL";
				}
				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, T.TRAN_CODE AS TRAN_CODE , T.SERVICE_CODE AS SERVICE_CODE,T.SHIPMENT_TYPE AS SHIPMENT_TYPE FROM DISTROUTEDET A,DISTROUTE B ,TRANSPORTER T"
						  + " 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 <= ? "
						 //Changed By Pragyan 16JUL13 To pass the customer code is null
						 // +	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE = ? ";
						 // +	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE = ? AND T.TRAN_CODE = A.TRAN_CODE ";
						  +	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE = ? AND T.TRAN_CODE = A.TRAN_CODE AND B.CUST_CODE IS NULL";
					*/
					sql =  sSQL + "  MIN_WEIGHT <= ? AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE = ? AND B.CUST_CODE IS NULL";
				}
				else
				{
					/*	sql =  " SELECT A.TRAN_CODE AS TRAN_CODE,A.TRANS_MODE AS TRANS_MODE,A.MAX_WEIGHT,A.LOC_TYPE,A.SHIP_TYPE,T.TRAN_CODE AS TRAN_CODE , T.SERVICE_CODE AS SERVICE_CODE,T.SHIPMENT_TYPE AS SHIPMENT_TYPE FROM DISTROUTEDET A,DISTROUTE B ,TRANSPORTER T"
						  + " 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 <= ? "
						//Changed By Pragyan 16JUL13 To pass the customer code is null
						  //+	" 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')";
						//  +	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE NOT IN ('M','P') AND T.TRAN_CODE = A.TRAN_CODE ";
							+	" AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE NOT IN ('M','P') AND T.TRAN_CODE = A.TRAN_CODE AND B.CUST_CODE IS NULL";
						*/
					sql =  sSQL + " MIN_WEIGHT <= ?  AND MAX_WEIGHT >= ? AND MIN_CASE <= ? AND MAX_CASE >= ? AND SHIP_TYPE NOT IN ('M','P')  AND B.CUST_CODE IS NULL";
				}
				
				
				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"));
					// CHANGE BY REKHA ON 27-05-13 ADD SERVICE_CODE START
					serviceCode=rs.getString("SERVICE_CODE");
					// CHANGE BY REKHA ON 27-05-13 ADD SERVICE_CODE END
					shipmentType = rs.getString("SHIPMENT_TYPE");
					//Changed By Pragyan 23-DEC-13 To check ADSI Connection is required.(KB/Ashish mail Dt.121413) 
					adsiFlag = rs.getString("ADSI_FLAG");
				}
				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);
			transInfoMap.put("SERVICE_CODE", serviceCode);
			transInfoMap.put("PIN", pinTo);
			transInfoMap.put("SHIPMENT_TYPE",shipmentType);
			//Changed By Pragyan 23-DEC-13 To check ADSI Connection is required.(KB/Ashish mail Dt.121413) 
			transInfoMap.put("ADSI_FLAG",adsiFlag);
			//Changed Prgayna 14/08/14 for is direct transporter code start.
			transInfoMap.put("IS_DIRECT_TRANSPORTER","N");
			//chnaged by pragyan on 15/10/14 for cold chain
			if(isStorageCondExist)
			{
				transInfoMap.put("IS_STORAGE_CONDN","Y");
			}
			else
			{
				transInfoMap.put("IS_STORAGE_CONDN","N");
			}
			
			transInfoMap.putAll(sordMap);
			
			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
	//Changed by shankara on 13-06-13 for bug fixing.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 = ""
		//Changed By Rekha to get additional fields for ADSI
		,custName="",custShName = "",shipCity="",shipCountry = "",shipAdd1 = "",shipAdd2 = "",shipAdd3 = "",
		shipPh="",shipFax ="",shipMailId = "",custPord = "",dlvPin = "", frtTerm = "";
		//changed by sankara on 11/10/13 for getting drug_lic_no_1 and drug_licno1_upto start.
		String licenceNo = "";
	    java.sql.Date lincenceUpto = null;
	    String licenceNo2 = "";
	    java.sql.Date lincenceUpto2 = null;
		//changed by sankara on 11/10/13 for getting drug_lic_no_1 and drug_licno1_upto end.
		try
		{
									
			//Change By Rekha To get the required rcpnt value from customer
			//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 = ? ";*/
			/*sql = "SELECT C.CUST_CODE AS CUST_CODE," 
				+" C.STAN_CODE AS STAN_CODE," 
				+" S.SITE_CODE__SHIP AS SHIP_CODE," 
				+" S.CUST_PORD AS CUST_PORD," 
				+" C.STATE_CODE AS STATE_DLV," 
				+" C.SHIP_CONS_GRP AS  SHIP_CONS_GRP," 
				+" C.CUST_NAME AS  CUST_NAME,"
				+" C.SH_NAME AS  SH_NAME,"
				+" C.ADDR1 AS  ADDR1,"
				+" C.ADDR2 AS  ADDR2,"
				+" C.ADDR3 AS  ADDR3,"
				+" C.CITY AS  CITY,"
				+" C.COUNT_CODE AS  COUNT_CODE,"
				+" C.TELE1 AS  PHONE,"
				+" C.FAX AS  FAX,"
				+" C.EMAIL_ADDR AS  EMAIL_ID"
				+" FROM SORDER S,CUSTOMER C "
				+ " WHERE S.CUST_CODE__DLV = C.CUST_CODE "
				+ " AND S.SALE_ORDER = ? ";*/
			
			sql = " SELECT S.CUST_CODE__DLV AS CUST_CODE,"
				+" S.STAN_CODE AS STAN_CODE,"
				+" S.SITE_CODE__SHIP AS SHIP_CODE,"
				+" S.CUST_PORD AS CUST_PORD,"
				+" S.STATE_CODE__DLV AS STATE_DLV,"
				+" C.SHIP_CONS_GRP AS  SHIP_CONS_GRP,"
				+" S.DLV_TO AS  CUST_NAME,"
				+" C.SH_NAME AS  SH_NAME,"
				+" S.DLV_ADD1 AS  ADDR1,"
				+" S.DLV_ADD2 AS  ADDR2,"
				+" S.DLV_ADD3 AS  ADDR3,"
				+" S.DLV_CITY AS  CITY,"
				+" S.COUNT_CODE__DLV AS  COUNT_CODE,"
				+" S.TEL1__DLV AS  PHONE,"
				+" S.FAX__DLV AS  FAX,"
				+" C.EMAIL_ADDR AS  EMAIL_ID,"
				//changed by sankara on 11/10/13 for getting drug_lic_no_1 and drug_licno1_upto start.
				+" C.DRUG_LIC_NO_1 AS  DRUG_LIC_NO_1,"
				+" C.DRUG_LICNO1_UPTO AS  DRUG_LICNO1_UPTO, "
				//changed by sankara on 11/10/13 for getting drug_lic_no_1 and drug_licno1_upto end.
				+" S.DLV_PIN AS  DLV_PIN, "
				//changed by Pragyan on 23/12/13 for getting FRT TERM.
				+" S.FRT_TERM AS  FRT_TERM"
				+" 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");
				custName = rs.getString("CUST_NAME");
				custShName = rs.getString("SH_NAME");
				shipCity = rs.getString("CITY");
				shipAdd1 = rs.getString("ADDR1");
				shipAdd2 = rs.getString("ADDR2");
				shipAdd3 = rs.getString("ADDR3");
				shipCountry = rs.getString("COUNT_CODE");
				shipPh = rs.getString("PHONE");
				shipMailId = rs.getString("EMAIL_ID");
				shipFax = rs.getString("FAX");
				custPord = rs.getString("CUST_PORD");
				dlvPin =  rs.getString("DLV_PIN");
				//changed by sankara on 11/10/13 for getting drug_lic_no_1 and drug_licno1_upto start.
				licenceNo =  rs.getString("DRUG_LIC_NO_1");
				lincenceUpto =  rs.getDate("DRUG_LICNO1_UPTO");
				//changed by sankara on 11/10/13 for getting drug_lic_no_1 and drug_licno1_upto end.
				frtTerm =  rs.getString("FRT_TERM");
			}
			//changed by sankara on 14/10/13 for getting drug_lic_no_1 and drug_licno1_upto start.
			if( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}

			sql = " SELECT S.CUST_CODE__DLV AS CUST_CODE,"
					+" S.STAN_CODE AS STAN_CODE,"
					+" S.SITE_CODE__SHIP AS SHIP_CODE,"
					+" S.CUST_PORD AS CUST_PORD,"
					+" S.STATE_CODE__DLV AS STATE_DLV,"
					+" C.SHIP_CONS_GRP AS  SHIP_CONS_GRP,"
					+" S.DLV_TO AS  CUST_NAME,"
					+" C.SH_NAME AS  SH_NAME,"
					+" S.DLV_ADD1 AS  ADDR1,"
					+" S.DLV_ADD2 AS  ADDR2,"
					+" S.DLV_ADD3 AS  ADDR3,"
					+" S.DLV_CITY AS  CITY,"
					+" S.COUNT_CODE__DLV AS  COUNT_CODE,"
					+" S.TEL1__DLV AS  PHONE,"
					+" S.FAX__DLV AS  FAX,"
					+" C.EMAIL_ADDR AS  EMAIL_ID,"
					+" C.DRUG_LIC_NO_1 AS  DRUG_LIC_NO_2,"
					+" C.DRUG_LICNO1_UPTO AS  DRUG_LICNO2_UPTO, "
					+" S.DLV_PIN AS  DLV_PIN"
					+" FROM SORDER S,CUSTOMER C"
					+" WHERE S.CUST_CODE__BIL = C.CUST_CODE "
					+" AND S.SALE_ORDER = ? ";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,saleOrder);
			rs = pstmt.executeQuery();

			if(rs.next())
			{				
				licenceNo2 =  rs.getString("DRUG_LIC_NO_2");
				lincenceUpto2 =  rs.getDate("DRUG_LICNO2_UPTO");
			}
			//changed by sankara on 11/10/13 for getting drug_lic_no_1 and drug_licno1_upto end.
			
			sordInfoMap.put("CUST_CODE", custCode);
			sordInfoMap.put("STAN_CODE", stanCode);
			sordInfoMap.put("SHIP_CODE", siteCodeShip);
			sordInfoMap.put("STATE_DLV", stateCodeDlv);
			sordInfoMap.put("CUST_NAME", custName);
			sordInfoMap.put("SH_NAME", custShName);
			sordInfoMap.put("CITY", shipCity);
			sordInfoMap.put("ADDR1", shipAdd1);
			sordInfoMap.put("ADDR2", shipAdd2);
			sordInfoMap.put("ADDR3", shipAdd3);
			sordInfoMap.put("COUNT_CODE", shipCountry);
			sordInfoMap.put("PHONE", shipPh);
			sordInfoMap.put("EMAIL_ID", shipMailId);
			sordInfoMap.put("FAX", shipFax);
			sordInfoMap.put("CUST_PORD", custPord);
			sordInfoMap.put("DLV_PIN", dlvPin);
			//changed by sankara on 11/10/13 for getting drug_lic_no_1 and drug_licno1_upto start.
			sordInfoMap.put("DRUG_LIC_NO_1", licenceNo);
			sordInfoMap.put("DRUG_LICNO1_UPTO", lincenceUpto);
			sordInfoMap.put("DRUG_LIC_NO_2", licenceNo2);
			sordInfoMap.put("DRUG_LICNO2_UPTO", lincenceUpto2);
			//changed by sankara on 11/10/13 for getting drug_lic_no_1 and drug_licno1_upto end.
			
			if(shipConsGrp != null && shipConsGrp.length() > 0 )
			{
				sordInfoMap.put("SHIP_CONS_GRP", shipConsGrp);
			}
			else
			{
				sordInfoMap.put("SHIP_CONS_GRP", custCode);
			}
			sordInfoMap.put("CUST_PORD", custPord);
			sordInfoMap.put("FRT_TERM", frtTerm);
			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,String siteCodeShip,Connection conn) throws ITMException
	private String getDocLoc(String tranCode,String siteCodeShip,Connection conn) throws ITMException
	{
		String sql = "";
		String sqlShipStanCode = "";
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		String docLoc = "";
				
		try
		{
										
			//Changed By Site Transporter on 22/09/14 start.

			/*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");
			}*/


			sql = "SELECT A.LOC_CODE__DOCK AS DOC_LOC FROM SITE_TRANSPORTER A "
					+ " WHERE A.TRAN_CODE = ? AND SITE_CODE = ? ";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranCode);
			pstmt.setString(2, siteCodeShip);
			rs = pstmt.executeQuery();

			if(rs.next())
			{
				docLoc  = rs.getString("DOC_LOC");
			}
			//Changed By Site Transporter on 22/09/14 end.
			else
			{
				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();

				if(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
		{
			//Changed by Pragyan to check 29/11/14 To proper checking sorder count
			//sql = "SELECT MAX(LINE_NO) AS MAX FROM SORDITEM WHERE SALE_ORDER = ? " ;
			sql = "SELECT COUNT(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	
							    {
							    	
							    	//Changed By Pragyan to get the replenisghment for actual avilable quantity.start
							    	/*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);
							    	}*/
							    	returnString="Y:"+String.valueOf(stockQuantity);
							    	//Changed By Pragyan to get the replenisghment for actual avilable quantity.end
							    	//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;
		//Changed By Pragyan 24-feb-14 ^^^^^
		double replQty = 0.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,"
							//Changed By Pragyan 24-feb-14 ^^^^^
	        				+ " 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.LINE_NO__PICK,S.QUANTITY AS STK_QTY,REPL_QTY AS REPL_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");
					//^^^^^
					//replQty =  rsReplHistory.getDouble("REPL_QTY");
					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);
							//^^^^^^^
							//tempHisMap.put("REPL_QTY",replQty);
							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
						{
							//changed by sankara on 24/06/14 for report calling from remote
							//changed by sankara on 22/07/14 not reuired as per pragyan sir start.
							/*if(isRemotePrintRptSrvCofigur)
							{
								errString = jrGenerator.callRemotePrintServlet(reportObjName, xsdString, chgUser, printer.trim(), 1, conn);
							}
							else
							{
								errString = jrGenerator.printReport(reportObjName, xsdString, chgUser, printer.trim(), 1, conn);
							}*/
							 errString = jrGenerator.callRemotePrintServlet(reportObjName, xsdString, chgUser, printer.trim(), 1, conn);
							//changed by sankara on 22/07/14 not reuired as per pragyan sir end.
							//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;
		double holdQty = 0.0;
		
		double sordAllocQty = 0.0;
		double activeReplQty = 0.0;
		double finalQty = 0.0;
		double totalCaseQty = 0.0,totalPickQty = 0.0,stkActReplQty = 0.0;
		
		try
		{
			sql= "SELECT SUM(QUANTITY) AS QUANTITY,SUM(ALLOC_QTY) AS ALLOC_QTY,SUM((CASE WHEN STOCK.HOLD_QTY IS NULL THEN 0 ELSE STOCK.HOLD_QTY END)) AS HOLD_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");
				holdQty = rs.getDouble("HOLD_QTY");
			}
			
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			
			System.out.println("For deduction ["+qtyAllocate+"]");
			System.out.println("quantity["+quantity+"]allocQty["+allocQty+"]holdQty["+holdQty+"]");
			/*System.out.println("For Result ["+(quantity - (allocQty - qtyAllocate))+"]");
			stockQty = quantity - (allocQty - qtyAllocate);
			System.out.println("For stockQty ["+stockQty+"]");
			stockQty = stockQty - holdQty;*/
			
			sql= "SELECT SUM(QTY_ALLOC) as QTY_ALLOC FROM SORDALLOC 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())
			{
				sordAllocQty = rs.getDouble("QTY_ALLOC");
			}
			
			System.out.println("sordAllocQty["+sordAllocQty+"]");
			finalQty = quantity - (allocQty - sordAllocQty);
			System.out.println("finalQty["+finalQty+"]");
			
			if(rs != null)
			{
				rs.close();
				rs = null;
			}
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			
			sql = "SELECT SUM(D.QUANTITY) AS QUANTITY FROM REPL_ORD_DET D, REPL_ORD_HDR H WHERE D.ITEM_CODE = ? " 
					+" AND D.SITE_CODE = ? AND D.LOC_CODE = ? AND D.LOT_NO = ? AND D.LOT_SL = ? "
    				+" 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 IN('Q','T','P','E','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);
			
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				activeReplQty = rs.getDouble("QUANTITY");
			}
			
			System.out.println("activeReplQty["+activeReplQty+"]");
			finalQty = finalQty - activeReplQty;
			System.out.println("finalQty after activeReplQty["+finalQty+"]");
			
			HashMap tempMap = (HashMap)itemQtyMapForActiveRepl.get(itemCode+":"+siteCode+":"+lotNo+":"+lotSl+":"+locCode);
			if(tempMap != null && tempMap.size() > 0)
			{
				totalCaseQty = (Double)tempMap.get("ACTIVE_REPL_QTY");
				totalPickQty = (Double)tempMap.get("REPL_PICK_QTY");
				stkActReplQty= (Double)tempMap.get("REPL_STK_QTY"); 
				
				System.out.println("Found totalCaseQty["+totalCaseQty+"]totalPickQty["+totalPickQty+"]stkActReplQty["+stkActReplQty+"]");
			}
			finalQty = finalQty - totalCaseQty;
			System.out.println("finalQty after Map ReplQty["+finalQty+"]");
			
			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 e2)
			{
				throw new ITMException(e2);
			}
		
		}
	return finalQty;  	
	}
	//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,pstmtSord = null;
		ResultSet rs2 = null, rs3 = null, rs1 = null,rsSord = null;
		String refSer = "";
		String refId = "";
		String tempOrder = "";
		String saleOrder = "";
		String sql1 = "",sSQLUpdatSord = "";
		String errString = "";
		int update = 0;
		int updateSorder = 0;
		
		try
		{
			
			
			sSQLUpdatSord = "UPDATE SORDER SET SHIP_STATUS = ? WHERE SALE_ORDER = ?";
			pstmtSord = conn.prepareStatement(sSQLUpdatSord);
			
			//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 replConfirmedSet = 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();
									replConfirmedSet.add("true");
								}
								else
								{
									replConfirmedSet.add("false");
								}
							}					
							if( pstmt1 != null)
							{
								pstmt1.close();
								pstmt1 = null;
							}
							if( rs1 != null)
							{
								rs1.close();
								rs1 = null;
							}
						}	
						else
						{
							//update = pstmt3.executeUpdate();
							replConfirmedSet.add("true");
						}
					}
					System.out.println(" isReplConfirmed "+replConfirmedSet);
					//if(replConfirmedSet.size() <=0 ||  !replConfirmedSet.contains("false"))
					if(!replConfirmedSet.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;
				}
				
				
				//Changed By Pragyan WM3DSUN015 To update status in Sorder as InProcess after .start
				pstmtSord.setString(1, "P");
				pstmtSord.setString(2, saleOrder);
				updateSorder = pstmtSord.executeUpdate();
				
				if(updateSorder > 0)
				{
					System.out.println(" SORDER UPDATE COUNT ["+updateSorder+"]");
				}
				pstmtSord.clearParameters();
				//Changed By Pragyan WM3DSUN015 To update status in Sorder as InProcess after .end
			}
			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.	
			
			if( pstmtSord!= null)
			{
				pstmtSord.close();
				pstmtSord = null;
			}
		}
		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
	{
		long startTime19 = System.currentTimeMillis();
		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
		{
			
				System.out.println("getActiveCaseReplMap ReplType["+replType+"]locInvstat["+locInvstat+"]locCode["+locCode+"]lotNo["+lotNo+"]lotSl["+lotSl+"]");

				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 if(replType == "X")
				{
					
						
					//Changed By Pragyan 24-APR-14 AS CASE PICK REPLENISHMENT IS PRESENT THEN IT SHOULD CHECK FOR CASE TO ACTIVE REPLENISHMENT
					
					if(locInvstat.equalsIgnoreCase(deepStoreInvstat) || locInvstat.equalsIgnoreCase(reserveInvstat))
					{
						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 = ? "
									+" 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'";
					}
					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 = ? "
							 //+" 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";
								+" 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 != "" && replType != "X")
			{
				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);
			}
		
		}
		long endTime19 = System.currentTimeMillis();
		System.out.println("DIFFERANCE IN TIME FOR getActiveCaseReplMap IN SECONDS:::["+(endTime19-startTime19)/1000+"]");
	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;  	
	}
	//Changed By Pragyan for Cold Chain on 19-SEP-14   [W14FSUN003]	
	//private String getPackItemVolumeWeight(double weight,double volume, String packType,Connection conn)throws Exception
	private String getPackItemVolumeWeight(double weight,double volume, String packType,String facilityCode ,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
		{
			
		//Start Changed by Pragyan on 19-SEP-14	   [W14FSUN003]	
			if(facilityCode != null && facilityCode.trim().length() > 0)
			{

				
				sql= "SELECT GROSS_WEIGHT,LENGTH*WIDTH*HEIGHT AS VOLUME "
			 		+" FROM PACKING_FACILITY WHERE " 
			 		+" FACILITY_CODE = ? AND LENGTH*WIDTH*HEIGHT >=?  AND "
			 		+" GROSS_WEIGHT= ( SELECT MIN(GROSS_WEIGHT) " 
			 		+" FROM PACKING_FACILITY WHERE " 
			 		+" FACILITY_CODE = ? AND LENGTH*WIDTH*HEIGHT =(SELECT MIN(LENGTH*WIDTH*HEIGHT) "
			 		+" VOLUME FROM PACKING_FACILITY WHERE " 
			 		+" FACILITY_CODE = ? AND 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_FACILITY WHERE FACILITY_CODE = ? AND PACK_TYPE IN( ?,'B') AND ( LENGTH*WIDTH*HEIGHT) > 0   AND GROSS_WEIGHT > 0 "
						+" ORDER BY LENGTH*WIDTH*HEIGHT DESC";
				
				pstmt = conn.prepareStatement(sql);
				
				pstmt.setString(1, facilityCode);
				pstmt.setDouble(2, volume);
				pstmt.setString(3, facilityCode);
				pstmt.setString(4, facilityCode);
				pstmt.setDouble(5, weight);
				pstmt.setDouble(6, volume);
				pstmt.setString(7, packType);
				pstmt.setString(8, packType);
				pstmt.setString(9, 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, facilityCode);
					pstmt1.setString(2, 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;
				}
			}
			
			
			if(volumeItem == 0.0 && weightItem == 0.0)
			{
					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;
					}
			}
		   //End Changed by Pragyan on 19-SEP-14   [W14FSUN003]		
		}
		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
	{
		
		
		
		//Changed By Pragyan 15-MAR-14 not to update repl type blank.start
		System.out.println("CURRENT REPL TYPE AND QUANTITY FOR UPDATING updateReplOrdDet()["+replType+"reqQuantity["+reqQuantity+"]");
		if(replType != null && replType.length() > 0)
		{
			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 LINE_NO = ?" ;
			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));
		}
		else
		{
			sql= "UPDATE REPL_ORD_DET SET ACTUAL_QTY = ? WHERE ITEM_CODE = ?" +
				 " AND LOC_CODE = ? AND SITE_CODE = ? AND LOT_NO = ? AND LOT_SL = ? AND REPL_ORDER = ? AND LINE_NO = ?" ;
			pstmt =  conn.prepareStatement(sql);
			pstmt.setDouble(1, reqQuantity);
			pstmt.setString(2, itemCode);
			pstmt.setString(3, locCode);
			pstmt.setString(4, siteCode);
			pstmt.setString(5, lotNo);
			pstmt.setString(6, lotSl);
			pstmt.setString(7, replOrder);
			pstmt.setInt(8, 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);
			//changed by sankara on 22/07/14 not required as per pragyan sir start.
			/*if(isRemotePrintRptSrvCofigur)
			{
			 errString = jrGenerator.callRemotePrintServlet(reportObjName, xsdString, chgUser, printer.trim(), 1, conn);
			}
			else
			{
				errString = jrGenerator.printReport(reportObjName, xsdString, chgUser, printer.trim(), 1, conn);
			}*/
			errString = jrGenerator.callRemotePrintServlet(reportObjName, xsdString, chgUser, printer.trim(), 1, conn);
			//changed by sankara on 22/07/14 not reuired as per pragyan sir end.
			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 double getRateStdoum(String saleOrder,String itemCode,Connection conn) throws ITMException
{
	 String sql = "";
	 double rateStdOum = 0.0;
	 PreparedStatement pstmt = null;
	 ResultSet rs = null;
	 
	 try
	 {
		 
		 sql =   " SELECT RATE__STDUOM FROM SORDDET WHERE  SALE_ORDER = ? AND ITEM_CODE = ?";
				 
		 pstmt = conn.prepareStatement(sql);
		 pstmt.setString(1, saleOrder);
		 pstmt.setString(2, itemCode);
		 
		 
		 rs = pstmt.executeQuery();
		 if( rs.next())
		 {
			 rateStdOum = rs.getDouble(1);
			
		 }
		 rs.close(); rs = null;
		 pstmt.close(); pstmt = null;	 
		 
	 }
	 catch(Exception ex)
	 {
		 ex.printStackTrace();
		 throw new ITMException(ex);
	 }
	 return rateStdOum;
 }
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+"] ");
		 //Changes by Dadaso pawar on 11/02/15 [Start] For direct pick location pallet No. Should be updated for each case.
		// sql =   "UPDATE CARTON_MASTER SET PALLET_NO = ? WHERE PTCN = ? AND CARTON_TYPE IN ('A','M')";
		  sql =   "UPDATE CARTON_MASTER SET PALLET_NO = ? WHERE PTCN = ? AND CARTON_TYPE IN ('A','C')";
		  //Changes by Dadaso pawar on 11/02/15 [End] For direct pick location pallet No. Should be updated for each case.
		 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
//changed by sankara on 21/08/13 for bug fixing start..
private String printExceptionMessage( String Code, Connection conn, String errString)  throws ITMException 
{
	String mainStr = "";  
	String errMessage = "";  
	String endDesc = "";

	try
	{
		System.out.println("ERRSTRINGSANKARA====="+errString);
		errMessage =  new ITMDBAccessEJB().getErrorString("",Code,"","",conn);
		String begPart = errMessage.substring(0,errMessage.indexOf("<message>")+9);
		System.out.println("BEGPART===="+begPart);
		//String endDesc = errMessage.substring(errMessage.indexOf("</description>"));
		if(errString != null && errString.indexOf("<description>") != -1 && (errString.indexOf("</description>") + 14) != -1)
		{
			endDesc = errString.substring(errString.indexOf("<description>"),errString.indexOf("</description>")+14);
		}
		else
		{
			//endDesc = errMessage.substring(errMessage.indexOf("</description>"));
			return errMessage;
		}
		System.out.println("ENDDESC====="+endDesc);
	//	String message = errString.substring(107,185);
		mainStr= begPart+"Exception Data"+"</message>";
		mainStr= mainStr + "Exception"+endDesc+"</error>"+"</Errors>"+"</Root>";
		System.out.println("printExceptionMessage:::::::::::::::::: "+mainStr);
		begPart = null;
	}
	catch(Exception e)
	{
		e.printStackTrace();
		throw new ITMException(e);
	}
	return mainStr;
}
//changed by sankara on 21/08/13 for bug fixing end..
//changed by sankara on 24/09/13 for update status in sorddet start.
public void updateBackOrderStatus (String salesOrder, Connection conn) throws ITMException     
{

	String sql = "";
	String soreItemsql = "";
	String updatesql = "";
	String pendingOrder = "";
	String LineNo = "";
	int upddateStatus = 0;
	int orderQuantity = 0;
	int allocQuantity = 0;
	PreparedStatement pstmt = null,pstmtupdate = null;
	ResultSet rs = null, rs1 = null;

	try
	{
		 //changed by sankara on 27/09/13 quantity_stduom as ordered quantity
		//sql = " SELECT S.PENDING_ORDER, SI.LINE_NO, SI.QTY_ORD, SI.QTY_ALLOC FROM SORDER S, SORDITEM SI WHERE S.SALE_ORDER = SI.SALE_ORDER AND S.SALE_ORDER = ? ";
		  sql = " SELECT S.PENDING_ORDER, SI.LINE_NO, SD.QUANTITY__STDUOM, SI.QTY_ALLOC FROM SORDER S, SORDITEM SI, SORDDET SD " +
		        " WHERE S.SALE_ORDER = SI.SALE_ORDER AND SD.SALE_ORDER = S.SALE_ORDER AND SD.SALE_ORDER = SI.SALE_ORDER " +
		        " AND SD.LINE_NO = SI.LINE_NO AND S.SALE_ORDER = ? ";
		//Changed by Dhanraj on 27JUN14  to over come open cursor issue
		updatesql = " UPDATE SORDDET SET HOLD_FLAG = 'Y' WHERE SALE_ORDER = ? AND LINE_NO = ? ";
		pstmtupdate = conn.prepareStatement(updatesql);
		  
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, salesOrder);
		rs = pstmt.executeQuery();
		while( rs.next())
		{
			pendingOrder = rs.getString(1);
			LineNo = rs.getString(2);
			orderQuantity = rs.getInt(3);
			allocQuantity = rs.getInt(4);
			System.out.println("pendingOrder"+pendingOrder);
			System.out.println("LineNo:"+LineNo);
			
			if( pendingOrder.trim().equalsIgnoreCase("H") && ( allocQuantity < orderQuantity ) )
			{
				//Changed by Dhanraj on 27JUN14  to over come open cursor issue
				/*updatesql = " UPDATE SORDDET SET HOLD_FLAG = 'Y' WHERE SALE_ORDER = ? AND LINE_NO = ? ";
				pstmtupdate = conn.prepareStatement(updatesql);*/
				pstmtupdate.setString(1, salesOrder);
				pstmtupdate.setString(2, LineNo);
				upddateStatus =  pstmtupdate.executeUpdate();
				if( upddateStatus > 0 )
				{
					System.out.println("Updateing in sorddet  ["+upddateStatus+"] For Sale Order["+salesOrder+"]LineNo["+LineNo+"]");
				}
				pstmtupdate.clearParameters();
			}
			
		}
	}
	catch(Exception ex)
	{
		ex.printStackTrace();
		throw new ITMException(ex);
	}
	finally
	{
		try
		{
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if(pstmtupdate != null)
			{
				pstmtupdate.close();
				pstmtupdate = null;
			}	
			if( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( rs1 != null )
			{
				rs1.close();
				rs1 = null;
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			throw new ITMException(ex);
		}
	}
}
//changed by sankara on 24/09/13 for update status in sorddet end.

//changed by Pragyan on 28/FEB/14 for update repl qty in stock.start
public void updateStkReplQty(String locCode,String itemCode,String lotNo,String lotSl,double replQty, Connection conn) throws ITMException     
{

	String sql = "";
	int upddateStatus = 0;
	PreparedStatement pstmtupdate = null;
	
	try
	{
		
		  sql = " UPDATE STOCK SET REPL_QTY = ?  " +
		        " WHERE LOC_CODE = ? AND ITEM_CODE = ? AND LOT_NO = ? AND LOT_SL = ? AND ALLOC_QTY > 0";

		  pstmtupdate = conn.prepareStatement(sql);
		  pstmtupdate.setDouble(1, replQty);
		  pstmtupdate.setString(2, locCode);
		  pstmtupdate.setString(3, itemCode);
		  pstmtupdate.setString(4, lotNo);
		  pstmtupdate.setString(5, lotSl);
		  upddateStatus =  pstmtupdate.executeUpdate();
	}
	catch(Exception ex)
	{
		ex.printStackTrace();
		throw new ITMException(ex);
	}
	finally
	{
		try
		{
		
			if(pstmtupdate != null)
			{
				pstmtupdate.close();
				pstmtupdate = null;
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			throw new ITMException(ex);
		}
	}
}
//changed by Pragyan on 28/FEB/14 for update repl qty in stock.end
private String getInventoryStatus(String locCode,Connection conn) throws ITMException
{
	 String sql = "",invStat = "";
	 PreparedStatement pstmt = null;
	 ResultSet rs = null;
	 
	 try
	 {
		 
		 sql =   " SELECT INV_STAT FROM LOCATION WHERE  LOC_CODE = ?";
				 
		 pstmt = conn.prepareStatement(sql);
		 pstmt.setString(1, locCode); 
		  rs = pstmt.executeQuery();
		  
		  
		 if( rs.next())
		 {
			 invStat = rs.getString(1);
			
		 }
		 rs.close(); rs = null;
		 pstmt.close(); pstmt = null;	 
		 
	 }
	 catch(Exception ex)
	 {
		 ex.printStackTrace();
		 throw new ITMException(ex);
	 }
	 return invStat;
 }

private boolean isRemotePrintSrvCofigured(String propertyName , Connection conn) throws ITMException
{
	String sql = "";
	String flagRemoteRptSrvltCofigured = "N";
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	boolean isConfigured = false;
	
	try
	{
		flagRemoteRptSrvltCofigured  = discommon.getDisparams("999999",propertyName,conn);       
		
		if("Y".equalsIgnoreCase(flagRemoteRptSrvltCofigured))
		{
			return isConfigured = true;
		}
		else
		{
			return isConfigured;
		}
			
	}
	catch(Exception e)
	{
		e.printStackTrace();
		throw new ITMException(e);
	}
	finally
	{
		try
		{	
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			throw new ITMException(ex);
		}
	}
}
//Changed By Pragyan 14/08/14 for tran_code argument and loc type parent start.
private HashMap getArgTransporterInfoMap(String saleOrder, double perShipWeight ,double noArt,String pickType , String shipType ,String transporterCode, Connection conn) throws ITMException
{
	String sql = "";
	String sql1 = "";
	String sqlShipStanCode = "";
	String sqlCust = "";
	ResultSet rs = null;
	ResultSet rs1 = null;
	PreparedStatement pstmt = null;
	HashMap transInfoMap = new HashMap();
	String stanCodeFrm = "",stateCodeFrm = "",siteCodeShip = "",stanCodeCust= "",custCodeDlv = "",stateCodeCust ="";
	String tranCode = "",transMode= "",maxWeight= "",locType= "";
	String pinTo = "",pinFrm = "";
	HashMap stationInfoMap = null;
	String dbShipType = "";
	String serviceCode = "";
	String shipmentType = "";
	//Changed By Pragyan 23-DEC-13 To check ADSI Connection is required.(KB/Ashish mail Dt.121413) 
	String adsiFlag = "";

	try
	{
		System.out.println("transporterCode::::::::::::::"+transporterCode);


		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);
		pinTo = (String)stationInfoMap.get("DLV_PIN");

		System.out.println("custCodeDlv::::::::"+custCodeDlv);
		
		//Changed BY Pragyan for Site Transporter on 22/09/14 start.
		
		sql = " SELECT T.SERVICE_CODE, T.SHIPMENT_TYPE, T.ADSI_FLAG,M.TRANS_MODE FROM SITE_TRANSPORTER T,TRANSPORTER_MODE M WHERE T.TRAN_CODE = ? AND M.TRAN_CODE = T.TRAN_CODE AND T.SITE_CODE = ?";   
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, transporterCode); 
		pstmt.setString(2, siteCodeShip); 
		
		rs = pstmt.executeQuery();
		if(rs.next())
		{
			System.out.println("Block In else If found else rs.............");
			serviceCode= checkNull(rs.getString("SERVICE_CODE"));
			shipmentType = checkNull(rs.getString("SHIPMENT_TYPE"));
			adsiFlag = checkNull(rs.getString("ADSI_FLAG"));
			transMode = checkNull(rs.getString("TRANS_MODE"));
		}
		//Changed BY Pragyan for Site Transporter on 22/09/14 end.
		else
		{

			rs.close(); rs = null;
			pstmt.close(); pstmt = null;	
			
			sql = " SELECT T.SERVICE_CODE, T.SHIPMENT_TYPE, T.ADSI_FLAG,M.TRANS_MODE FROM TRANSPORTER T,TRANSPORTER_MODE M WHERE T.TRAN_CODE = ? AND M.TRAN_CODE = T.TRAN_CODE ";   
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, transporterCode); 
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				System.out.println("Block In else If found else rs.............");
				serviceCode= checkNull(rs.getString("SERVICE_CODE"));
				shipmentType = checkNull(rs.getString("SHIPMENT_TYPE"));
				adsiFlag = checkNull(rs.getString("ADSI_FLAG"));
				transMode = checkNull(rs.getString("TRANS_MODE"));
			}
		}
		rs.close(); rs = null;
		pstmt.close(); pstmt = null;	 


		transInfoMap.put("TRAN_CODE", transporterCode);
		transInfoMap.put("TRANS_MODE", transMode);
		transInfoMap.put("MAX_WEIGHT", "");
		transInfoMap.put("LOC_TYPE", "");
		transInfoMap.put("CUST_CODE_DLV", custCodeDlv);
		transInfoMap.put("SHIP_TYPE", "");
		transInfoMap.put("SERVICE_CODE", serviceCode);
		transInfoMap.put("PIN", pinTo);
		transInfoMap.put("SHIPMENT_TYPE",shipmentType);
		//Changed By Pragyan 23-DEC-13 To check ADSI Connection is required.(KB/Ashish mail Dt.121413) 
		transInfoMap.put("ADSI_FLAG",adsiFlag);
		transInfoMap.put("IS_DIRECT_TRANSPORTER","Y");
		transInfoMap.putAll(sordMap);
	}
	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;	
}
//Merge code on 19-SEP-14   [W14FSUN003]	
//Changed By Pragyan 14/08/14 for tran_code argument and loc type parent end.
private double getFillerWeight(String packCode,String locTypeParent,double weight,double volume, Connection conn) throws ITMException
{
	 String sql = "";
	 double fillerWeight = 0.0;
	 PreparedStatement pstmt = null;
	 ResultSet rs = null;
	 
	 try
	 {
		 
		 sql =   " SELECT FILLER_WEIGHT FROM PACKING_FILLER WHERE  PACK_CODE = ? AND LOC_TYPE__PARENT = ? AND " 
		 		+" (? BETWEEN MIN_WEIGHT AND MAX_WEIGHT) AND (? BETWEEN MIN_VOLUME AND MAX_VOLUME) ORDER BY FILLER_WEIGHT ASC";
				 
		 pstmt = conn.prepareStatement(sql);
		 pstmt.setString(1, packCode);
		 pstmt.setString(2, locTypeParent);
		 pstmt.setDouble(3, weight);
		 pstmt.setDouble(4, volume);
		 		 
		 rs = pstmt.executeQuery();
		 if( rs.next())
		 {
			 fillerWeight = rs.getDouble(1);
			
		 }
		 rs.close(); rs = null;
		 pstmt.close(); pstmt = null;	 
		 
	 }
	 catch(Exception ex)
	 {
		 ex.printStackTrace();
		 throw new ITMException(ex);
	 }
	 return fillerWeight;
 }
//Changed By Pragyan 14/08/14 for tran_code argument and loc type parent end.
private void updatePacketWeigfhts(String masterPackTranId ,String packCode,double tareWeight,double fillerweight,double caseWeight,String masterCartonNo, Connection conn) throws ITMException
{
	 String sql = "";
	 int  updateCount = 0;
	 PreparedStatement pstmt = null;
	 ResultSet rs = null;
	 
	 try
	 {
		 
		 sql =   " UPDATE  PACK_HDR SET TARE_WEIGHT = ?,FILLER_WEIGHT = ? WHERE TRAN_ID = ?";
				 
		 pstmt = conn.prepareStatement(sql);
		 pstmt.setDouble(1, tareWeight);
		 pstmt.setDouble(2, fillerweight);
		 pstmt.setString(3, masterPackTranId);
			 		 
		 updateCount = pstmt.executeUpdate();
		 
		 if(updateCount > 0)
		 {
			 System.out.println("	Update Count for master pack weight update "+updateCount);
		 }
		
		 if( pstmt != null )
		 {
			pstmt.close();
			pstmt = null;
		 }
	 }
	 catch(Exception ex)
	 {
		 ex.printStackTrace();
		 throw new ITMException(ex);
	 }
	 finally
		{
			try
			{
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch (Exception e1)
			{
				throw new ITMException(e1);
			}
		}
	 
  }

}