package ibase.webitm.ejb.mfg;

//BD0783 replaced with BD0783 -- 14/01/09
/*
 1. truncate table plan_hdr;
 2. add sale_order and line_no, seq_no in plan_header
 alter table plan_hdr add sale_ordr char(10);
 alter table plan_hdr add line_no char(3);
 alter table plan_hdr add seq_no number(10);
 3. make seq_no not null
 alter table plan_hdr modify seq_no number(10) not null;
 4. Drop primay key of plan_hdr
 alter table plan_hdr drop constraint plan_hdr_x;
 alter table plan_hdr drop constraint planhdr_x;

 5. Create new primary key with sale_order and line_no
 alter table add constraint plan_hdr_x primary key (site_code,item_code,seq_no) using index tablespace itm_mfg_i1;

 6. in of case mfgtype = "O" create workorder instead of mps order
 */
import org.w3c.dom.*;

import java.rmi.RemoteException;
import java.util.*;
import java.util.Map.Entry;
import java.sql.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.text.NumberFormat;
import java.text.DecimalFormat;

import javax.ejb.*;

import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.*;
import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.ejb.fin.FinCommon;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.TransIDGenerator;
import ibase.system.config.*;
import ibase.utility.CommonConstants;

import javax.ejb.Stateless; // added for ejb3
//12/04/10 manoharan MF90BHU003

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFCell;

//import org.apache.poi.xssf.usermodel.*;
//import org.apache.poi.ss.util.CellRangeAddress;
//import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.w3c.dom.*;

import javax.xml.parsers.*;

//end 12/04/10 manoharan MF90BHU003

@Stateless
//added for ejb3
public class RunMRPPrc extends ProcessEJB implements RunMRPPrcLocal, RunMRPPrcRemote // SessionBean
{

	String errString = "";
	String siteCodeFrom = "0";
	String siteCodeTo = "zz";
	String itemCodeFrom = "0";
	String itemCodeTo = "zz";
	String itemSerFrom = "0";
	String itemSerTo = "zz";
	String disPlan = null;
	String mfgPlan = null;
	String matPlan = null;
	String verifier = null;
	// 19-12-2005 manoharan
	java.sql.Timestamp dateFrom = null;
	java.sql.Timestamp dateTo = null;
	String sDateFrom = "";
	String sDateTo = "";
	String dbDateFrom = "";
	String dbDateTo = "";
	String dateFromString = "";
	String dateToString = "";
	// end 19-12-2005 manoharan
	// 01-10-2007 manoharan
	String sRunDate = null;
	java.sql.Timestamp runDate = null;
	String dbRunDate = null;
	String runDateString = "";
	// end 01-10-2007 manoharan

	String standingOrdTypes = "";
	String mrpExpediate = "";
	String mrpTrackTranId = "";
	String mrpDynMinStk = "";
	String roundReqTo = "";
	String minOrderChk = "";
	String deptCodeMfg = "";
	String madeToOrder = null;
	String madeToStock = null;
	String balIntersite = "";
	String userId;
	String genIndent = "";

	int MrpClubbingHorizon;
	int processCycle;
	int expediateDays;

	private ArrayList adpeList = new ArrayList();
	private ArrayList interSiteList = new ArrayList();
	private ArrayList surplusList = new ArrayList();
	private ArrayList surplusListOriginal = new ArrayList();

	private ArrayList indList = new ArrayList();
	private ArrayList mpsList = new ArrayList();
	private ArrayList indDemList = new ArrayList();
	private ArrayList disList = new ArrayList();

	Connection conn = null;

	transient GenericUtility genericUtility = null;

	HashMap itemCodeMap = new HashMap();
	HashMap siteCodeMap = new HashMap();
	HashMap itemHashMap = new HashMap();
	Set itemList = new HashSet();
	Set cyclicCheck = null;
	String logInSite = "";
	String chgUser = "";
	String chgTerm = "";
	HashMap hmap = new HashMap();
	int level = 0;

	CommonConstants commonConstants = new CommonConstants();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();

	CyclicItem cyclicItem = new CyclicItem();// Added by JIten 07/11/06
	FileWriter fw = null;
	FileWriter fw1 = null;
	FileWriter fwInvalidBom = null;
	String validBomItemCode = null;
	boolean invaldBomExists = false;

	String context = "";// Gulzar on 4/30/2012

	StringBuffer xmlDataString = null; // sachin on 26/6/13
	String wnName="";   // sachin on 26/6/13
	String sorderList = "0";//Manoj dtd 17/10/2013
	String itemCodeList = "0";//Manoj dtd 17/10/2013
	boolean isDetailReq = false;//Manoj dtd 17/10/2013
	String siteItemList = "0";//chandrashekar 0n 04/04/2014
	String siteList = "0";//chandrashekar 0n 10/07/2014
	boolean isRequirement = false;//Chandrashekar 04/04/2014

	ArrayList IPD_INDEPENDENT = new ArrayList();
	ArrayList IPD_INDENT = new ArrayList();
	ArrayList IPD_MPS_ORDER = new ArrayList();
	ArrayList IPD_DIST = new ArrayList();

	String wnName1="";   // chandrakant on 29/4/14

	HashMap<String, ArrayList<String>> altitemMap=new HashMap<String, ArrayList<String>>();//Manoj dtd 30/04/2014 to store Alternate item

	// HashMap <String,ArrayList>itemBomMap=new HashMap<String, ArrayList>();
	HashMap <String,String>itemBomMap=new HashMap<String, String>();
	HashMap <String,Set<String>>itemBomMap1=new HashMap<String, Set<String>>();
	HashMap <String,Set<String>>itemBomMap2=new HashMap<String, Set<String>>();

	Boolean isBomReplace = false; // added by cpatil on 17/05/14
	String bomCode1="";
	String siteCode1="" ;   // added by cpatil on 17/05/14
	double bomReplaceDemand= 0;
	String saleOrderReplaceBom="", lineNoReplaceBom="";
	HashMap itemCodeDetailMap = new HashMap();

	HashMap itemWorkOrderMap = new HashMap();  // 18/06/14
	HashMap parentItemMap = new HashMap();  // 18/06/14


	boolean isWizard=false;

	String orderType="";   // added by cpatil on 02/07/14
	long startTime = 0;

	String itemCodeOnlyList="";  //added cpatil on 20/11/14

	String finalString="";
	HashMap <String,String>bomMap=new HashMap<String, String>();

	//String  IPD_INDEPENDENT = "",IPD_INDENT = "",IPD_MPS_ORDER = "",IPD_DIST = "";  //cpatil on 15/01/14
	/*
	 * public void ejbCreate() throws RemoteException, CreateException { try {
	 * System.out.println("RunMRPPrcEJB ejbCreate called........."); } catch
	 * (Exception e) {
	 * System.out.println("Exception :ProcessEJB :ejbCreate :==>"+e); throw new
	 * CreateException(); } }
	 * 
	 * public void ejbRemove() { }
	 * 
	 * public void ejbActivate() { }
	 * 
	 * public void ejbPassivate() { }
	 */

	/*
	 * public String process() throws RemoteException,ITMException {
	 * System.out.println("Called process()....."); return ""; }
	 */
	ArrayList<ADPElement> al1=null;
	TreeMap<String, ArrayList<ADPElement>> finalMap=new TreeMap<String, ArrayList<ADPElement>>();

	String locGroupList="";
	HashMap<String, String> locGroupMap = new HashMap<String, String>();
	HashMap<String, String> soItemListMap = new HashMap<String, String>();

	String yield="";
	String soItemList="";

	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException, ITMException
	{
		System.out.println("Called process(string, string).....");
		String resultString = null;
		Document dom = null, dom1 = null;
		String retString = null;
		long endTime = 0, totalTime = 0, totalHrs = 0, totlMts = 0, totSecs = 0; // Added
		// by
		// Jiten
		// 13/11/06
		// -
		try
		{
			if (xmlString != null && xmlString.trim().length() != 0)
			{
				// System.out.println("XML String :" + xmlString);
				genericUtility = GenericUtility.getInstance();
				dom = genericUtility.parseString(xmlString);
			}
			// added by Jiten 13/11/06 -
			startTime = System.currentTimeMillis();
			retString = getData(dom, dom1, windowName, xtraParams);
			endTime = System.currentTimeMillis();
			totalTime = endTime - startTime;
			System.out.println("Total Time Spend :: " + totalTime + " Milliseconds");

			totSecs = (int) (((double) 1 / 1000) * (totalTime));
			totalHrs = (int) (totSecs / 3600);
			totlMts = (int) (((totSecs - (totalHrs * 3600)) / 60));
			totSecs = (int) (totSecs - ((totalHrs * 3600) + (totlMts * 60)));

			System.out.println("Total Time Spend :: " + totalHrs + " Hours " + totlMts + " Minutes " + totSecs + " seconds");
			// End adding 13/11/06 -
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :Process (String xmlString):" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			itemCodeList ="";
		}
		System.out.println("Returning from Process :: " + retString);
		return retString;
	}




	private String getWinName(Node node) throws Exception
	{
		String objName = "";
		NamedNodeMap attrMap = node.getAttributes();
		objName = attrMap.getNamedItem("objName").getNodeValue();
		//cpatil-25/08/14-System.out.println(" Object Name is==>" + objName);
		return "w_" + objName;
	}

	public String getData(Document dom, Document dom1, String windowName, String xtraParams) throws RemoteException, ITMException
	{
		errString = "";
		String resultString = "",windowName1="",bomCodeParent= "";
		ResultSet rs = null;
		this.wnName=windowName;
		long endTime = 0, totalTime = 0, totalHrs = 0, totlMts = 0, totSecs = 0; // Added


		System.out.println("win name is ==>"+wnName);


		// System.out.println("Initial Size of Item Has Map :" +
		// itemHashMap.size());
		//if("w_runmrp_det".equalsIgnoreCase(windowName))
		if("w_mrp_run_wiz".equalsIgnoreCase(windowName))
		{
			isDetailReq=true;
		}
		if("w_requirement".equalsIgnoreCase(windowName))
		{
			isRequirement=true;
		}

		if (genericUtility == null)
		{
			genericUtility = GenericUtility.getInstance();
		}
		if (dom != null)
		{
			System.out.println("dom =[" + genericUtility.serializeDom(dom) + "]");
		}
		logInSite = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
		genericUtility = GenericUtility.getInstance();
		ConnDriver connDriver = new ConnDriver();
		try
		{
			context = genericUtility.getColumnValue("wizard", dom);
			//cpatil-25/08/14-System.out.println("context =[" + context + "]");
			/*Commented by Manoj dtd 06/06/2014 not required 
			 if (context != null && context.trim().length() > 0)
			{
				context = "3";
			} else
			{
				context = "2";
			}*/
			if (context != null && context.trim().length() > 0)
			{
				isWizard=true;
			}
			//sorderList= genericUtility.getColumnValue("sale_order_list", dom);
			itemCodeList = genericUtility.getColumnValue("item_code_list", dom);   // added by cpatil
			siteItemList = genericUtility.getColumnValue("site_item_list", dom);   //added by chandrashekar
			siteList = genericUtility.getColumnValue("site_list", dom);   //added by chandrashekar
			itemCodeOnlyList = genericUtility.getColumnValue("item_code_only_list", dom);   // added by cpatil
			//cpatil-25/08/14-System.out.println("siteList@@@@@@"+siteList);
			locGroupList = genericUtility.getColumnValue("locGroupList", dom);   // added by cpatil
			soItemList = genericUtility.getColumnValue("soItemList", dom);   // added by cpatil
			System.out.println("@@@@@@soItemList["+soItemList+"]");
			yield = genericUtility.getColumnValue("yield", dom);//added by chandrashekar on 05-Feb-2015
			if(yield == null || yield.trim().length() == 0)
			{
				yield = "Y";
			}
			System.out.println("yield>>>>>["+yield+"]");
			if( soItemList != null )
			{
				System.out.println("@@@@@ soItemList["+soItemList+"]");
				String soItemLst[]=soItemList.split(",");
				System.out.println("@@@@@ soItemLst.length["+soItemLst.length+"]");
				for(int i=0;i<soItemLst.length;i++)
				{
					String SOrder="",tempItemCode="";
					String tempsoItemLst=soItemLst[i];

					System.out.println("@@@@@ tempsoItemLst["+tempsoItemLst+"]");
					String tempsoItemLstArr[]=tempsoItemLst.split("@");
					if( tempsoItemLstArr.length > 0 )
					{
						SOrder=tempsoItemLstArr[0];
					}
					if( tempsoItemLstArr.length > 1 )
					{
						tempItemCode=tempsoItemLstArr[1];
					}
					System.out.println("@@@@@ SOrder["+SOrder+"]tempItemCode["+tempItemCode+"]");
					if( soItemListMap.containsKey(tempItemCode) )
					{
						String tempVal = soItemListMap.get(tempItemCode).toString();
						soItemListMap.put(checkNull(tempItemCode).trim(), tempVal+","+checkNull(SOrder).trim() );
					}
					else
					{
						soItemListMap.put(checkNull(tempItemCode).trim(), checkNull(SOrder).trim() );
					}
				}
				System.out.println("@@@@@ final soItemListMap["+soItemListMap+"]");
			}

			if( locGroupList != null )
			{
				System.out.println("@@@@@ locGroupList["+locGroupList+"]");
				String locGroupLst[]=locGroupList.split(",");
				System.out.println("@@@@@ locGroupLst.length["+locGroupLst.length+"]");
				for(int i=0;i<locGroupLst.length;i++)
				{
					String SOrder="",locGroup="";
					String tempLocGroup=locGroupLst[i];
					System.out.println("@@@@@ tempLocGroup["+tempLocGroup+"]");
					String tempLocGroupArr[]=tempLocGroup.split("@");
					if( tempLocGroupArr.length > 0 )
					{
						SOrder=tempLocGroupArr[0];
					}
					if( tempLocGroupArr.length > 1 )
					{
						locGroup=tempLocGroupArr[1];
					}
					System.out.println("@@@@@ SOrder["+SOrder+"]locGroup["+locGroup+"]");
					locGroupMap.put(checkNull(SOrder).trim(), locGroup);
				}
				System.out.println("@@@@@locGroupMap["+locGroupMap+"]");
			}



			String isBomReplaceStr = genericUtility.getColumnValue("isBomReplace", dom);   // added by cpatil on 17/05/14

			if( isDetailReq )
			{
				orderType = genericUtility.getColumnValue("order_type", dom);   // added by cpatil on 26/06/14
			}

			if (isBomReplaceStr == null || isBomReplaceStr.trim().length() == 0)
			{
				isBomReplaceStr = "N";
			}
			if("N".equalsIgnoreCase(isBomReplaceStr))
			{
				isBomReplace = false;
			}
			else if("Y".equalsIgnoreCase(isBomReplaceStr))
			{
				isBomReplace = true;
				bomCode1 =  genericUtility.getColumnValue("bom_code", dom);   // added by cpatil on 17/05/14
				siteCode1 = genericUtility.getColumnValue("site_code", dom);   // added by cpatil on 17/05/14
				bomReplaceDemand = Double.parseDouble( genericUtility.getColumnValue("bomReplaceDemand", dom)==null ? "0" : genericUtility.getColumnValue("bomReplaceDemand", dom));
				bomCodeParent = checkNull( genericUtility.getColumnValue("bom_code_parent", dom));

				saleOrderReplaceBom = genericUtility.getColumnValue("saleOrderReplaceBom", dom);   // added by cpatil on 17/05/14
				lineNoReplaceBom = genericUtility.getColumnValue("lineNoReplaceBom", dom);   // added by cpatil on 17/05/14

			}
			System.out.println("@@@@@@@@@@@ isBomReplace["+isBomReplace+"]bomReplaceDemand["+bomReplaceDemand+"]");

			// ADDEED BY CPATIL for remove null pointer exception on 26/05/14
			if( dom1 != null )
			{
				if( !(isBomReplace))  // added by cpatil on 26/05/14 for bom replacement
				{
					NodeList parentNodeList1 = dom1.getElementsByTagName("Detail3");
					Node parentNode1 = parentNodeList1.item(0);
					try 
					{
						windowName1 = this.getWinName(parentNode1);
					} 
					catch (Exception e1)
					{
						e1.printStackTrace();
					}
					this.wnName1=windowName1;
					//cpatil-25/08/14-System.out.println("wnName1 ==>"+wnName1);
				}
			}
			// end

			// Added by Jiten 07/11/06
			// this.fw = new
			// FileWriter(CommonConstants.JBOSSHOME+"\\log\\RepeatBom.log");
			this.fw = new FileWriter(CommonConstants.JBOSSHOME + File.separator + "log" + File.separator + "RepeatBom.log");
			this.fw.write("Site Code		Bom Code		Item Code		CyclicItemCode" + "\r\n");
			// End
			// Added by jiten 10/11/06
			// this.fw1 = new
			// FileWriter(CommonConstants.JBOSSHOME+"\\log\\SkipItem.log");
			this.fw1 = new FileWriter(CommonConstants.JBOSSHOME + File.separator + "log" + File.separator + "SkipItem.log");
			this.fw1.write("Site Code	 Product Code	 ItemCode Skipped" + "\r\n");
			// End

			// 19-01-2007 manohar
			this.fwInvalidBom = new FileWriter(CommonConstants.JBOSSHOME + File.separator + "log" + File.separator + "InValidBom.log");
			this.fwInvalidBom.write("Site Code  Item Code   Bom Code     Message\r\n");
			this.fwInvalidBom.write("=========  ==========  ==========   ========\r\n");
			// End 19-01-2007 manohar

			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "userId");

			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId");
			CommonConstants.setIBASEHOME();
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver = null;
			// validate the filter parameter entered by the user
			errString = validateFilterParams(dom);

			endTime = System.currentTimeMillis();
			totalTime = endTime - startTime;
			System.out.println("Total Time Spend :: " + totalTime + " Milliseconds");

			totSecs = (int) (((double) 1 / 1000) * (totalTime));
			totalHrs = (int) (totSecs / 3600);
			totlMts = (int) (((totSecs - (totalHrs * 3600)) / 60));
			totSecs = (int) (totSecs - ((totalHrs * 3600) + (totlMts * 60)));

			System.out.println("Total Time Spend validateFilterParams[" + totalHrs + "] Hours [" + totlMts + "] Minutes [" + totSecs + "] seconds");


			if (errString != null && errString.trim().length() > 0)
			{
				//cpatil-25/08/14-System.out.println("Error validating filter parameters:..." + errString);
				return errString;
			}

			// Populating Common Parameters...
			errString = "";
			// //cpatil-25/08/14-System.out.println("Populating Common Parameters...");
			errString = populateCommonParameters();
			endTime = System.currentTimeMillis();
			totalTime = endTime - startTime;
			//cpatil-25/08/14-System.out.println("Total Time Spend :: " + totalTime + " Milliseconds");

			totSecs = (int) (((double) 1 / 1000) * (totalTime));
			totalHrs = (int) (totSecs / 3600);
			totlMts = (int) (((totSecs - (totalHrs * 3600)) / 60));
			totSecs = (int) (totSecs - ((totalHrs * 3600) + (totlMts * 60)));

			//cpatil-25/08/14-System.out.println("Total Time Spend populateCommonParameters[" + totalHrs + "] Hours [" + totlMts + "] Minutes [" + totSecs + "] seconds");

			if (errString != null && errString.trim().length() > 0)
			{
				System.out.println("Error While Populating Common Parameters:..." + errString);
				return errString;
			}

			// Populating Site Code Map.......
			if(!( isBomReplace))   // added by cpatil on 17/05/14 for BomReplace 
			{
				//cpatil-25/08/14-System.out.println("Populating Site Code Map.......");
				siteCodeTo = siteCodeTo.trim() + "     ";
				siteCodeTo = siteCodeTo.substring(0, 5);// + "z";
				errString = populateSiteMap();
				if (errString != null && errString.trim().length() > 0)
				{
					System.out.println("Error While Populating Site:..." + errString);
					return errString;
				}
			}
			else
			{
				//cpatil-25/08/14-System.out.println("Populating Site Code Map.......");
				siteCode1 = siteCode1.trim() + "     ";
				siteCode1 = siteCode1.substring(0, 5);
				errString = populateSiteMap();
				if (errString != null && errString.trim().length() > 0)
				{
					System.out.println("Error While Populating Site:..." + errString);
					return errString;
				}
			}
			endTime = System.currentTimeMillis();
			totalTime = endTime - startTime;
			//cpatil-25/08/14-System.out.println("Total Time Spend :: " + totalTime + " Milliseconds");

			totSecs = (int) (((double) 1 / 1000) * (totalTime));
			totalHrs = (int) (totSecs / 3600);
			totlMts = (int) (((totSecs - (totalHrs * 3600)) / 60));
			totSecs = (int) (totSecs - ((totalHrs * 3600) + (totlMts * 60)));

			//cpatil-25/08/14-System.out.println("Total Time Spend [" + isBomReplace + "] populateSiteMap[" + totalHrs + "] Hours [" + totlMts + "] Minutes [" + totSecs + "] seconds");

			if(!( isBomReplace))   // added by cpatil on 17/05/14 for BomReplace 
			{
				// Populating Item Code Map.......
				itemCodeTo = itemCodeTo.trim() + "          ";
				itemCodeTo = itemCodeTo.substring(0, 10);// + "z";

				itemSerTo = itemSerTo.trim() + "     ";
				itemSerTo = itemSerTo.substring(0, 5);// + "z";

				//cpatil-25/08/14-System.out.println("Populating Item Code Map.......");

				errString = populateItemMap();

				if (errString != null && errString.trim().length() > 0)
				{
					System.out.println("Error While Populating Item code:..." + errString);
					return errString;
				}

			}
			else
			{
				//cpatil-25/08/14-System.out.println("Else 12/06/14 itemCodeTo [" + itemCodeTo + "] itemCodeMap [" + itemCodeMap +"]");
				itemCodeMap.put(itemCodeTo, new Integer(itemCodeMap.size() + 1));
			}
			endTime = System.currentTimeMillis();
			totalTime = endTime - startTime;
			//cpatil-25/08/14-System.out.println("Total Time Spend :: " + totalTime + " Milliseconds");

			totSecs = (int) (((double) 1 / 1000) * (totalTime));
			totalHrs = (int) (totSecs / 3600);
			totlMts = (int) (((totSecs - (totalHrs * 3600)) / 60));
			totSecs = (int) (totSecs - ((totalHrs * 3600) + (totlMts * 60)));

			//cpatil-25/08/14-System.out.println("Total Time Spend [" + isBomReplace + "] populateItemMap[" + totalHrs + "] Hours [" + totlMts + "] Minutes [" + totSecs + "] seconds");

			// Populating All Items...........
			// if MatPlan equals 'Y' then call method populateAllItem()

			if(!( isBomReplace))   // added by cpatil on 17/05/14 for BomReplace 
			{
				if (matPlan.equals("Y"))
				{
					System.out.println("Populating All Items...........");
					errString = populateAllItem();
					endTime = System.currentTimeMillis();
					totalTime = endTime - startTime;
					//cpatil-25/08/14-System.out.println("Total Time Spend :: " + totalTime + " Milliseconds");

					totSecs = (int) (((double) 1 / 1000) * (totalTime));
					totalHrs = (int) (totSecs / 3600);
					totlMts = (int) (((totSecs - (totalHrs * 3600)) / 60));
					totSecs = (int) (totSecs - ((totalHrs * 3600) + (totlMts * 60)));

					//cpatil-25/08/14-System.out.println("Total Time Spend [" + isBomReplace + "] populateAllItem[" + totalHrs + "] Hours [" + totlMts + "] Minutes [" + totSecs + "] seconds");

					if (errString != null && errString.trim().length() > 0)
					{
						System.out.println("Error While Populating All Items:..." + errString);
						return errString;
					}
					// 19-01-2007 manoharan
					if (verifier != null && verifier.equalsIgnoreCase("Y"))
					{
						if (invaldBomExists)
						{
							errString = itmDBAccessEJB.getErrorString("", "VTBOMUCON", "", "", conn);
							return errString;
						}
					}
					// end 19-01-2007 manoharan
				}
			}

			if( isBomReplace )  // added by cpatil on 19/05/14
			{
				//cpatil-25/08/14-System.out.println("13/06/14  adpeList.size() before[" + adpeList.size() + "]");
				adpeList.clear();
				ADPElement adpElement = new ADPElement();
				adpElement.setSiteCode(siteCode1);
				adpElement.setItemCode(itemCodeTo);
				adpElement = setAdpeValues(adpElement);
				//adpElement.setSaleOrder(saleOrderReplaceBom);
				//adpElement.setLineNo(lineNoReplaceBom);
				adpElement.setBomCodeParent(bomCodeParent);
				adpElement.setBomCode(bomCode1);
				System.out.println("@@@@@@cpatil270115::bomCode1["+bomCode1+"]dateFrom["+dateFrom+"]bomReplaceDemand["+bomReplaceDemand+"]saleOrderReplaceBom["+saleOrderReplaceBom+"]lineNoReplaceBom["+lineNoReplaceBom+"]itemCodeTo["+itemCodeTo+"]");
				//adpElement.setDemand(dateFrom,bomReplaceDemand , saleOrderReplaceBom, lineNoReplaceBom  ); 
				//adpElement.setDemand(dateFrom,bomReplaceDemand , saleOrderReplaceBom, lineNoReplaceBom , true );
				//adpElement.setDemand(dateFrom,bomReplaceDemand , saleOrderReplaceBom, itemCodeTo  );

				/*
				if(itemBomMap.containsKey(itemCodeTo) )
				{
					ArrayList tempList = itemBomMap.get(itemCodeTo);
					tempList.add(bomCodeParent);
					itemBomMap.put(itemCodeTo, tempList);
				}
				else
				{	
					ArrayList tempList = new ArrayList();
					tempList.add(bomCodeParent);
					itemBomMap.put(itemCodeTo, tempList);
				}
				 */
				itemBomMap.put(itemCodeTo, bomCodeParent);
				Set<String> bomSet=new HashSet<String>();
				if(itemBomMap1.size()>0)
				{
					if(itemBomMap1.containsKey(itemCodeTo))	
					{
						bomSet=itemBomMap1.get(itemCodeTo);
						bomSet.add(bomCodeParent);
					}
					else
					{
						System.out.println("596--itemCodeTo["+itemCodeTo+"]bomCodeParent["+bomCodeParent+"]");
						bomSet=new HashSet<String>(); 
						bomSet.add(bomCodeParent);
					}
				}
				else
				{
					System.out.println("602--itemCodeTo["+itemCodeTo+"]bomCodeParent["+bomCodeParent+"]");
					bomSet=new HashSet<String>(); 
					bomSet.add(bomCodeParent);
				}
				itemBomMap1.put(itemCodeTo, bomSet);

				itemCodeMap.put(itemCodeTo, new Integer(itemCodeMap.size() + 1));
				//adpElement.setDemand(dateFrom,bomReplaceDemand , "          ", "   " );
				//270115		//adpeList.add(adpElement);
				//cpatil-25/08/14-System.out.println("13/06/14  adpeList.size() after 1 [" + adpeList.size() + "] itemBomMap [" + itemBomMap + "]");

				errString = bomExplode( siteCode1, bomCode1);
				endTime = System.currentTimeMillis();
				totalTime = endTime - startTime;
				//cpatil-25/08/14-System.out.println("Total Time Spend :: " + totalTime + " Milliseconds");

				totSecs = (int) (((double) 1 / 1000) * (totalTime));
				totalHrs = (int) (totSecs / 3600);
				totlMts = (int) (((totSecs - (totalHrs * 3600)) / 60));
				totSecs = (int) (totSecs - ((totalHrs * 3600) + (totlMts * 60)));

				//cpatil-25/08/14-System.out.println("Total Time Spend [" + isBomReplace + "] bomExplode[" + totalHrs + "] Hours [" + totlMts + "] Minutes [" + totSecs + "] seconds");
				if (errString != null && errString.trim().length() > 0)
				{
					System.out.println("@@@ cpatil --- Error While Calling method bomExplode(String, String):..." + errString);
					return errString;
				}
				String parentBom = itemCodeDetailMap.get(bomCode1) == null ? "":itemCodeDetailMap.get(bomCode1).toString();
				itemCodeDetailMap.put(itemCodeTo, parentBom+"@"+bomCode1);

				String sourceItem = setDescription("item_code", "bom", "bom_code", bomCode1, conn);
				parentItemMap.put(itemCodeTo, sourceItem );   //18/06/14
				//cpatil-25/08/14-System.out.println("@@@@ 500 : sourceItem["+sourceItem+"]bomCode["+bomCode1+"]itemCodeTo["+itemCodeTo+"]parentItemMap["+parentItemMap+"]");

				//cpatil-25/08/14-System.out.println("13/06/14  adpeList.size() after 2 [" + adpeList.size() + "] itemBomMap [" + itemBomMap + "]");

			}
			//else
			//{
			System.out.println("680---"+adpeList.size());
			errString = populateADPElementList();
			endTime = System.currentTimeMillis();
			totalTime = endTime - startTime;
			//cpatil-25/08/14-System.out.println("Total Time Spend :: " + totalTime + " Milliseconds");

			totSecs = (int) (((double) 1 / 1000) * (totalTime));
			totalHrs = (int) (totSecs / 3600);
			totlMts = (int) (((totSecs - (totalHrs * 3600)) / 60));
			totSecs = (int) (totSecs - ((totalHrs * 3600) + (totlMts * 60)));

			//cpatil-25/08/14-System.out.println("Total Time Spend [" + isBomReplace + "] populateADPElementList [" + totalHrs + "] Hours [" + totlMts + "] Minutes [" + totSecs + "] seconds");
			//}

			// generate the ADPElement array here..

			if (errString != null && errString.trim().length() > 0)
			{
				System.out.println("Error While Populating ADPEList:..." + errString);
				return errString;
			}
			if (disPlan.equals("Y") && balIntersite.equals("Y"))
			{
				errString = populateInterSiteDistance();
				if (errString != null && errString.trim().length() > 0)
				{
					System.out.println("Error While Optimizing ADPEList:..." + errString);
					return errString;
				}
				populateSurplusList();
				//cpatil-25/08/14-System.out.println("Size of populateSurplusList : " + surplusList.size());
				//cpatil-25/08/14-System.out.println("Size of populateInterSiteDistance : " + interSiteList.size());
			}
			// demand/supply to be inserted in separate table

			//
			errString = mrpOptimize();
			endTime = System.currentTimeMillis();
			totalTime = endTime - startTime;
			//cpatil-25/08/14-System.out.println("Total Time Spend :: " + totalTime + " Milliseconds");

			totSecs = (int) (((double) 1 / 1000) * (totalTime));
			totalHrs = (int) (totSecs / 3600);
			totlMts = (int) (((totSecs - (totalHrs * 3600)) / 60));
			totSecs = (int) (totSecs - ((totalHrs * 3600) + (totlMts * 60)));

			//cpatil-25/08/14-System.out.println("Total Time Spend [" + isBomReplace + "] mrpOptimize [" + totalHrs + "] Hours [" + totlMts + "] Minutes [" + totSecs + "] seconds");
			if (errString != null && errString.trim().length() > 0)
			{
				System.out.println("Error While Optimizing ADPEList:..." + errString);
				return errString;
			}

			/*// Added by sachin on 26/6/13  

			if (wnName.equals("w_requirement"))
			{
				if (xmlDataString.toString() != null && xmlDataString.length() > 0)
				{
					System.out.println("returning xml data String " + xmlDataString.toString());
					return xmlDataString.toString();
				}
			}
			 //End Added by sachin on 26/6/13 
			 */
			errString = generatePlanDemand();
			endTime = System.currentTimeMillis();
			totalTime = endTime - startTime;
			//cpatil-25/08/14-System.out.println("Total Time Spend :: " + totalTime + " Milliseconds");

			totSecs = (int) (((double) 1 / 1000) * (totalTime));
			totalHrs = (int) (totSecs / 3600);
			totlMts = (int) (((totSecs - (totalHrs * 3600)) / 60));
			totSecs = (int) (totSecs - ((totalHrs * 3600) + (totlMts * 60)));

			//cpatil-25/08/14-System.out.println("Total Time Spend generatePlanDemand [" + totalHrs + "] Hours [" + totlMts + "] Minutes [" + totSecs + "] seconds");
			if (errString != null && errString.trim().length() > 0)
			{
				System.out.println("Error While generating Plan Demand:..." + errString);
				return errString;
			}
			// 31/01/2008 manoharan not to insert plan demand in case of
			// verification
			//cpatil-25/08/14-System.out.println("@@@@@@@@@@@cpatil verifier["+verifier+"]");
			if (verifier != null && verifier.equalsIgnoreCase("N"))
			{
				//Condition added by Manoj dtd 01/01/2013
				//if(!isDetailReq)
				//{
				errString = InsertPlanDemand();
				endTime = System.currentTimeMillis();
				totalTime = endTime - startTime;
				//cpatil-25/08/14-System.out.println("Total Time Spend :: " + totalTime + " Milliseconds");

				totSecs = (int) (((double) 1 / 1000) * (totalTime));
				totalHrs = (int) (totSecs / 3600);
				totlMts = (int) (((totSecs - (totalHrs * 3600)) / 60));
				totSecs = (int) (totSecs - ((totalHrs * 3600) + (totlMts * 60)));

				//cpatil-25/08/14-System.out.println("Total Time Spend InsertPlanDemand [" + totalHrs + "] Hours [" + totlMts + "] Minutes [" + totSecs + "] seconds");
				if (errString != null && errString.trim().length() > 0)
				{
					System.out.println("Error While inserting Plan Demand:..." + errString);
					return errString;
				}	
				//}

				// Added by Jiten
				String sql = "";
				String lsWhere = "";
				int noOfPlan = 0;
				Statement stmt = null;
				if (matPlan.equalsIgnoreCase("Y") && (mfgPlan.equalsIgnoreCase("Y")) && (disPlan.equalsIgnoreCase("Y")))
				{
					lsWhere = "";
				} else
				{
					if (mfgPlan.equalsIgnoreCase("Y"))
					{
						lsWhere = lsWhere + "'M'";
						noOfPlan = noOfPlan + 1;
					}
					if (disPlan.equalsIgnoreCase("Y"))
					{
						if (noOfPlan == 0)
						{
							lsWhere = "'D'";
						} else
						{
							lsWhere = lsWhere + ",'D'";
						}
						noOfPlan = noOfPlan + 1;
					}
					if (matPlan.equalsIgnoreCase("Y"))
					{
						if (noOfPlan == 0)
						{
							lsWhere = "'P'";
						} else
						{
							lsWhere = lsWhere + ",'P'";
						}
						noOfPlan = noOfPlan + 1;
					}
					if (noOfPlan == 1)
					{
						lsWhere = " AND SUPP_SOUR = " + lsWhere + "";
					} else if (noOfPlan > 1)
					{
						lsWhere = " AND SUPP_SOUR IN (" + lsWhere + ")";
					}
				}
				//Condition added by Manoj dtd 01/01/2013 
				if(!isDetailReq)
				{
					// uncommented on 04/04/11 manoharan foreign key defined with on
					// delete cascade
					sql = "DELETE FROM PLAN_DET WHERE SITE_CODE >='" + siteCodeFrom + "' " + " AND SITE_CODE <= '" + siteCodeTo + "' ";
					// + " AND ITEM_CODE >= '"+itemCodeFrom+"' "
					// + " AND ITEM_CODE <= '"+itemCodeTo+"'" ;//+ lsWhere;
					//cpatil-25/08/14-System.out.println("Delete plan_hdr Sql : " + sql);
					stmt = conn.createStatement();

					int deletedInDetail = stmt.executeUpdate(sql);
					//cpatil-25/08/14-System.out.println("Deleted in Detail For Material Plan: " + deletedInDetail);
					stmt.close();

					//cpatil-25/08/14-System.out.println("Deleted in detail For Material Plan: " + deletedInDetail);

					sql = "DELETE FROM PLAN_HDR WHERE SITE_CODE >='" + siteCodeFrom.trim() + "' " + " AND SITE_CODE <= '" + siteCodeTo + "' " + lsWhere;
					// + " AND ITEM_CODE >= '"+itemCodeFrom.trim()+"' "
					// + " AND ITEM_CODE <= '"+itemCodeTo+"'" + lsWhere;

					//cpatil-25/08/14-System.out.println("Delete plan_hdr Sql : " + sql);
					stmt = conn.createStatement();
					int deletedInHeader = stmt.executeUpdate(sql);

					//cpatil-25/08/14-System.out.println("Deleted in Header For Material Plan: " + deletedInHeader);
					stmt.close();
					// End adding

					// commented by Jiten
					/*
					 * String sql = "DELETE FROM PLAN_HDR"; Statement stmt =
					 * conn.createStatement(); int deletedInHeader =
					 * stmt.executeUpdate(sql); stmt.close();
					 * System.out.println("Deleted in Header : " + deletedInHeader);
					 * 
					 * sql = "DELETE FROM PLAN_DET"; stmt = conn.createStatement();
					 * int deletedInDetail = stmt.executeUpdate(sql);
					 * System.out.println("Deleted in Detail : " + deletedInDetail);
					 * stmt.close();
					 */
					// End
					endTime = System.currentTimeMillis();
					totalTime = endTime - startTime;
					//cpatil-25/08/14-System.out.println("Total Time Spend :: " + totalTime + " Milliseconds");

					totSecs = (int) (((double) 1 / 1000) * (totalTime));
					totalHrs = (int) (totSecs / 3600);
					totlMts = (int) (((totSecs - (totalHrs * 3600)) / 60));
					totSecs = (int) (totSecs - ((totalHrs * 3600) + (totlMts * 60)));

					//cpatil-25/08/14-System.out.println("Total Time Spend delete old plan [" + totalHrs + "] Hours [" + totlMts + "] Minutes [" + totSecs + "] seconds");

					errString = InsertPlanTable();
					endTime = System.currentTimeMillis();
					totalTime = endTime - startTime;
					//cpatil-25/08/14-System.out.println("Total Time Spend :: " + totalTime + " Milliseconds");

					totSecs = (int) (((double) 1 / 1000) * (totalTime));
					totalHrs = (int) (totSecs / 3600);
					totlMts = (int) (((totSecs - (totalHrs * 3600)) / 60));
					totSecs = (int) (totSecs - ((totalHrs * 3600) + (totlMts * 60)));

					//cpatil-25/08/14-System.out.println("Total Time Spend InsertPlanTable [" + totalHrs + "] Hours [" + totlMts + "] Minutes [" + totSecs + "] seconds");
					if (errString != null && errString.trim().length() > 0)
					{
						System.out.println("Error While inserting Plan HdrDet:..." + errString);

						return errString;
					}

				}

			}

			resultString = setValuesInBrow();
			endTime = System.currentTimeMillis();
			totalTime = endTime - startTime;
			//cpatil-25/08/14-System.out.println("Total Time Spend :: " + totalTime + " Milliseconds");

			totSecs = (int) (((double) 1 / 1000) * (totalTime));
			totalHrs = (int) (totSecs / 3600);
			totlMts = (int) (((totSecs - (totalHrs * 3600)) / 60));
			totSecs = (int) (totSecs - ((totalHrs * 3600) + (totlMts * 60)));

			//cpatil-25/08/14-System.out.println("Total Time Spend setValuesInBrow [" + totalHrs + "] Hours [" + totlMts + "] Minutes [" + totSecs + "] seconds");
			Write2XSL();
			endTime = System.currentTimeMillis();
			totalTime = endTime - startTime;
			//cpatil-25/08/14-System.out.println("Total Time Spend :: " + totalTime + " Milliseconds");

			totSecs = (int) (((double) 1 / 1000) * (totalTime));
			totalHrs = (int) (totSecs / 3600);
			totlMts = (int) (((totSecs - (totalHrs * 3600)) / 60));
			totSecs = (int) (totSecs - ((totalHrs * 3600) + (totlMts * 60)));

			//cpatil-25/08/14-System.out.println("Total Time Spend Write2XSL [" + totalHrs + "] Hours [" + totlMts + "] Minutes [" + totSecs + "] seconds");
		} catch (SQLException se)
		{
			System.out.println("SQLException :RunMRPPrcEJB :process(Document dom, Document dom2, String winName, String xtraParams):" + se.getMessage() + ":");
			this.errString = genericUtility.createErrorString(se);
			se.printStackTrace();
			throw new ITMException(se);
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :process(Document dom, Document dom2, String winName, String xtraParams):" + e.getMessage() + ":");
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			throw new ITMException(e);
		} finally
		{
			try
			{
				if (errString != null && errString.trim().length() > 0)
				{
					conn.rollback();

				}
				if (conn != null)
				{
					conn.close();
					conn = null;
				}
				this.fw.flush();// Added by Jiten 07/11/06
				this.fw.close();// Added by Jiten 07/11/06
				this.fw1.flush();// Added by JIten 10/11/06
				this.fw1.close();// Added by JIten 10/11/06
				this.fwInvalidBom.flush(); // 19-01-2007 manohar
				this.fwInvalidBom.close(); // 19-01-2007 manohar
				cleanup();
			} catch (Exception e)
			{
			}

		}
		return resultString; // Jiten - 03/11/06 Moved here from Finally block
	}

	public String validateFilterParams(Document dom) throws ITMException
	{
		String processCycleString = null;
		try
		{
			genericUtility = genericUtility.getInstance();


			// Fetching SiteCodeFrom from Entered by User in GUI
			verifier = genericUtility.getColumnValue("verifier", dom);
			// System.out.println("verifier ::"+verifier);

			if( !(isBomReplace))   // added by cpatil on 19/05/14 for bom replacement
			{
				siteCodeFrom = genericUtility.getColumnValue("site_code__from", dom);
				if (siteCodeFrom == null || siteCodeFrom.trim().length() == 0)
				{
					siteCodeFrom = "";
					//cpatil-25/08/14-System.out.println("Site Code From is Null...");
					errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
					return errString;
				}
				//cpatil-25/08/14-System.out.println("Site Code From............." + siteCodeFrom);
				// Fetching SiteCodeTo from Entered by User in GUI
				siteCodeTo = genericUtility.getColumnValue("site_code__to", dom);
				if (siteCodeTo == null || siteCodeTo.trim().length() == 0)
				{
					siteCodeTo = "";
					//cpatil-25/08/14-System.out.println("Site Code To is Null...");
					errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
					return errString;
				}
				//cpatil-25/08/14-System.out.println("Site Code To..............." + siteCodeTo);
				// Fetching ItemCodeFrom from Entered by User in GUI
				itemCodeFrom = genericUtility.getColumnValue("item_code__from", dom);
				if (itemCodeFrom == null || itemCodeFrom.trim().length() == 0)
				{
					itemCodeFrom = "";
					//cpatil-25/08/14-System.out.println("Item Code From is Null...");
					errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
					return errString;
				}
				//cpatil-25/08/14-System.out.println("Item Code From............." + itemCodeFrom);
				// Fetching ItemCodeTo from Entered by User in GUI
				itemCodeTo = genericUtility.getColumnValue("item_code__to", dom);
				if (itemCodeTo == null || itemCodeTo.trim().length() == 0)
				{
					itemCodeTo = "";
					//cpatil-25/08/14-System.out.println("Item Code To is Null...");
					errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
					return errString;
				}
				//cpatil-25/08/14-System.out.println("Item Code To............." + itemCodeTo);
			}
			// Fetching DateFrom from Entered by User in GUI
			sDateFrom = genericUtility.getColumnValue("date_from", dom);
			if (sDateFrom == null || sDateFrom.trim().length() == 0)
			{
				sDateFrom = "";
				//cpatil-25/08/14-System.out.println("From Date is Null...");
				errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
				return errString;
			}

			//cpatil-25/08/14-System.out.println("From Date............." + sDateFrom);
			// Fetching dateTo from Entered by User in GUI
			sDateTo = genericUtility.getColumnValue("date_to", dom);

			if (sDateTo == null || sDateTo.trim().length() == 0)
			{
				sDateTo = "";
				//cpatil-25/08/14-System.out.println("To Date is Null...");
				errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
				return errString;
			}

			//cpatil-25/08/14-System.out.println("To Date............." + sDateTo);
			// Fetching ItemSerFrom from Entered by User in GUI
			itemSerFrom = genericUtility.getColumnValue("item_ser__from", dom);
			if (itemSerFrom == null || itemSerFrom.trim().length() == 0)
			{
				itemSerFrom = "";
				//cpatil-25/08/14-System.out.println("From Item Series is Null...");
				errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
				return errString;
			}
			//cpatil-25/08/14-System.out.println("Item Series From............." + itemSerFrom);
			// Fetching ItemSerTo from Entered by User in GUI
			itemSerTo = genericUtility.getColumnValue("item_ser__to", dom);
			if (itemSerTo == null || itemSerTo.trim().length() == 0)
			{
				itemSerTo = "";
				//cpatil-25/08/14-System.out.println("Item Series To is Null...");
				errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
				return errString;
			}
			//cpatil-25/08/14-System.out.println("To Item Series............." + itemSerTo);

			// Fetching DisPlan from Entered by User in GUI
			disPlan = genericUtility.getColumnValue("dis_plan", dom);
			//cpatil-25/08/14-System.out.println("Dis Plan............." + disPlan);
			if (disPlan == null || disPlan.trim().length() == 0)
			{
				disPlan = "";
				//cpatil-25/08/14-System.out.println("Dis Plan is Null...");
				errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
				return errString;
			}
			//cpatil-25/08/14-System.out.println("Dis Plan............." + disPlan);
			// Fetching MfgPlan from Entered by User in GUI
			mfgPlan = genericUtility.getColumnValue("mfg_plan", dom);
			if (mfgPlan == null || mfgPlan.trim().length() == 0)
			{
				mfgPlan = "";
				//cpatil-25/08/14-System.out.println("Mfg Plan is Null...");
				errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
				return errString;
			}
			//cpatil-25/08/14-System.out.println("Mfg Plan............." + mfgPlan);
			// Fetching MatPlan from Entered by User in GUI
			matPlan = genericUtility.getColumnValue("mat_plan", dom);
			if (matPlan == null || matPlan.trim().length() == 0)
			{
				matPlan = "";
				//cpatil-25/08/14-System.out.println("Mat Plan is Null...");
				errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
				return errString;
			}
			//cpatil-25/08/14-System.out.println("Mat Plan............." + matPlan);

			processCycleString = genericUtility.getColumnValue("process_cycle", dom);
			if (processCycleString == null || processCycleString.trim().length() == 0)
			{
				//cpatil-25/08/14-System.out.println("Process Cycle is Null...");
				errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
				return errString;
			}
			try
			{
				processCycle = Integer.parseInt(processCycleString);
			} catch (Exception e)
			{
				processCycle = 1;
			}
			//cpatil-25/08/14-System.out.println("Process Cycle............." + processCycle);

			// Fetching Made To Stock from Entered by User in GUI
			madeToStock = genericUtility.getColumnValue("made_to_stock", dom);
			if (madeToStock == null || madeToStock.trim().length() == 0)
			{
				madeToStock = "";
				//cpatil-25/08/14-System.out.println("Made To Stock is Null...");
				errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
				return errString;
			}
			//cpatil-25/08/14-System.out.println("Made To Stock............." + madeToStock);

			// Fetching Made To Oerder from Entered by User in GUI
			madeToOrder = genericUtility.getColumnValue("made_to_order", dom);
			if (madeToOrder == null || madeToOrder.trim().length() == 0)
			{
				madeToOrder = "";
				//cpatil-25/08/14-System.out.println("Made To Order is Null...");
				errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
				return errString;
			}
			//cpatil-25/08/14-System.out.println("Made To Order............." + madeToOrder);

			// Fetching Balance Intersite from Entered by User in GUI
			balIntersite = genericUtility.getColumnValue("balance_intersite", dom);
			if (balIntersite == null || balIntersite.trim().length() == 0)
			{
				balIntersite = "";
				//cpatil-25/08/14-System.out.println("Balance Intersite is Null...");
				errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
				return errString;
			}
			genIndent = genericUtility.getColumnValue("gen_ind", dom);
			if (genIndent == null || genIndent.trim().length() == 0)
			{
				genIndent = "";
				//cpatil-25/08/14-System.out.println("Generate Indent is Null...");
				errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
				return errString;
			}
			//cpatil-25/08/14-System.out.println("Generate Indent............." + genIndent);

			// 19-12-2005 manoharan convert string date to sql timestamp
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getDBDateFormat());
			if( !(isBomReplace))  // added by cpatil on 19/05/14 for bomreplacement
			{
				dbDateFrom = sDateFrom;
				dbDateTo = sDateTo;
				sDateFrom = genericUtility.getValidDateString(sDateFrom, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
				dbDateFrom = genericUtility.getValidDateString(dbDateFrom, genericUtility.getApplDateFormat(), "dd-MMM-yyyy");
				//cpatil-25/08/14-System.out.println("sDateFrom : " + sDateFrom);
				// //cpatil-25/08/14-System.out.println();
				dateFrom = java.sql.Timestamp.valueOf(sDateFrom + " 00:00:00");
				sDateTo = genericUtility.getValidDateString(sDateTo, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
				dbDateTo = genericUtility.getValidDateString(dbDateTo, genericUtility.getApplDateFormat(), "dd-MMM-yyyy");
				dateTo = java.sql.Timestamp.valueOf(sDateTo + " 00:00:00");
				//cpatil-25/08/14-System.out.println("Db Date from :" + dbDateFrom);
				//cpatil-25/08/14-System.out.println("Db Date to   :" + dbDateTo);
				//SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getDBDateFormat());
				dateFromString = simpleDateFormat.format(dateFrom);
				dateToString = simpleDateFormat.format(dateTo);
				//cpatil-25/08/14-System.out.println("Db Date from [Timestamp]:" + dateFrom);
				//cpatil-25/08/14-System.out.println("Db Date to   [Timestamp]:" + dateTo);
				//cpatil-25/08/14-System.out.println("Db Date from [Timestamp : yyyy-MM-dd]:" + dateFromString);
				//cpatil-25/08/14-System.out.println("Db Date to   [Timestamp : yyyy-MM-dd]:" + dateToString);
			}
			else
			{
				sDateFrom = genericUtility.getColumnValue("date_from", dom);
				sDateTo = genericUtility.getColumnValue("date_to", dom);

				dbDateFrom = sDateFrom;
				dbDateTo = sDateTo;
				sDateFrom = genericUtility.getValidDateString(sDateFrom, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
				dbDateFrom = genericUtility.getValidDateString(dbDateFrom, genericUtility.getApplDateFormat(), "dd-MMM-yyyy");
				//cpatil-25/08/14-System.out.println("sDateFrom : " + sDateFrom);
				// //cpatil-25/08/14-System.out.println();
				dateFrom = java.sql.Timestamp.valueOf(sDateFrom + " 00:00:00");
				sDateTo = genericUtility.getValidDateString(sDateTo, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
				dbDateTo = genericUtility.getValidDateString(dbDateTo, genericUtility.getApplDateFormat(), "dd-MMM-yyyy");
				dateTo = java.sql.Timestamp.valueOf(sDateTo + " 00:00:00");
				//cpatil-25/08/14-System.out.println("Db Date from :" + dbDateFrom);
				//cpatil-25/08/14-System.out.println("Db Date to   :" + dbDateTo);

				dateFromString = simpleDateFormat.format(dateFrom);
				dateToString = simpleDateFormat.format(dateTo);
				//cpatil-25/08/14-System.out.println("Db Date from [Timestamp]:" + dateFrom);
				//cpatil-25/08/14-System.out.println("Db Date to   [Timestamp]:" + dateTo);
				//cpatil-25/08/14-System.out.println("Db Date from [Timestamp : yyyy-MM-dd]:" + dateFromString);
				//cpatil-25/08/14-System.out.println("Db Date to   [Timestamp : yyyy-MM-dd]:" + dateToString);

			}

			// end 19-12-2005 manoharan string converted to timestamp
			// 01-10-2007 manoharan
			sRunDate = genericUtility.getColumnValue("run_date", dom);
			if (sRunDate == null || sRunDate.trim().length() == 0)
			{
				sRunDate = "";
				//cpatil-25/08/14-System.out.println("Run Date is Null...");
				errString = itmDBAccessEJB.getErrorString("", "VTMRPPARM", "", "", conn);
				return errString;
			}
			//cpatil-25/08/14-System.out.println("Run Date............." + sRunDate);

			dbRunDate = genericUtility.getValidDateString(sRunDate, genericUtility.getApplDateFormat(), "dd-MMM-yyyy");
			sRunDate = genericUtility.getValidDateString(sRunDate, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
			runDate = java.sql.Timestamp.valueOf(sRunDate + " 00:00:00");
			runDateString = simpleDateFormat.format(runDate);
			// end 01-10-2007 manoharan
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :process(Document dom, Document dom2, String windowName, String xtraParams):" + e.getMessage() + ":");
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString;
	}

	// Populating Common Parameters i.e. :

	private String populateCommonParameters() throws ITMException
	{
		String mrpClubbingHorizonString = "";
		String expediateDaysString = null;
		Statement stmt = null;
		String sql = "";
		ResultSet rs = null;
		errString = "";
		ArrayList arrStdOrdType = null;
		System.out.println("Database Name:........." + CommonConstants.DB_NAME);
		try
		{
			stmt = conn.createStatement();
			standingOrdTypes = itmDBAccessEJB.getEnvDis("999999", "STANDING_ORDTYPES", conn);
			if (standingOrdTypes.equals("NULLFOUND"))
			{
				standingOrdTypes = "";
			}
			//cpatil-25/08/14-System.out.println("standingOrdTypes:............." + standingOrdTypes);

			// ***** standingOrdTypes to be changed to make an in ()
			// e.g original value will be R,S,JW, etc.
			// to convert in the form of "'R','S','JW'"

			arrStdOrdType = genericUtility.getTokenList(standingOrdTypes, ",");
			standingOrdTypes = "";
			for (int index = 0; index < arrStdOrdType.size(); index++)
			{
				if (index == arrStdOrdType.size() - 1)
				{
					standingOrdTypes = standingOrdTypes.concat("'").concat((String) arrStdOrdType.get(index)).concat("'");
				} else
				{
					standingOrdTypes = standingOrdTypes.concat("'").concat((String) arrStdOrdType.get(index)).concat("',");
				}
			}
			//cpatil-25/08/14-System.out.println("New Str Ord Type :" + standingOrdTypes);

			sql = "SELECT VAR_VALUE FROM MFGPARM WHERE PRD_CODE ='999999' AND VAR_NAME ='MRP_EXPEDIATE'";

			rs = stmt.executeQuery(sql);
			if (rs.next())
			{
				if (rs.getString(1) == null)
					mrpExpediate = "N";
				else
					mrpExpediate = rs.getString(1);
			}
			//cpatil-25/08/14-System.out.println("MrpExpediate:................." + mrpExpediate);
			rs.close();

			sql = "SELECT VAR_VALUE FROM MFGPARM WHERE PRD_CODE ='999999' AND VAR_NAME ='EXPEDIATE_DAYS'";

			rs = stmt.executeQuery(sql);
			if (rs.next())
			{
				if (rs.getString(1) == null)
					expediateDaysString = "0";
				else
					expediateDaysString = rs.getString(1);
			}
			if (expediateDaysString.equals("NULLFOUND") || expediateDaysString == null)
			{
				expediateDaysString = "0";
			}
			try
			{
				expediateDays = Integer.parseInt(expediateDaysString);
			} catch (NumberFormatException e)
			{
				expediateDays = 0;
			}
			//cpatil-25/08/14-System.out.println("Expediate Days :..............." + expediateDays);
			rs.close();

			sql = "SELECT VAR_VALUE FROM MFGPARM WHERE PRD_CODE ='999999' AND VAR_NAME ='MRP_TRACK_TRANID'";

			rs = stmt.executeQuery(sql);
			if (rs.next())
			{
				if (rs.getString(1) == null)
					mrpTrackTranId = "N";
				else
					mrpTrackTranId = rs.getString(1);
			}
			//cpatil-25/08/14-System.out.println("mrpTrackTranId:..............." + mrpTrackTranId);
			rs.close();

			mrpClubbingHorizonString = itmDBAccessEJB.getEnvDis("999999", "MRP_CLUBBING_HORIZON", conn);
			if (mrpClubbingHorizonString.equals("NULLFOUND"))
			{
				MrpClubbingHorizon = 0;
			} else
			{
				try
				{
					MrpClubbingHorizon = Integer.parseInt(mrpClubbingHorizonString);
				} catch (Exception e)
				{
					MrpClubbingHorizon = 0;
				}
			}
			//cpatil-25/08/14-System.out.println("MrpClubbingHorizon:..........." + MrpClubbingHorizon);

			mrpDynMinStk = itmDBAccessEJB.getEnvDis("999999", "MRP_DYN_MIN_STK", conn);
			if (mrpDynMinStk.equals("NULLFOUND"))
				mrpDynMinStk = "N";
			//cpatil-25/08/14-System.out.println("mrpDynMinStk:................." + mrpDynMinStk);

			roundReqTo = itmDBAccessEJB.getEnvDis("999999", "ROUND_REQ_TO", conn);
			if (roundReqTo.equals("NULLFOUND"))
				roundReqTo = "N";
			//cpatil-25/08/14-System.out.println("roundReqTo:................." + roundReqTo);

			minOrderChk = itmDBAccessEJB.getEnvDis("999999", "MIN_ORDER_CHK", conn);
			if (minOrderChk.equals("NULLFOUND"))
				minOrderChk = "N";
			//cpatil-25/08/14-System.out.println("minOrderChk:................." + minOrderChk);

			deptCodeMfg = itmDBAccessEJB.getEnvDis("999999", "DEPT_CODE_MFG", conn);
			if (deptCodeMfg.equals("NULLFOUND"))
			{
				errString = itmDBAccessEJB.getErrorString("", "VTMRPDEPT", "", "", conn);
				return errString;
			} else
			{
				sql = "SELECT COUNT(1) FROM DEPARTMENT WHERE DEPT_CODE = '" + deptCodeMfg + "'";
				rs = stmt.executeQuery(sql);
				if (rs.next() && rs.getInt(1) > 0)
				{
					//cpatil-25/08/14-System.out.println("Department Code Mfg [" + deptCodeMfg + "] exists in deparment master");
				} else
				{
					//cpatil-25/08/14-System.out.println("Department Code Mfg  [" + deptCodeMfg + "] not exists in deparment master");
					errString = itmDBAccessEJB.getErrorString("", "VTINVDEPT", "", "", conn);
				}
				rs.close();
			}
			//cpatil-25/08/14-System.out.println("deptCodeMfg:................." + deptCodeMfg);

			stmt.close();
		} catch (SQLException se)
		{
			System.out.println("SQLException :RunMRPPrcEJB :populateCommonParameters().." + se.getMessage());
			se.printStackTrace();
			errString = se.getMessage();
			throw new ITMException(se);
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :populateCommonParameters():...." + e.getMessage() + ":");
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			if (stmt != null)
			{
				stmt = null;
			}
			if (rs != null)
			{
				rs = null;
			}
			System.out.println("Error String :===> " + errString);
		}
		return errString; // moved here from finally block - Jiten - 03/11/06
	}

	// Populating Site Map

	private String populateSiteMap() throws ITMException
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "";
		int count = 0;
		try
		{
			sql = "SELECT DISTINCT ";
			sql = sql + "CASE WHEN SITE_CODE__PLAN IS NULL THEN SITE_CODE ELSE SITE_CODE__PLAN END ";
			sql = sql + "FROM SITEITEM ";
			sql = sql + "WHERE ";
			if(isRequirement)
			{
				sql = sql + "CASE WHEN SITE_CODE__PLAN IS NULL THEN SITE_CODE ELSE SITE_CODE__PLAN END  IN("+siteList+") ";
				pstmt = conn.prepareStatement(sql);
			}
			else
			{
				sql = sql + "CASE WHEN SITE_CODE__PLAN IS NULL THEN SITE_CODE ELSE SITE_CODE__PLAN END >= ? ";
				sql = sql + "AND CASE WHEN SITE_CODE__PLAN IS NULL THEN SITE_CODE ELSE SITE_CODE__PLAN END <= ?";

				pstmt = conn.prepareStatement(sql);
				if( !(isBomReplace))   //added by cpatil for bom replacement
				{
					pstmt.setString(1, siteCodeFrom);
					pstmt.setString(2, siteCodeTo);
				}
				else
				{
					pstmt.setString(1, siteCode1);
					pstmt.setString(2, siteCode1);
				}
				//pstmt = conn.prepareStatement(sql);
			} 

			rs = pstmt.executeQuery();

			while (rs.next())
			{
				count++;
				siteCodeMap.put(rs.getString(1), new Integer(count));
				// System.out.println(rs.getString(1));

			}

		} catch (SQLException se)
		{
			System.out.println("SQLException : RunMRPPrcEJB :populateSiteMap()" + se.getMessage());
			se.printStackTrace();
			errString = se.getMessage();
			throw new ITMException(se);
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :populateSiteMap():" + e.getMessage() + ":");
			this.errString = genericUtility.createErrorString(e);
			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)
			{
			}
		}
		return errString;// Moved here as finally block does not complete
		// normally - jiten 03/11/06
	}

	// Poulating Item code
	private String populateItemMap() throws ITMException
	{

		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "";
		Set setSite = siteCodeMap.entrySet();
		Iterator itrSite = setSite.iterator();
		String subQuery=" ";
		// System.out.println("Database Name:............"+CommonConstants.DB_NAME);
		try
		{
			//cpatil-25/08/14-System.out.println("@@@@@CommonConstants.DB_NAME["+CommonConstants.DB_NAME+"]::::::isDetailReq["+isDetailReq+"]");
			if(isDetailReq)
			{
				if ((CommonConstants.DB_NAME).equalsIgnoreCase("db2"))   /// added for db2 on 17/02/14
				{
					//subQuery=" AND C.ITEM_CODE IN ( SELECT ITEM_CODE__ORD FROM SORDDET  WHERE CONCAT (SALE_ORDER,ITEM_CODE) IN("+itemCodeList+") ) ";
					//subQuery=" AND C.ITEM_CODE IN ( SELECT ITEM_CODE__ORD FROM SORDDET  WHERE CONCAT (SALE_ORDER,ITEM_CODE) IN("+itemCodeList+") " +
					//		" UNION SELECT ITEM_CODE FROM MPS_ORDER  WHERE CONCAT (TRAN_ID,ITEM_CODE) IN("+itemCodeList+") ) ";
					subQuery=" and ( C.ITEM_CODE IN ("+itemCodeOnlyList+ ") OR C.ITEM_CODE IN( SELECT ITEM_CODE FROM MPS_ORDER  WHERE CONCAT (TRAN_ID,ITEM_CODE) IN ("+itemCodeList+") ) ) ";
					//	subQuery=" and  C.ITEM_CODE IN ( select "+itemCodeOnlyList+" from dual " +
					//" UNION SELECT ITEM_CODE FROM MPS_ORDER  WHERE CONCAT (TRAN_ID,ITEM_CODE) IN("+itemCodeList+") ) ";
				}
				else
				{
					//	subQuery=" AND C.ITEM_CODE IN(SELECT ITEM_CODE__ORD FROM SORDER WHERE SALE_ORDER IN("+sorderList+") ";
					//subQuery=" AND C.ITEM_CODE IN(SELECT ITEM_CODE__ORD FROM SORDDET WHERE SALE_ORDER||ITEM_CODE IN("+itemCodeList+")" +
					//		" UNION SELECT ITEM_CODE FROM MPS_ORDER WHERE TRAN_ID||ITEM_CODE IN("+itemCodeList+") )";
					//	subQuery=" and  C.ITEM_CODE IN ("+itemCodeOnlyList+ ") OR C.ITEM_CODE IN( SELECT ITEM_CODE FROM MPS_ORDER  WHERE CONCAT (TRAN_ID,ITEM_CODE) IN("+itemCodeList+") ) ";
					//	subQuery=" and  ( C.ITEM_CODE IN ( select "+itemCodeOnlyList+" from dual " +
					//			" UNION SELECT ITEM_CODE  FROM MPS_ORDER WHERE ( TRAN_ID||ITEM_CODE) IN ("+itemCodeList+") ) ) ";

					subQuery=" and ( C.ITEM_CODE IN ("+itemCodeOnlyList+ ") OR C.ITEM_CODE IN( SELECT ITEM_CODE FROM MPS_ORDER  WHERE CONCAT (TRAN_ID,ITEM_CODE) IN ("+itemCodeList+") ) ) ";	
				}
			}else if(isRequirement)
			{
				if ((CommonConstants.DB_NAME).equalsIgnoreCase("db2"))   /// chandrashekar added for Requirement wizard on 04/04/14
				{

					//subQuery=" AND C.ITEM_CODE IN(SELECT ITEM_CODE FROM SITEITEM WHERE CONCAT(SITE_CODE,ITEM_CODE) IN("+siteItemList+"))";
					subQuery=" AND CONCAT(A.SITE_CODE,A.ITEM_CODE)IN("+siteItemList+")";
				}
				else
				{ 
					subQuery=" AND (A.SITE_CODE||A.ITEM_CODE IN("+siteItemList+"))";

				}
			}

			if ((CommonConstants.DB_NAME).equalsIgnoreCase("db2"))
			{
				sql = "SELECT CASE WHEN C.ITEM_CODE__PLAN IS NULL THEN C.ITEM_CODE ELSE C.ITEM_CODE__PLAN END ITEM_CODE,";
				sql = sql + "CASE WHEN B.ITEM_CODE IS NULL THEN C.ITEM_SER ELSE ";
				sql = sql + "CASE WHEN B.VALID_UPTO IS NULL THEN B.ITEM_SER ELSE C.ITEM_SER END END ITEM_SER, A.MASTER_SCH ";
				sql = sql + "FROM SITEITEM A LEFT OUTER JOIN ITEMSER_CHANGE B ON A.ITEM_CODE = B.ITEM_CODE, ITEM C ";
				sql = sql + "WHERE A.ITEM_CODE = C.ITEM_CODE ";
				sql = sql + "AND C.ITEM_CODE >= ? ";
				sql = sql + "AND C.ITEM_CODE <= ? ";
				sql = sql + "AND A.SITE_CODE = ? ";
				sql = sql + "AND CASE WHEN A.MASTER_SCH IS NULL THEN 'Y' ELSE A.MASTER_SCH END  <> 'N' ";
				sql = sql + "AND B.VALID_UPTO IS NULL ";
				sql = sql + "AND C.ITEM_SER >=? ";
				sql = sql + "AND C.ITEM_SER <=? "+subQuery+"  ORDER BY ITEM_CODE ASC";
			} else
			{
				sql = "SELECT CASE WHEN C.ITEM_CODE__PLAN IS NULL THEN C.ITEM_CODE ELSE C.ITEM_CODE__PLAN END ITEM_CODE, ";
				sql = sql + "CASE WHEN B.ITEM_CODE IS NULL THEN C.ITEM_SER ELSE  ";
				sql = sql + "CASE WHEN B.VALID_UPTO IS NULL THEN B.ITEM_SER ELSE C.ITEM_SER END END ITEM_SER, A.MASTER_SCH ";
				sql = sql + "FROM SITEITEM A, ITEMSER_CHANGE B, ITEM C ";
				sql = sql + "WHERE A.ITEM_CODE = C.ITEM_CODE ";
				sql = sql + "AND A.ITEM_CODE = B.ITEM_CODE (+) ";
				sql = sql + "AND C.ITEM_CODE >= ? ";
				sql = sql + "AND C.ITEM_CODE <= ? ";
				sql = sql + "AND A.SITE_CODE = ? ";
				sql = sql + "AND CASE WHEN A.MASTER_SCH IS NULL THEN 'Y' ELSE A.MASTER_SCH END  <> 'N' ";
				sql = sql + "AND B.VALID_UPTO IS NULL ";
				sql = sql + "AND C.ITEM_SER >= ? ";
				sql = sql + "AND C.ITEM_SER <= ? "+subQuery+"  ORDER BY ITEM_CODE ASC";

			}

			System.out.println("@@@@@ sql :["+sql+"]");
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itemCodeFrom);
			pstmt.setString(2, itemCodeTo);
			pstmt.setString(4, itemSerFrom);
			pstmt.setString(5, itemSerTo);

			while (itrSite.hasNext())
			{
				Map.Entry siteMapEntry = (Map.Entry) itrSite.next();
				String siteCode = (String) siteMapEntry.getKey();

				pstmt.setString(3, siteCode);

				rs = pstmt.executeQuery();

				//cpatil-25/08/14-System.out.println("Populating item for site : " + siteCode);
				while (rs.next())
				{
					System.out.println("rs.getString(1)--" + rs.getString(1));
					if (itemCodeMap.containsKey(rs.getString(1)))
					{
						//cpatil-25/08/14-System.out.println("Item Code already exists : " + rs.getString(1));
					} else
					{
						itemCodeMap.put(rs.getString(1), new Integer(itemCodeMap.size() + 1));
						// System.out.println("Item Code added : "+rs.getString(1));
					}
				}
			}
		} catch (SQLException se)
		{
			System.out.println("SQLException : RunMRPPrcEJB :populateItemMap()" + se.getMessage());
			se.printStackTrace();
			errString = se.getMessage();
			throw new ITMException(se);
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :populateItemMap():" + e.getMessage() + ":");
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			try
			{
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
			} catch (Exception e)
			{
			}
		}
		return errString;// Moved here as finally block does not complete
		// normally - Jiten - 03/11/06
	}

	// Populating All Items

	private String populateAllItem() throws ITMException
	{
		String bomCode = "";
		String suppSour = "";
		Set setSite = siteCodeMap.entrySet();
		Set setItem = itemCodeMap.entrySet();

		Iterator itrItem = setItem.iterator();
		ArrayList itemArr = new ArrayList();

		int count = 0;

		while (itrItem.hasNext())
		{
			Map.Entry itemMapEntry = (Map.Entry) itrItem.next();
			itemArr.add((String) itemMapEntry.getKey());
		}
		Iterator itrSite = setSite.iterator();
		try
		{

			while (itrSite.hasNext())
			{
				Map.Entry siteMapEntry = (Map.Entry) itrSite.next();
				if (isBomReplace)
				{
					System.out.println("12/06/14 manohar itemArr.size() [" + itemArr.size() + "]");
				}
				// (String)siteMapEntry.getKey());
				int ctr;
				for (ctr = 0; ctr < itemArr.size(); ctr++)
				{
					//cpatil-25/08/14-System.out.println("(String)itemArr.get(ctr)--" + (String) itemArr.get(ctr));
					suppSour = getSuppSour((String) siteMapEntry.getKey(), (String) itemArr.get(ctr));
					suppSour = suppSour.trim();
					bomCode = getBomCode((String) siteMapEntry.getKey(), (String) itemArr.get(ctr));
					//cpatil-25/08/14-System.out.println("SuppSour---" + suppSour + "bomCode--" + bomCode);
					// //cpatil-25/08/14-System.out.println("populateAllItem(): Supp_Sour:..." +
					// suppSour + "   Bom Code:..." + bomCode);
					if (((suppSour != null) && (!suppSour.equals("P"))) && (bomCode != null))
					{
						Set levelBom = new HashSet();
						level = 1;
						levelBom.add(bomCode);
						hmap.put(new Integer(level), levelBom);
						// itemHashMap.put( (String)itemArr.get(ctr), new
						// Integer(count) );
						//cpatil-25/08/14-System.out.println("itemArr.get(ctr)--" + itemArr.get(ctr));
						itemList.add((String) itemArr.get(ctr));
						// System.out.println("Exploding BOM for site : " +
						// (String)siteMapEntry.getKey() + " Item : " +
						// (String)itemArr.get(ctr) + " BOM : " + bomCode);
						// Added by Jiten 07/11/06
						cyclicItem.bomCode = bomCode;
						cyclicItem.itemCode = (String) itemArr.get(ctr);
						cyclicItem.siteCode = (String) siteMapEntry.getKey();
						// end

						validBomItemCode = cyclicItem.itemCode; // 19-01-2007
						// manoharan
						cyclicCheck = new HashSet();
						errString = bomExplode((String) siteMapEntry.getKey(), bomCode);
						itemHashMap.clear();
						if (errString != null && errString.trim().length() > 0)
						{
							//cpatil-25/08/14-System.out.println("Error While Calling method bomExplode(String, String):..." + errString);
							return errString;
						}
						level = 0;
						hmap.clear();
					}
				}
				itemList.clear();

			}
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :populateAllItem()");
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		}
		return errString;
	}

	public String bomExplode(String siteCode, String bomCode) throws ITMException
	{
		// PreparedStatement pstmt = null;
		Statement pstmt = null;
		PreparedStatement pstmtInner1 = null;
		PreparedStatement pstmtInner2 = null;
		ResultSet rsCount = null;
		String sql = "", sqlInner1 = "", sqlInner2 = "";
		ResultSet rs = null, rsInner1 = null, rsInner2 = null;
		String innerSuppSour = null;
		String innerBomCode = null;

		PreparedStatement pstmtValidBom = null;
		String sqlValidBom = "SELECT CONFIRMED, ACTIVE,ITEM_CODE FROM BOM WHERE BOM_CODE = ?";
		ResultSet rsValidBom = null;
		boolean bomExists = false;
		String logMsg = null;
		String confirmedBom = null;
		String activeBom = null;
		ArrayList<String > al=null;
		//Added by Manoj dtd 30/04/2014 to add Alternate items in list
		PreparedStatement pstmt1=null;
		ResultSet rs1=null;
		String bomItem="";
		try
		{

			// 19-01-2007 manoharan
			// check whether the bom is valid should be confirmed and active
			pstmtValidBom = conn.prepareStatement(sqlValidBom);
			pstmtValidBom.setString(1, bomCode);
			rsValidBom = pstmtValidBom.executeQuery();
			bomExists = false;
			while (rsValidBom.next())
			{
				bomExists = true;
				confirmedBom = rsValidBom.getString(1);
				activeBom = rsValidBom.getString(2);
				bomItem= rsValidBom.getString(3);
			}
			//cpatil-25/08/14-System.out.println("confirmedBom---"+confirmedBom+"---activeBom---"+activeBom);
			rsValidBom.close();
			pstmtValidBom.close();
			// this.fwInvalidBom.write("Site Code	 Item Code	 Bom Code   Message\r\n");
			if (confirmedBom == null || confirmedBom.trim().length() == 0 || confirmedBom.equalsIgnoreCase("N") || activeBom == null || activeBom.trim().length() == 0 || activeBom.equalsIgnoreCase("N"))
			{
				siteCode = (siteCode.trim() + "     ").substring(0, 5);
				validBomItemCode = (validBomItemCode.trim() + "          ").substring(0, 10);
				bomCode = (bomCode.trim() + "          ").substring(0, 10);
				logMsg = siteCode + "      " + validBomItemCode + "  " + bomCode + "  ";
				// ========= ========== ========== ========
				if (confirmedBom == null || confirmedBom.trim().length() == 0 || confirmedBom.equalsIgnoreCase("N"))
				{
					logMsg = logMsg + "BOM not confirmed";
				}
				if (activeBom == null || activeBom.trim().length() == 0 || activeBom.equalsIgnoreCase("N"))
				{
					logMsg = logMsg + " BOM not active";
				}
				invaldBomExists = true;
				this.fwInvalidBom.write(logMsg + "\r\n");
			}

			// end 19-01-2007 manoharan
			Set levelBom = new HashSet();
			sql = "SELECT DISTINCT CASE WHEN ITEM.ITEM_CODE__PLAN IS NULL THEN ITEM.ITEM_CODE ELSE ITEM.ITEM_CODE__PLAN END " + " FROM BOMDET, ITEM " + " WHERE ITEM.ITEM_CODE = BOMDET.ITEM_CODE " + " AND BOMDET.BOM_CODE = '" + bomCode + "'";
			// pstmt = conn.prepareStatement(sql);
			System.out.println(sql);
			pstmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
			// pstmt.setString(1,bomCode);
			rs = pstmt.executeQuery(sql);
			int ctr = 0;

			while (rs.next())
			{
				System.out.println("rs.getString(1)----" + rs.getString(1));
				levelBom.add(rs.getString(1));
				ctr = 1;

				//Added by Manoj dtd 30/04/2014 to add Alternate items in list
				if(isDetailReq)
				{
					//120115	

					pstmt1=conn.prepareStatement("SELECT DISTINCT ITEM_CODE__ALT,QUANTITY FROM BOM_ALT WHERE BOM_CODE=? AND ITEM_CODE=? AND CONFIRMED = 'Y' AND ACTIVE_YN= 'Y' ");
					pstmt1.setString(1, bomCode);
					pstmt1.setString(2, rs.getString(1));
					rs1=pstmt1.executeQuery();
					while(rs1.next())
					{

						if(altitemMap.containsKey(rs.getString(1)))
						{
							al=altitemMap.get(rs.getString(1));
						}
						else
						{
							al=new ArrayList<String>();
						}

						al.add(rs1.getString(1)+"@"+rs1.getString(2));
						altitemMap.put(rs.getString(1), al);

						itemBomMap.put(rs.getString(1), bomCode);
						Set<String> bomSet=new HashSet<String>();
						Set<String> itemSet=new HashSet<String>();

						if(itemBomMap1.size()>0)
						{
							if(itemBomMap1.containsKey(itemCodeTo))	
							{
								bomSet=itemBomMap1.get(itemCodeTo);
								bomSet.add(bomCode);
							}
							else
							{
								bomSet=new HashSet<String>(); 
								bomSet.add(bomCode);
							}
						}
						else
						{
							bomSet=new HashSet<String>(); 
							bomSet.add(bomCode);
						}
						itemBomMap1.put(itemCodeTo, bomSet);
						///////////////////////////////////////
						if(itemBomMap2.size()>0)
						{
							if(itemBomMap2.containsKey(itemCodeTo))	
							{
								itemSet=itemBomMap2.get(itemCodeTo);
								itemSet.add(bomItem);
							}
							else
							{
								itemSet=new HashSet<String>(); 
								itemSet.add(bomItem);
							}
						}
						else
						{
							itemSet=new HashSet<String>(); 
							itemSet.add(bomItem);
						}
						itemBomMap2.put(itemCodeTo, itemSet);

						//////////////////////////////////////////////
						//cpatil-25/08/14-System.out.println("1347---altitemMap.size()----"+altitemMap.size()+"----"+al.get(0)+"---altitemMap---"+altitemMap);
						//cpatil-25/08/14-System.out.println("1374---itemBomMap.size()----"+itemBomMap.size()+"---itemBomMap---"+itemBomMap);
						//al.clear();

						String parentBom = itemCodeDetailMap.get(rs.getString(1)) == null ? "":itemCodeDetailMap.get(rs.getString(1)).toString();
						itemCodeDetailMap.put(rs.getString(1), parentBom+"@"+bomCode);
						//cpatil-25/08/14-System.out.println("@@@@ itemCodeDetailMap 1492["+itemCodeDetailMap+"]");

						String sourceItem = setDescription("item_code", "bom", "bom_code", bomCode, conn);
						parentItemMap.put(rs.getString(1), sourceItem );   //18/06/14
						//cpatil-25/08/14-System.out.println("@@@@ 1552 : sourceItem["+sourceItem+"]bomCode["+bomCode+"]parentItemMap["+parentItemMap+"]");

					}
					rs1.close();
					rs1=null;
					pstmt1.close();
					pstmt1=null;
					System.out.println("altitemMap["+altitemMap+"]");

				}
				//Ended by Manoj dtd 30/04/2014 to add Alternate items in list

			}
			level = level + ctr;
			hmap.put(new Integer(level), levelBom);
			//cpatil-25/08/14-System.out.println("level--" + level);
			for (int i = 1; i < level; i++)
			{
				//cpatil-25/08/14-System.out.println("Level Loop Entered---" + i + "---" + hmap.size());
				levelBom = (HashSet) hmap.get(new Integer(i));
				//cpatil-25/08/14-System.out.println("Level Loop Entered---" + i + "---" + levelBom.size());
				Iterator it = levelBom.iterator();
				while (it.hasNext())
				{
					System.out.println("SET Value---" + it.next().toString());
				}
			}
			rs.beforeFirst();
			while (rs.next())
			{

				// System.out.println("Item Code : "+rs.getString(1));
				// 14/06/14 manoharan in case of changing bom_code itemCodeMap is not populated so populate the same 
				//if( isBomReplace )  
				//{
				if (itemCodeMap.containsKey(rs.getString(1)))
				{
					//cpatil-25/08/14-System.out.println("14/06/14 supreme isBomReplace [" + isBomReplace + "] itemCodeMap already contains [" + rs.getString(1) + "]");
				} 
				//else
				//{
				itemCodeMap.put(rs.getString(1), new Integer(itemCodeMap.size() + 1));
				/*
					if(itemBomMap.containsKey(rs.getString(1)) )
					{
						ArrayList tempList = itemBomMap.get(rs.getString(1));
						tempList.add(bomCode);
						itemBomMap.put(rs.getString(1), tempList);
					}
					else
					{	
						ArrayList tempList = new ArrayList();
						tempList.add(bomCode);
						itemBomMap.put(rs.getString(1), tempList);
					}
				 */
				itemBomMap.put(rs.getString(1), bomCode);
				Set<String> bomSet=new HashSet<String>();
				if(itemBomMap1.size()>0)
				{
					if(itemBomMap1.containsKey(rs.getString(1)))	
					{
						bomSet=itemBomMap1.get(rs.getString(1));
						bomSet.add(bomCode);
					}
					else
					{
						System.out.println("1889--itemCodeTo["+rs.getString(1)+"]bomCode["+bomCode+"]");
						bomSet=new HashSet<String>(); 
						bomSet.add(bomCode);
					}
				}
				else
				{
					System.out.println("1896--itemCodeTo["+rs.getString(1)+"]bomCode["+bomCode+"]");
					bomSet=new HashSet<String>(); 
					bomSet.add(bomCode);
				}
				itemBomMap1.put(rs.getString(1), bomSet);
				String parentBom = itemCodeDetailMap.get(rs.getString(1)) == null ? "":itemCodeDetailMap.get(rs.getString(1)).toString();
				itemCodeDetailMap.put(rs.getString(1), parentBom+"@"+bomCode);

				//cpatil-25/08/14-System.out.println();
				String sourceItem = setDescription("item_code", "bom", "bom_code", bomCode, conn);
				parentItemMap.put(rs.getString(1), sourceItem );   //18/06/14
				//cpatil-25/08/14-System.out.println("@@@@ 1589 : sourceItem["+sourceItem+"]bomCode["+bomCode+"]parentItemMap["+parentItemMap+"]");

				//cpatil-25/08/14-System.out.println("14/06/14 supreme isBomReplace [" + isBomReplace + "] itemCodeMap added with [" + rs.getString(1) + "] itemCodeDetailMap [" + itemCodeDetailMap + "]");
				//}
				//}
				sqlInner1 = "SELECT COUNT(1) FROM ITEM WHERE ITEM_CODE = ?";
				pstmtInner1 = conn.prepareStatement(sqlInner1);
				pstmtInner1.setString(1, rs.getString(1));
				rsCount = pstmtInner1.executeQuery();
				// rsCount =
				// stmt.executeQuery("SELECT COUNT(1) FROM ITEM WHERE ITEM_CODE = '"
				// + rs.getString(1) + "'");
				if (rsCount.next() && rsCount.getInt(1) > 0)
				{
					rsCount.close();
					pstmtInner1.close();
					// Add ItemCode in ItemCodeMap if it not present earlier
					innerSuppSour = getSuppSour(siteCode, rs.getString(1));
					innerBomCode = getBomCode(siteCode, rs.getString(1));
					//cpatil-25/08/14-System.out.println("innerBomCode---------" + innerBomCode);
					// //cpatil-25/08/14-System.out.println("bomExplode Function :: Site Code :: "+siteCode+"Bom Code ::"+bomCode+"Item Code ::"+rs.getString(1));
					boolean isCyclic = false;
					//cpatil-25/08/14-System.out.println("innerSuppSour-----" + innerSuppSour + "----innerBomCode----" + innerBomCode);
					if (((innerSuppSour != null) && (!innerSuppSour.equals("P"))) && (innerBomCode != null))
					{

						for (int i = 1; i < level; i++)
						{

							levelBom = (HashSet) hmap.get(new Integer(i));
							//cpatil-25/08/14-System.out.println("levelBom.contains(rs.getString(1))--" + level + "---" + i + "---" + levelBom.size() + "--" + levelBom.contains(rs.getString(1)));
							if (levelBom.size() > 0 && levelBom.contains(rs.getString(1)))
							{
								//cpatil-25/08/14-System.out.println("levelBom.contains(rs.getString(1))--" + levelBom.contains(rs.getString(1)));

								// Added by Jiten 07/11/06//
								if (verifier != null && verifier.equalsIgnoreCase("Y"))
								{
									this.fw.write(cyclicItem.siteCode + "		" + cyclicItem.bomCode + "		" + cyclicItem.itemCode + "		" + rs.getString(1) + "\r\n");
									//cpatil-25/08/14-System.out.println("Cyclic Item Code is : " + rs.getString(1));
								} else
								{
									//cpatil-25/08/14-System.out.println("Cyclic Item Code is : " + rs.getString(1));
									errString = itmDBAccessEJB.getErrorString("", "VTMRPITEME", "", "", conn);
									rs.close();
									pstmt.close();
									return errString;
								}
								isCyclic = true;
							}

							//cpatil-25/08/14-System.out.println("manohar 14/01/12 checking item existance in  itemCodeMap-------" + rs.getString(1));
							if (!itemCodeMap.containsKey(rs.getString(1)))
							{
								//cpatil-25/08/14-System.out.println("manohar 14/01/12 Placing value in itemCodeMap-------" + rs.getString(1));
								itemCodeMap.put(rs.getString(1), new Integer(itemCodeMap.size() + 1));
								/*
								if(itemBomMap.containsKey(rs.getString(1)) )
								{
									ArrayList tempList = itemBomMap.get(rs.getString(1));
									tempList.add(bomCode);
									itemBomMap.put(rs.getString(1), tempList);
								}
								else
								{	
									ArrayList tempList = new ArrayList();
									tempList.add(bomCode);
									itemBomMap.put(rs.getString(1), tempList);
								}
								 */
								itemBomMap.put(rs.getString(1), bomCode);
								bomSet=new HashSet<String>();
								if(itemBomMap1.size()>0)
								{
									if(itemBomMap1.containsKey(rs.getString(1)))	
									{
										bomSet=itemBomMap1.get(rs.getString(1));
										bomSet.add(bomCode);
									}
									else
									{
										System.out.println("1988--itemCodeTo["+rs.getString(1)+"]bomCode["+bomCode+"]");
										bomSet=new HashSet<String>(); 
										bomSet.add(bomCode);
									}
								}
								else
								{
									System.out.println("1995--itemCodeTo["+rs.getString(1)+"]bomCode["+bomCode+"]");
									bomSet=new HashSet<String>(); 
									bomSet.add(bomCode);
								}
								itemBomMap1.put(rs.getString(1), bomSet);
								parentBom = itemCodeDetailMap.get(rs.getString(1)) == null ? "":itemCodeDetailMap.get(rs.getString(1)).toString();
								itemCodeDetailMap.put(rs.getString(1), parentBom+"@"+bomCode);

								sourceItem = setDescription("item_code", "bom", "bom_code", bomCode, conn);
								parentItemMap.put(rs.getString(1), sourceItem );   //18/06/14
								//cpatil-25/08/14-System.out.println("@@@@ 1661 : sourceItem["+sourceItem+"]bomCode["+bomCode+"]parentItemMap["+parentItemMap+"]");
								//cpatil-25/08/14-System.out.println("@@@@ itemCodeDetailMap 1575["+itemCodeDetailMap+"]");
							} else
							{
								//cpatil-25/08/14-System.out.println("manohar 14/01/12 already in itemCodeMap-------" + rs.getString(1));
							}

						}
					} else
					{
						//cpatil-25/08/14-System.out.println("manohar 14/01/12 checking item existance in  itemCodeMap material -------" + rs.getString(1));
						if (!itemCodeMap.containsKey(rs.getString(1)))
						{
							//cpatil-25/08/14-System.out.println("manohar 14/01/12 Placing value in itemCodeMap-------material" + rs.getString(1));
							itemCodeMap.put(rs.getString(1), new Integer(itemCodeMap.size() + 1));
							/*
							if(itemBomMap.containsKey(rs.getString(1)) )
							{
								ArrayList tempList = itemBomMap.get(rs.getString(1));
								tempList.add(bomCode);
								itemBomMap.put(rs.getString(1), tempList);
							}
							else
							{	
								ArrayList tempList = new ArrayList();
								tempList.add(bomCode);
								itemBomMap.put(rs.getString(1), tempList);
							}
							 */
							itemBomMap.put(rs.getString(1), bomCode);
							bomSet=new HashSet<String>();
							if(itemBomMap1.size()>0)
							{
								if(itemBomMap1.containsKey(rs.getString(1)))	
								{
									bomSet=itemBomMap1.get(rs.getString(1));
									bomSet.add(bomCode);
								}
								else
								{
									System.out.println("2045--itemCodeTo["+rs.getString(1)+"]bomCode["+bomCode+"]");
									bomSet=new HashSet<String>(); 
									bomSet.add(bomCode);
								}
							}
							else
							{
								System.out.println("2052--itemCodeTo["+rs.getString(1)+"]bomCode["+bomCode+"]");
								bomSet=new HashSet<String>(); 
								bomSet.add(bomCode);
							}
							itemBomMap1.put(rs.getString(1), bomSet);
							parentBom = itemCodeDetailMap.get(rs.getString(1)) == null ? "":itemCodeDetailMap.get(rs.getString(1)).toString();
							itemCodeDetailMap.put(rs.getString(1), parentBom+"@"+bomCode);

							sourceItem = setDescription("item_code", "bom", "bom_code", bomCode, conn);
							parentItemMap.put(rs.getString(1), sourceItem );   //18/06/14
							//cpatil-25/08/14-System.out.println("@@@@ 1682 : sourceItem["+sourceItem+"]bomCode["+bomCode+"]parentItemMap["+parentItemMap+"]");

							//cpatil-25/08/14-System.out.println("@@@@ itemCodeDetailMap 1592["+itemCodeDetailMap+"]");


						} else
						{
							//cpatil-25/08/14-System.out.println("manohar 14/01/12 already in itemCodeMap-------material" + rs.getString(1));
						}
					}
					if (((innerSuppSour != null) && (!innerSuppSour.equals("P"))) && (innerBomCode != null) && (isCyclic == false))
					{
						// //cpatil-25/08/14-System.out.println("Inner Exploding BOM for site : "
						// + siteCode + " Item : " + rs.getString(1) + " BOM : "
						// + innerBomCode);
						validBomItemCode = rs.getString(1);
						errString = bomExplode(siteCode, innerBomCode);

						if (errString != null && errString.trim().length() > 0)
						{
							System.out.println("Error While Calling method bomExplode(String, String):..." + errString);
							rs.close();
							pstmt.close();
							return errString;
						}
					}

				} else
				{
					rsCount.close();
					sqlInner2 = "SELECT COUNT(1) FROM BOM WHERE BOM_CODE = ?";
					pstmtInner2 = conn.prepareStatement(sqlInner2);
					pstmtInner2.setString(1, rs.getString(1));
					rsCount = pstmtInner2.executeQuery();
					// rsCount =
					// stmt.executeQuery("SELECT COUNT(1) FROM BOM WHERE BOM_CODE = '"
					// + rs.getString(1) + "'");
					if (rsCount.next() && rsCount.getInt(1) > 0)
					{
						rsCount.close();
						pstmtInner2.close();
						validBomItemCode = "BOMDET:" + rs.getString(1);
						errString = bomExplode(siteCode, rs.getString(1));
						if (errString != null && errString.trim().length() > 0)
						{
							System.out.println("Error While Calling method bomExplode(String, String):..." + errString);
							rs.close();
							pstmt.close();
							return errString;
						}
					}
					rsCount.close();
				}

			}
			level--;
			rs.close();
			rs = null;// Added by Jiten 09/11/06 -Sun
		} catch (SQLException se)
		{
			System.out.println("SQLException :RunMRPPrcEJB :bomExplode(String siteCode, String MatPlan, String bomCode).." + se.getMessage());
			se.printStackTrace();
			errString = se.getMessage();
			throw new ITMException(se);
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :bomExplode(String siteCode, String MatPlan, String bomCode):...." + e.getMessage() + ":");
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			try
			{
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if (rsInner1 != null)
				{
					rsInner1.close();
					rsInner1 = null;
				}
				if (pstmtInner1 != null)
				{
					pstmtInner1.close();
					pstmtInner1 = null;
				}
				if (rsInner1 != null)
				{
					rsInner1 = null;
				}
				if (pstmtInner2 != null)
				{
					pstmtInner2.close();
					pstmtInner2 = null;
				}
				if (rsInner2 != null)
				{
					rsInner2.close();
					rsInner2 = null;
				}
				this.fw.flush();// Added by Jiten 07/11/06
			} catch (Exception e)
			{
				System.out.println(e);
				throw new ITMException(e);
			}
		}
		return errString;// Moved here as finally does not complete - jiten
		// -03/11/06
	}

	/*
	 * private String bomExplode(String siteCode, String bomCode) throws
	 * ITMException { PreparedStatement pstmt = null; PreparedStatement
	 * pstmtInner1 = null; PreparedStatement pstmtInner2 = null; ResultSet
	 * rsCount = null; String sql = "", sqlInner1 = "", sqlInner2 = "";
	 * ResultSet rs = null, rsInner1 = null, rsInner2 = null; String
	 * innerSuppSour = null; String innerBomCode = null;
	 * 
	 * PreparedStatement pstmtValidBom = null; String sqlValidBom =
	 * "SELECT CONFIRMED, ACTIVE FROM BOM WHERE BOM_CODE = ?"; ResultSet
	 * rsValidBom = null; boolean bomExists = false; String logMsg = null;
	 * String confirmedBom = null; String activeBom = null; // 29/09/10
	 * manoharan to close the main resultset before processing ArrayList
	 * mainList = new ArrayList(); String tempItemCode = ""; int setLength=0;
	 * 
	 * // end 29/09/10 manoharan try {
	 * 
	 * // 19-01-2007 manoharan // check whether the bom is valid should be
	 * confirmed and active pstmtValidBom = conn.prepareStatement(sqlValidBom);
	 * pstmtValidBom.setString(1,bomCode); rsValidBom =
	 * pstmtValidBom.executeQuery(); bomExists = false; if(rsValidBom.next()) {
	 * bomExists = true; confirmedBom = rsValidBom.getString(1); activeBom =
	 * rsValidBom.getString(2); } rsValidBom.close(); pstmtValidBom.close();
	 * //this
	 * .fwInvalidBom.write("Site Code	 Item Code	 Bom Code   Message\r\n");
	 * if(confirmedBom == null || confirmedBom.trim().length() == 0 ||
	 * confirmedBom.equalsIgnoreCase("N") || activeBom == null ||
	 * activeBom.trim().length() == 0 || activeBom.equalsIgnoreCase("N")) {
	 * siteCode = (siteCode.trim() + "     ").substring(0,5); validBomItemCode =
	 * (validBomItemCode.trim() + "          ").substring(0,10); bomCode =
	 * (bomCode.trim() + "          ").substring(0,10); logMsg = siteCode +
	 * "      " + validBomItemCode + "  " + bomCode + "  "; //=========
	 * ========== ========== ======== if(confirmedBom == null ||
	 * confirmedBom.trim().length() == 0 || confirmedBom.equalsIgnoreCase("N"))
	 * { logMsg = logMsg + "BOM not confirmed"; } if(activeBom == null ||
	 * activeBom.trim().length() == 0 || activeBom.equalsIgnoreCase("N")) {
	 * logMsg = logMsg + " BOM not active"; } invaldBomExists = true;
	 * this.fwInvalidBom.write(logMsg + "\r\n"); } // end 19-01-2007 manoharan
	 * Set levelBom=new HashSet(); sql =
	 * "SELECT DISTINCT CASE WHEN ITEM.ITEM_CODE__PLAN IS NULL THEN ITEM.ITEM_CODE ELSE ITEM.ITEM_CODE__PLAN END "
	 * + " FROM BOMDET, ITEM " + " WHERE ITEM.ITEM_CODE = BOMDET.ITEM_CODE "
	 * +" AND BOMDET.BOM_CODE = ?"; pstmt = conn.prepareStatement(sql);
	 * pstmt.setString(1,bomCode); rs = pstmt.executeQuery(); int ctr=0;
	 * while(rs.next()) { System.out.println("Item Code : "+rs.getString(1));
	 * mainList.add(rs.getString(1)); cyclicCheck.add(rs.getString(1));
	 * levelBom.add(rs.getString(1)); ctr=1; } level=level+ctr; hmap.put(new
	 * Integer(level),levelBom); System.out.println("level--"+level);
	 * rs.close(); pstmt.close(); // for(int i=1;i<level;i++) // { //
	 * System.out.println("Level Loop Entered---"+i+"---"+hmap.size()); //
	 * levelBom=(HashSet) hmap.get(new Integer(i)); //
	 * System.out.println("Level Loop Entered---"+i+"---"+levelBom.size()); //
	 * Iterator it=levelBom.iterator(); // while(it.hasNext()) // { //
	 * System.out.println("SET Value---"+it.next().toString()); // } // // // //
	 * }
	 * 
	 * 
	 * 
	 * for (int mainCtr = 0; mainCtr < mainList.size() ; mainCtr++) {
	 * System.out.println("(String) mainList.get(mainCtr)--"+(String)
	 * mainList.get(mainCtr)); }
	 * 
	 * for (int mainCtr = 0; mainCtr < mainList.size() ; mainCtr++) {
	 * tempItemCode = (String) mainList.get(mainCtr); mainList.remove(mainCtr);
	 * 
	 * //System.out.println("Manoj  tempItemCode--"+tempItemCode);
	 * setLength=itemList.size(); //setLength = cyclicCheck.size(); Iterator
	 * itr=itemList.iterator(); while(itr.hasNext()) {
	 * System.out.println(itr.next()); }
	 * System.out.println("setLength--"+setLength); System.out.println("Hello");
	 * System.out.println("tempItemCode--"+tempItemCode+"--"+itemList.size());
	 * itemList.add(tempItemCode);
	 * System.out.println("tempItemCode--"+tempItemCode+"--"+itemList.size());
	 * sqlInner1 = "SELECT COUNT(1) FROM ITEM WHERE ITEM_CODE = ?";
	 * 
	 * pstmtInner1 = conn.prepareStatement(sqlInner1);
	 * pstmtInner1.setString(1,tempItemCode); rsCount =
	 * pstmtInner1.executeQuery();
	 * 
	 * //rsCount =
	 * stmt.executeQuery("SELECT COUNT(1) FROM ITEM WHERE ITEM_CODE = '" +
	 * rs.getString(1) + "'"); if(rsCount.next() && rsCount.getInt(1) > 0) {
	 * rsCount.close(); rsCount = null; pstmtInner1.close(); pstmtInner1 = null;
	 * // Add ItemCode in ItemCodeMap if it not present earlier innerSuppSour =
	 * getSuppSour(siteCode,tempItemCode); innerBomCode =
	 * getBomCode(siteCode,tempItemCode);
	 * System.out.println("Inner Bom Code  "+innerSuppSour
	 * +"--"+innerBomCode+"--"+tempItemCode);
	 * //System.out.println("bomExplode Function :: Site Code :: "
	 * +siteCode+"Bom Code ::"+bomCode+"Item Code ::"+rs.getString(1));
	 * 
	 * if( ( (innerSuppSour != null) && (!innerSuppSour.equals("P")) ) &&
	 * (innerBomCode != null) ) {
	 * 
	 * System.out.println("itemList.size()--"+verifier+"--"+setLength+"--"+itemList
	 * .size()); //14.11.2010 Manoj
	 * 
	 * for(int i=1;i<level;i++) {
	 * 
	 * levelBom=(HashSet) hmap.get(new Integer(i));
	 * System.out.println("levelBom.contains(tempItemCode)--"
	 * +level+"---"+i+"---"
	 * +levelBom.size()+"--"+levelBom.contains(tempItemCode));
	 * if(levelBom.size()>0 && levelBom.contains(tempItemCode)) {
	 * System.out.println
	 * ("levelBom.contains(tempItemCode)--"+levelBom.contains(tempItemCode));
	 * if(verifier != null && verifier.equalsIgnoreCase("Y")) {
	 * System.out.println
	 * ("itemList.size()--"+verifier+"--"+setLength+"--"+itemList.size());
	 * this.fw
	 * .write(cyclicItem.siteCode+"		"+cyclicItem.bomCode+"		"+cyclicItem.
	 * itemCode+"		"+tempItemCode+"\r\n");
	 * System.out.println("Cyclic Item Code is : " + tempItemCode); //return "";
	 * System
	 * .out.println("itemList.size()--"+verifier+"--"+setLength+"--"+itemList
	 * .size()); } else { System.out.println("Cyclic Item Code is : " +
	 * tempItemCode); errString =
	 * itmDBAccessEJB.getErrorString("","VTMRPITEME","","",conn); rs.close();
	 * pstmt.close(); itemList.clear(); return errString; } } } // end
	 * 14.11.2010 Manoj
	 * 
	 * } if(itemCodeMap.containsKey(tempItemCode)) {
	 * System.out.println("Test1"); } else { System.out.println("Test2");
	 * itemCodeMap.put(tempItemCode,new Integer(itemCodeMap.size() + 1));
	 * 
	 * } if( ( (innerSuppSour != null) && (!innerSuppSour.equals("P")) ) &&
	 * (innerBomCode != null) ) {
	 * System.out.println("Inner Exploding BOM for site : " + siteCode +
	 * " Item : " + tempItemCode + " BOM : " + innerBomCode); validBomItemCode =
	 * tempItemCode; errString = bomExplode(siteCode, innerBomCode);
	 * System.out.println("Inner 1"+siteCode+"--"+innerBomCode);
	 * System.out.println("Inner 2"+siteCode+"--"+innerBomCode);
	 * 
	 * if ( errString != null && errString.trim().length() > 0 ) {
	 * System.out.println
	 * ("Error While Calling method bomExplode(String, String):..."+errString);
	 * //rs.close(); //pstmt.close(); //rs = null; //pstmt = null; return
	 * errString; } }
	 * 
	 * } else { rsCount.close(); pstmtInner1.close(); sqlInner2 =
	 * "SELECT COUNT(1) FROM BOM WHERE BOM_CODE = ?"; pstmtInner2 =
	 * conn.prepareStatement(sqlInner2); pstmtInner2.setString(1,tempItemCode);
	 * rsCount = pstmtInner2.executeQuery(); //rsCount =
	 * stmt.executeQuery("SELECT COUNT(1) FROM BOM WHERE BOM_CODE = '" +
	 * rs.getString(1) + "'"); if(rsCount.next() && rsCount.getInt(1) > 0) {
	 * rsCount.close(); rsCount = null; pstmtInner2.close(); pstmtInner2 = null;
	 * 
	 * validBomItemCode = "BOMDET:" +tempItemCode; errString =
	 * bomExplode(siteCode, tempItemCode); if ( errString != null &&
	 * errString.trim().length() > 0 ) { System.out.println(
	 * "Error While Calling method bomExplode(String, String):..."+errString);
	 * //rs.close(); //pstmt.close(); //rs = null; //pstmt = null; return
	 * errString; } } else { rsCount.close(); rsCount = null;
	 * pstmtInner2.close(); pstmtInner2 = null; } } }
	 * 
	 * if ( rs != null) { rs.close(); rs = null;//Added by Jiten 09/11/06 -Sun }
	 * if ( pstmt != null) { pstmt.close(); pstmt = null; } } catch(SQLException
	 * se) { System.out.println(
	 * "SQLException :RunMRPPrcEJB :bomExplode(String siteCode, String MatPlan, String bomCode).."
	 * +se.getMessage()); se.printStackTrace(); errString = se.getMessage();
	 * throw new ITMException(se); } catch(Exception e) { System.out.println(
	 * "Exception :RunMRPPrcEJB :bomExplode(String siteCode, String MatPlan, String bomCode):...."
	 * + e.getMessage() + ":"); this.errString =
	 * genericUtility.createErrorString(e); e.printStackTrace(); errString =
	 * e.getMessage(); throw new ITMException(e); } finally { try { if ( rs !=
	 * null) { rs.close(); rs = null;//Added by Jiten 09/11/06 -Sun } if (pstmt
	 * != null) { pstmt.close(); pstmt = null; } if (rsInner1 != null) {
	 * rsInner1.close(); rsInner1 = null; } if (pstmtInner1 != null) {
	 * pstmtInner1.close(); pstmtInner1 = null; } if (rsInner1 != null){
	 * rsInner1 = null; } if (pstmtInner2 != null) { pstmtInner2.close();
	 * pstmtInner2 = null; } if (rsInner2 != null) { rsInner2.close(); rsInner2
	 * = null; } this.fw.flush();//Added by Jiten 07/11/06 } catch(Exception e)
	 * { System.out.println(e); throw new ITMException(e); } } return
	 * errString;//Moved here as finally does not complete - jiten -03/11/06 }
	 */

	// Populating Bom code

	private String getBomCode(String siteCode, String itemCode) throws ITMException
	{
		PreparedStatement pstmt = null;
		String sql = "";
		ResultSet rs = null;
		String bomCode = null;
		try
		{
			// sql = "select bom_code from siteitem where site_code ='" +
			// siteCode + "' AND item_code = '" + ItemCode + "'";
			sql = "SELECT BOM_CODE FROM SITEITEM WHERE SITE_CODE = ? AND ITEM_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, siteCode);
			pstmt.setString(2, itemCode);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				bomCode = rs.getString(1);
			} else
			{
				rs.close();
				pstmt.close();
				sql = "SELECT BOM_CODE FROM ITEM WHERE ITEM_CODE = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, itemCode);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					bomCode = rs.getString(1);
				}
			}
			rs.close();
			pstmt.close();
			rs = null;
			pstmt = null;
		} catch (SQLException se)
		{
			System.out.println("SQLException :RunMRPPrcEJB :getBomCode(String siteCode, String ItemCode).." + se.getMessage());
			se.printStackTrace();
			errString = se.getMessage();
			throw new ITMException(se);
		}

		catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :getBomCode(String siteCode, String ItemCode).." + e.getMessage());
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			if (pstmt != null)
			{
				pstmt = null;
			}
			if (rs != null)
			{
				rs = null;
			}
		}
		return bomCode; // Moved here as Finally block does not complete
		// normally - jiten -03/11/06
	}

	private String getBomCode(String siteCode, String itemCode, double quantity) throws ITMException
	{
		PreparedStatement pstmt = null;
		String sql = "";
		ResultSet rs = null;
		String bomCode = null;
		int count;
		if (quantity > 0)
		{
			try
			{
				sql = "SELECT count(1) FROM BOM WHERE ITEM_CODE = ? AND CONFIRMED = 'Y' AND ACTIVE = 'Y' ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, itemCode);
				rs = pstmt.executeQuery();
				if (rs.next() && rs.getInt(1) > 1)
				{
					count = rs.getInt(1);
					sql = "SELECT BOM_CODE FROM BOM WHERE ITEM_CODE = ? AND CONFIRMED = 'Y' AND ACTIVE = 'Y' " + "AND ? BWTWEEN MIN_BATCH_QTY AND MAX_BATCH_QTY ";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, itemCode);
					pstmt.setDouble(2, quantity);
					rs = pstmt.executeQuery();
					if (rs.next())
					{
						bomCode = rs.getString(1);
						rs.close();
						pstmt.close();
					} else
					{
						rs.close();
						pstmt.close();
						bomCode = getBomCode(siteCode, itemCode);
					}
				} else
				{

					rs.close();
					pstmt.close();
					bomCode = getBomCode(siteCode, itemCode);

				}
			} catch (SQLException se)
			{
				System.out.println("SQLException :RunMRPPrcEJB :getBomCode(String siteCode, String ItemCode).." + se.getMessage());
				se.printStackTrace();
				errString = se.getMessage();
				throw new ITMException(se);
			}

			catch (Exception e)
			{
				System.out.println("Exception :RunMRPPrcEJB :getBomCode(String siteCode, String ItemCode).." + e.getMessage());
				this.errString = genericUtility.createErrorString(e);
				e.printStackTrace();
				errString = e.getMessage();
				throw new ITMException(e);
			}
		} else
		{
			bomCode = getBomCode(siteCode, itemCode);
		}
		return bomCode;
	}

	private String getSuppSour(String siteCode, String itemCode) throws ITMException
	{
		PreparedStatement pstmt = null;
		String sql = "";
		ResultSet rs = null;
		String suppSour = null;
		try
		{
			// sql = "select supp_sour from siteitem where site_code ='" +
			// siteCode + "' AND item_code = '" + ItemCode + "'";
			sql = "SELECT SUPP_SOUR FROM SITEITEM WHERE SITE_CODE = ? AND ITEM_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, siteCode);
			pstmt.setString(2, itemCode);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				suppSour = checkNull(rs.getString(1));
			} else
			{
				rs.close();
				pstmt.close();
				sql = "SELECT SUPP_SOUR FROM ITEM WHERE ITEM_CODE = ? ";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, itemCode);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					suppSour = checkNull(rs.getString(1));
				}
			}

			rs.close();
			pstmt.close();
		} catch (SQLException se)
		{
			System.out.println("SQLException :RunMRPPrcEJB :getSuppSour(String siteCode, String ItemCode).." + se.getMessage());
			se.printStackTrace();
			errString = se.getMessage();
			throw new ITMException(se);
		}

		catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :getSuppSour(String siteCode, String ItemCode).." + e.getMessage());
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			try
			{
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
			} catch (Exception e)
			{
			}
		}
		return suppSour.trim(); // Moved here as finally block does not complete
		// normally - Jiten -03/11/06
	}

	private String getSiteCodeSupp(String siteCode, String itemCode) throws ITMException
	{
		PreparedStatement pstmt = null;
		String sql = "";
		ResultSet rs = null;
		String siteCodeSupp = null;
		try
		{
			// sql = "select supp_sour from siteitem where site_code ='" +
			// siteCode + "' AND item_code = '" + ItemCode + "'";
			sql = "SELECT SITE_CODE__SUPP FROM SITEITEM WHERE SITE_CODE = ? AND ITEM_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, siteCode);
			pstmt.setString(2, itemCode);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				siteCodeSupp = rs.getString(1);
			} else
			{

				siteCodeSupp = null;

			}

			rs.close();
			pstmt.close();
		} catch (SQLException se)
		{
			System.out.println("SQLException :RunMRPPrcEJB :getSuppSour(String siteCode, String ItemCode).." + se.getMessage());
			se.printStackTrace();
			errString = se.getMessage();
			throw new ITMException(se);
		}

		catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :getSuppSour(String siteCode, String ItemCode).." + e.getMessage());
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			try
			{
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
			} catch (Exception e)
			{
			}
			// return siteCodeSupp;
		}
		return siteCodeSupp; // Jiten - Moved here from finally 03/11/06
	}

	private String populateADPElementList() throws Exception
	{
		ADPElement adpElement = null;
		Iterator itrItem = null;
		Set setSite = siteCodeMap.entrySet();
		Iterator itrSite = setSite.iterator();
		PreparedStatement pstmt = null;
		String sql = "", siteCode = "", itemCode = "", mfgType = "";
		ResultSet rs = null;

		Set setItem = itemCodeMap.entrySet();
		//Added by Manoj dtd 30/04/2014 to add Alternate items in list
		//Iterator itrAltItem = null;
		//Set setAltItem=altitemMap.keySet();
		//cpatil-25/08/14-System.out.println("altitemMap----"+altitemMap);
		//cpatil-25/08/14-System.out.println("setAltItem----"+setAltItem);

		System.out.println("In populateADPElementList()adpeList.size():["+adpeList.size()+"]adpeList["+adpeList+"]");

		try
		{
			while (itrSite.hasNext())
			{
				Map.Entry siteMapEntry = (Map.Entry) itrSite.next();
				itrItem = setItem.iterator();
				while (itrItem.hasNext())
				{

					Map.Entry itemMapEntry = (Map.Entry) itrItem.next();


					//cpatil-25/08/14-System.out.println("@@@@@@@@ isBomReplace["+isBomReplace+"]::::siteMapEntry["+siteMapEntry+"]::::itemMapEntry["+itemMapEntry+"]itemCodeDetailMap["+itemCodeDetailMap+"]");


					siteCode = (String) siteMapEntry.getKey();
					itemCode = (String) itemMapEntry.getKey();
					if( isBomReplace )  				
					{
						//continue;

						int ctr = indexOfADPElement(siteCode, itemCode, "          ", "   ");
						System.out.println("@@@@@@2687 ctr["+ctr+"]");
						if (ctr > -1)
						{
							continue;
						}
					}
					adpElement = new ADPElement();
					adpElement.setbomSet( itemCodeDetailMap );

					//Manoj dtd 30/04/2014 to set Original/Alternate item flag
					adpElement.setOriginalOrAltitem("O");
					adpElement.setItemCodeParent(itemCode);  //added by cpatil on 03/05/14
					// 01/04/11 in case of made to order only made to order item
					// will be planned
					/*
					 * if ("Y".equals(madeToOrder)) { sql =
					 * "SELECT mfg_type FROM SITEITEM WHERE SITE_CODE = ? AND ITEM_CODE = ?"
					 * ; pstmt = conn.prepareStatement(sql);
					 * pstmt.setString(1,siteCode); pstmt.setString(2,itemCode);
					 * rs = pstmt.executeQuery(); if(rs.next()) { mfgType =
					 * rs.getString(1); } rs.close(); pstmt.close(); if
					 * (!"O".equals(mfgType)) { continue; } }
					 */
					// end 01/04/11 in case of made to order only made to order
					// item will be planned
					adpElement.setSiteCode((String) siteMapEntry.getKey());
					adpElement.setItemCode((String) itemMapEntry.getKey());
					adpElement = setAdpeValues(adpElement);



					if( !(isBomReplace ))
					{
						if (adpElement.getSuppSour() != null)
						{
							if (adpElement.getSuppSour().equals("D") && !disPlan.equals("Y"))
							{
								continue;
							}
							if (adpElement.getSuppSour().equals("M") && (!mfgPlan.equals("Y") && !matPlan.equals("Y")))
							{
								continue;
							}
							if (adpElement.getSuppSour().equals("P") && !matPlan.equals("Y"))
							{
								continue;
							}
						} 
						else
						{
							//cpatil-25/08/14-System.out.println("NULL : SiteCode : [" + siteMapEntry.getKey() + "] ItemCode : [" + itemMapEntry.getKey() + "]");
							errString = "Supply source is null...";
							return errString;
						}
					}
					// Code for adding Demand (i.e. getDemand()) in adpElement
					// // adpElement.setDemand(adpElement.getDemand(demand));
					// adpElement = populateDemandSupply(adpElement);//Commented
					// by Jiten 09/11/06

					if (adpElement != null)
						adpeList.add(adpElement);
				}


				//Added by Manoj dtd 30/04/2014 to add Alternate items in list
				/*itrAltItem=setAltItem.iterator();
				while(itrAltItem.hasNext())
				{
					System.out.println(" itrAltItem.next()---"+ (String) itrAltItem.next());
					String keyAlttem=(String) itrAltItem.next();
					//cpatil-25/08/14-System.out.println("keyAlttem----"+keyAlttem);
					ArrayList<String> altItemlist=altitemMap.get(keyAlttem);

					//cpatil-25/08/14-System.out.println("altItemlist.size()----"+altItemlist.size());
					for(int i=0;i<altItemlist.size();i++)
					{
						System.out.println("altItemlist.get(i)----"+altItemlist.get(i));
						adpElement = new ADPElement();
						adpElement.setOriginalOrAltitem("A");
						adpElement.setItemCodeParent(keyAlttem);  //added by cpatil on 03/05/14
						adpElement.setSiteCode((String) siteMapEntry.getKey());
						adpElement.setItemCode(altItemlist.get(i));
						adpElement = setAdpeValues(adpElement);
						adpeList.add(adpElement);
					}
					//Ended by Manoj dtd 30/04/2014 to add Alternate items in list

					//if (adpElement != null)

				}*/

			}
			populateADPList();// Added by Jiten 09/11/06
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :populateADPElementList().." + e.getMessage());
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		}
		return errString;
	}

	private ADPElement setAdpeValues(ADPElement adpElement) throws Exception
	{
		String orderOpt = "";
		String suppSour = "";
		String bomCode = "";
		String masterSch = "";

		double minQty = 0;
		int minStkDay = 0;
		double reoQty = 0;
		int purLeadTime = 0;
		int qcLeadTime = 0;
		int mfgLeadTime = 0;
		double integralQty = 0;
		double yieldPerc = 0;
		String itemStru = "";
		String siteCodeSupp = "";
		String siteCodePlan = "";
		String batchQtyType = "";
		double minOrderQty = 0;
		int maxStkDay = 0;
		double maxQty = 0;
		double minPlanPerc = 0;

		String siteCode = "";
		String itemCode = "";
		String itemSer = "";
		String sql = "";
		String unit = null;

		String acctCodeWp = "";
		String cctrCodeWp = "";
		String acctCode = "";
		String cctrCode = "";
		// 22/06/10 manoharan mfg lead time basis and batch size
		String mfgLeadBasis = "F";
		double batchSizeLead = 0;
		//

		ResultSet rs = null;
		ResultSet rsInner = null;
		PreparedStatement pstmt = null;
		PreparedStatement pstmt1 = null;
		PreparedStatement pstmtInner = null;
		itemCode = adpElement.getItemCode();
		siteCode = adpElement.getSiteCode();

		String bomCodeParent=""; //cpatil on 02/06/14

		System.out.println("@@@@@@@@2848 setAdpeValues() called......... ");
		try
		{ // 1
			sql = "SELECT CASE WHEN (CASE WHEN A.SUPP_SOUR IS NULL THEN B.SUPP_SOUR ELSE A.SUPP_SOUR END) IS NULL THEN '' ELSE " + "(CASE WHEN A.SUPP_SOUR IS NULL THEN B.SUPP_SOUR ELSE A.SUPP_SOUR END) END ,"
			// 2
			+ "CASE WHEN (CASE WHEN A.BOM_CODE IS NULL THEN B.BOM_CODE ELSE A.BOM_CODE END) IS NULL THEN '' ELSE " + "(CASE WHEN A.BOM_CODE IS NULL THEN B.BOM_CODE ELSE A.BOM_CODE END) END, "
			// 3
			+ "CASE WHEN (CASE WHEN A.MIN_QTY IS NULL THEN B.MIN_QTY ELSE A.MIN_QTY END) IS NULL THEN 0 ELSE " + "(CASE WHEN A.MIN_QTY IS NULL THEN B.MIN_QTY ELSE A.MIN_QTY END) END, "
			// 4
			+ "CASE WHEN (CASE WHEN A.MIN_STK_DAY IS NULL THEN B.MIN_STK_DAY ELSE A.MIN_STK_DAY END) IS NULL THEN 0 ELSE " + "(CASE WHEN A.MIN_STK_DAY IS NULL THEN B.MIN_STK_DAY ELSE A.MIN_STK_DAY END) END,"
			// 5
			+ "CASE WHEN A.REO_QTY IS NULL THEN 0 ELSE A.REO_QTY END, "
			// 6
			+ "CASE WHEN A.PUR_LEAD_TIME IS NULL THEN 0 ELSE A.PUR_LEAD_TIME END, "
			// 7
			+ "CASE WHEN A.QC_LEAD_TIME IS NULL THEN 0 ELSE A.QC_LEAD_TIME END, "
			// 8
			+ "CASE WHEN A.MFG_LEAD_TIME IS NULL THEN 0 ELSE A.MFG_LEAD_TIME END, "
			// 9
			+ "CASE WHEN A.INTEGRAL_QTY IS NULL THEN 0 ELSE A.INTEGRAL_QTY END, "
			// 10
			+ "CASE WHEN B.ITEM_STRU IS NULL THEN '' ELSE B.ITEM_STRU END, "
			// 11
			+ "CASE WHEN A.SITE_CODE__SUPP IS NULL THEN '' ELSE A.SITE_CODE__SUPP END, "
			// 12
			+ "CASE WHEN A.SITE_CODE__PLAN IS NULL THEN A.SITE_CODE ELSE A.SITE_CODE__PLAN END,"
			// 13
			+ "CASE WHEN (CASE WHEN A.BATCH_QTY_TYPE IS NULL THEN B.BATCH_QTY_TYPE ELSE A.BATCH_QTY_TYPE END) IS NULL THEN 'F' ELSE " + "(CASE WHEN A.BATCH_QTY_TYPE IS NULL THEN B.BATCH_QTY_TYPE ELSE A.BATCH_QTY_TYPE END) END,	"
			// 14
			+ "CASE WHEN (CASE WHEN A.MIN_ORDER_QTY IS NULL THEN B.MIN_ORDER_QTY ELSE A.MIN_ORDER_QTY END) IS NULL THEN 0 ELSE " + "(CASE WHEN A.MIN_ORDER_QTY IS NULL THEN B.MIN_ORDER_QTY ELSE A.MIN_ORDER_QTY END) END, "
			// 15
			+ "CASE WHEN (CASE WHEN A.MAX_STK_DAY IS NULL THEN B.MAX_STK_DAY ELSE A.MAX_STK_DAY END) IS NULL THEN 0 ELSE " + "(CASE WHEN A.MAX_STK_DAY IS NULL THEN B.MAX_STK_DAY ELSE A.MAX_STK_DAY END) END, "
			// 16
			+ "A.MASTER_SCH , "
			// 17
			+ "CASE WHEN (CASE WHEN A.MAX_QTY IS NULL THEN B.MAX_QTY ELSE A.MAX_QTY END) IS NULL THEN 0 ELSE " + "(CASE WHEN A.MAX_QTY IS NULL THEN B.MAX_QTY ELSE A.MAX_QTY END) END ,"
			// 18
			+ "(CASE WHEN A.ORDER_OPT IS NULL THEN B.ORDER_OPT ELSE A.ORDER_OPT END) END ,"
			// 19
			+ "(CASE WHEN A.YIELD_PERC IS NULL THEN B.YIELD_PERC ELSE A.YIELD_PERC END) END, "
			// 20
			+ "(CASE WHEN A.MIN_PLAN_PERC IS NULL THEN 0 ELSE A.MIN_PLAN_PERC END) END, "
			// 21
			+ "B.UNIT, "
			// 22
			+ "B.DESCR, "
			// 23
			+ "B.APR_CODE, "
			// 24
			+ "B.PACK_CODE, "
			// 25
			+ "CASE WHEN A.EMP_CODE__PUR IS NULL THEN CASE WHEN b.EMP_CODE__PUR IS NULL THEN C.EMP_CODE__PUR ELSE B.EMP_CODE__PUR END ELSE A.EMP_CODE__PUR END , "
			// 26
			+ "(CASE WHEN A.SUPP_CODE__PREF IS NULL THEN B.SUPP_CODE__PREF ELSE A.SUPP_CODE__PREF END ), "
			// 27
			+ "B.PURC_RATE, "
			// 28
			+ "C.ACCT_CODE__PH, "
			// 29
			+ "C.CCTR_CODE__PH, "
			// 30
			+ " B.ITEM_SER, "
			// 31, 32
			+ " CASE WHEN A.MFG_TYPE IS NULL THEN 'MRP' ELSE A.MFG_TYPE END, A.ROUTE_CODE, "
			// 33, 34
			+ " case when a.mfg_lead_basis is null then 'F' else a.mfg_lead_basis end, case when a.batch_size_lead is null then 0 else a.batch_size_lead end,A.EMP_CODE__PLN," 
			+ "CASE WHEN (CASE WHEN A.REO_LEV IS NULL THEN B.REO_LEV ELSE A.REO_LEV END) IS NULL THEN 0 ELSE " + "(CASE WHEN A.REO_LEV IS NULL THEN B.REO_LEV ELSE A.REO_LEV END) END as REO_LEV "
			+ " FROM SITEITEM A, ITEM B, ITEMSER C " + " WHERE A.ITEM_CODE = B.ITEM_CODE " + " AND B.ITEM_SER = C.ITEM_SER " + " AND A.SITE_CODE = ? " + " AND A.ITEM_CODE = ? ";
			// +" AND A.SITE_CODE = '" + siteCode + "' "
			// +" AND A.ITEM_CODE = '" + itemCode + "' ";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, siteCode);
			pstmt.setString(2, itemCode);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				suppSour = rs.getString(1);
				adpElement.setSuppSour(suppSour.trim());
				suppSour = suppSour.trim();

				bomCode = rs.getString(2);
				bomCodeParent=itemBomMap.get(itemCode);
				if( bomCodeParent == null )
				{
					bomCodeParent = rs.getString(2);
				}


				System.out.println("@@@@@@@@@@@@bomcode:2929isBomReplace["+isBomReplace+"]bomCode["+bomCode+"]itemCode["+itemCode+"]bomCodeParent["+bomCodeParent+"]itemBomMap["+itemBomMap+"]");

				if(!(isBomReplace))
				{
					System.out.println("@@@@@@ inside if bomCode["+bomCode+"]");
					adpElement.setBomCode(bomCode);
				}
				else
				{
					if(itemCodeTo.equalsIgnoreCase(itemCode) )
					{
						System.out.println("@@@@@@ inside else isBomReplace bomCode1["+bomCode1+"]");
						adpElement.setBomCode(bomCode1);
					}
					else
					{
						System.out.println("@@@@@@ inside else bomCode["+bomCode+"]");
						adpElement.setBomCode(bomCode);
					}
				}

				adpElement.setBomCodeParent(bomCodeParent);

				minQty = rs.getDouble(3);
				adpElement.setMinQty(minQty);

				minStkDay = rs.getInt(4);
				adpElement.setMinStkDay(minStkDay);

				reoQty = rs.getDouble(5);
				adpElement.setReoQty(reoQty);

				purLeadTime = rs.getInt(6);
				adpElement.setPurLeadTime(purLeadTime);

				qcLeadTime = rs.getInt(7);
				adpElement.setQcLeadTime(qcLeadTime);

				mfgLeadTime = rs.getInt(8);
				adpElement.setMfgLeadTime(mfgLeadTime);

				integralQty = rs.getDouble(9);
				if (integralQty == 0)
				{
					integralQty = 1;
				}
				adpElement.setIntegralQty(integralQty);

				itemStru = rs.getString(10);
				adpElement.setItemStru(itemStru);

				siteCodeSupp = rs.getString(11);
				adpElement.setSiteCodeSupp(siteCodeSupp);

				siteCodePlan = rs.getString(12);
				adpElement.setSiteCodePlan(siteCodePlan);

				batchQtyType = rs.getString(13);
				adpElement.setBatchQtyType(batchQtyType);

				minOrderQty = rs.getDouble(14);
				adpElement.setMinOrderQty(minOrderQty);

				maxStkDay = rs.getInt(15);
				adpElement.setMaxStkDay(maxStkDay);

				masterSch = rs.getString(16);
				adpElement.setMasterSch(masterSch);

				maxQty = rs.getDouble(17);
				adpElement.setMaxQty(maxQty);

				orderOpt = rs.getString(18);
				if (orderOpt == null)
				{
					orderOpt = "C";
				}
				if (orderOpt.equals("B") && batchQtyType == null)
				{
					adpElement.setBatchQtyType("V");
				}
				adpElement.setOrderOpt(orderOpt);

				yieldPerc = rs.getDouble(19);
				if (yieldPerc == 0)
				{
					yieldPerc = 100;
				}

				adpElement.setYieldPerc(yieldPerc);
				minPlanPerc = rs.getDouble(20);
				adpElement.setMinPlanPerc(minPlanPerc);
				unit = rs.getString(21);
				adpElement.setUnit(unit);
				adpElement.setItemDescr(rs.getString(22));
				adpElement.setAprCode(rs.getString(23));
				adpElement.setPackCode(rs.getString(24));
				adpElement.setEmpCodePur(rs.getString(25));
				adpElement.setSuppCodePref(rs.getString(26));
				adpElement.setPurcRate(rs.getDouble(27));
				adpElement.setAcctCodePh(rs.getString(28));
				adpElement.setCctrCodePh(rs.getString(29));
				adpElement.setItemSer(rs.getString(30));
				String mfgType = rs.getString(31);
				if (mfgType != null)
				{
					adpElement.setMfgType(mfgType.trim());
				}
				String routeCode = rs.getString(32);
				if (routeCode != null && routeCode.trim().length() > 0)
				{
					adpElement.setRouteCode(routeCode);
				}
				// 22/06/10 manoharan
				mfgLeadBasis = rs.getString(33);
				mfgLeadBasis = (mfgLeadBasis == null ? "F" : mfgLeadBasis);
				adpElement.setMfgLeadBasis(mfgLeadBasis);
				batchSizeLead = rs.getDouble(34);
				adpElement.setBatchSizeLead(batchSizeLead);
				adpElement.setEmpCodePlan(rs.getString("EMP_CODE__PLN"));//Manoj dtd 11/03/2014
				adpElement.setReorderLevel(rs.getDouble("REO_LEV"));//Manoj dtd 26/03/2015
				// end 22/06/10 manoharan
				rs.close();
			} else
			{
				//cpatil-25/08/14-System.out.println("*** No SiteItem *** " + siteCode + " " + itemCode);
				// ***************************** 04-01-2007 manoharan take all
				// values from item if no siteitem

				rs.close();
				pstmt.close();
				sql = "SELECT CASE WHEN B.SUPP_SOUR IS NULL THEN '' ELSE B.SUPP_SOUR END ,"
					// 2
					+ "CASE WHEN B.BOM_CODE IS NULL THEN '' ELSE B.BOM_CODE END, "
					// 3
					+ "CASE WHEN B.MIN_QTY IS NULL THEN 0 ELSE B.MIN_QTY END, "
					// 4
					+ "CASE WHEN B.MIN_STK_DAY IS NULL THEN 0 ELSE B.MIN_STK_DAY END,"
					// 5
					+ "CASE WHEN B.REO_QTY IS NULL THEN 0 ELSE B.REO_QTY END, "
					// 6
					+ "CASE WHEN B.PUR_LEAD_TIME IS NULL THEN 0 ELSE B.PUR_LEAD_TIME END, "
					// 7
					+ "CASE WHEN B.QC_LEAD_TIME IS NULL THEN 0 ELSE B.QC_LEAD_TIME END, "
					// 8
					+ "CASE WHEN B.MFG_LEAD IS NULL THEN 0 ELSE B.MFG_LEAD END, "
					// 9
					+ "CASE WHEN B.INTEGRAL_QTY IS NULL THEN 0 ELSE B.INTEGRAL_QTY END, "
					// 10
					+ "CASE WHEN B.ITEM_STRU IS NULL THEN '' ELSE B.ITEM_STRU END, "
					// 11
					+ "'' AS SITE_CODE__SUPP, "
					// 12
					+ "'" + siteCode + "' AS SITE_CODE__PLAN,"
					// 13
					+ "CASE WHEN B.BATCH_QTY_TYPE IS NULL THEN 'F' ELSE B.BATCH_QTY_TYPE END,	"
					// 14
					+ "CASE WHEN B.MIN_ORDER_QTY IS NULL THEN 0 ELSE B.MIN_ORDER_QTY END, "
					// 15
					+ "CASE WHEN B.MAX_STK_DAY IS NULL THEN 0 ELSE B.MAX_STK_DAY END, "
					// 16
					+ "'Y' AS MASTER_SCH , "
					// 17
					+ "CASE WHEN B.MAX_QTY IS NULL THEN 0 ELSE B.MAX_QTY END ,"
					// 18
					+ "CASE WHEN B.ORDER_OPT IS NULL THEN 'C' ELSE B.ORDER_OPT END ,"
					// 19
					+ "CASE WHEN B.YIELD_PERC IS NULL THEN 100 ELSE B.YIELD_PERC END, "
					// 20
					+ " 0 AS MIN_PLAN_PERC, "
					// 21
					+ "B.UNIT, "
					// 22
					+ "B.DESCR, "
					// 23
					+ "B.APR_CODE, "
					// 24
					+ "B.PACK_CODE, "
					// 25
					+ "CASE WHEN B.EMP_CODE__PUR IS NULL THEN C.EMP_CODE__PUR ELSE B.EMP_CODE__PUR END , "
					// 26
					+ "B.SUPP_CODE__PREF, "
					// 27
					+ "B.PURC_RATE, "
					// 28
					+ "C.ACCT_CODE__PH, "
					// 29
					+ "C.CCTR_CODE__PH, "
					// 30
					+ " B.ITEM_SER, "
					// 31
					+ " CASE WHEN B.MFG_TYPE IS NULL THEN 'MRP' ELSE B.MFG_TYPE END,B.EMP_CODE__PLN, "
					+ "CASE WHEN B.REO_LEV IS NULL THEN 0 ELSE B.REO_LEV END  as REO_LEV  "
					+ " FROM ITEM B, ITEMSER C " + " WHERE B.ITEM_SER = C.ITEM_SER" + " AND B.ITEM_CODE = '" + itemCode + "' ";

				pstmt = conn.prepareStatement(sql);
				// pstmt.setString(1,siteCode);
				// pstmt.setString(2,itemCode);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					suppSour = rs.getString(1);
					adpElement.setSuppSour(suppSour.trim());

					bomCode = rs.getString(2);
					bomCodeParent=itemBomMap.get(itemCode);
					if( bomCodeParent == null )
					{
						bomCodeParent = rs.getString(2);
					}
					System.out.println("@@@@@@@@@@@@bomcode:3118bomCode["+bomCode+"]itemCode["+itemCode+"]bomCodeParent["+bomCodeParent+"]itemBomMap["+itemBomMap+"]");
					adpElement.setBomCode(bomCode);

					adpElement.setBomCodeParent(bomCodeParent);

					minQty = rs.getDouble(3);
					adpElement.setMinQty(minQty);

					minStkDay = rs.getInt(4);
					adpElement.setMinStkDay(minStkDay);

					reoQty = rs.getDouble(5);
					adpElement.setReoQty(reoQty);

					purLeadTime = rs.getInt(6);
					adpElement.setPurLeadTime(purLeadTime);

					qcLeadTime = rs.getInt(7);
					adpElement.setQcLeadTime(qcLeadTime);

					mfgLeadTime = rs.getInt(8);
					adpElement.setMfgLeadTime(mfgLeadTime);

					integralQty = rs.getDouble(9);
					if (integralQty == 0)
					{
						integralQty = 1;
					}
					adpElement.setIntegralQty(integralQty);

					itemStru = rs.getString(10);
					adpElement.setItemStru(itemStru);

					siteCodeSupp = rs.getString(11);
					adpElement.setSiteCodeSupp(siteCodeSupp);

					siteCodePlan = rs.getString(12);
					adpElement.setSiteCodePlan(siteCodePlan);

					batchQtyType = rs.getString(13);
					adpElement.setBatchQtyType(batchQtyType);

					minOrderQty = rs.getDouble(14);
					adpElement.setMinOrderQty(minOrderQty);

					maxStkDay = rs.getInt(15);
					adpElement.setMaxStkDay(maxStkDay);

					masterSch = rs.getString(16);
					adpElement.setMasterSch(masterSch);

					maxQty = rs.getDouble(17);
					adpElement.setMaxQty(maxQty);

					orderOpt = rs.getString(18);
					if (orderOpt == null)
					{
						orderOpt = "C";
					}
					if (orderOpt.equals("B") && batchQtyType == null)
					{
						adpElement.setBatchQtyType("V");
					}
					adpElement.setOrderOpt(orderOpt);

					yieldPerc = rs.getDouble(19);
					if (yieldPerc == 0)
					{
						yieldPerc = 100;
					}
					System.out.println("@@@@@@@@@@@@3210 itemCode["+itemCode+"]yieldPerc["+yieldPerc+"]");
					adpElement.setYieldPerc(yieldPerc);
					minPlanPerc = rs.getDouble(20);
					adpElement.setMinPlanPerc(minPlanPerc);
					unit = rs.getString(21);
					adpElement.setUnit(unit);
					adpElement.setItemDescr(rs.getString(22));
					adpElement.setAprCode(rs.getString(23));
					adpElement.setPackCode(rs.getString(24));
					adpElement.setEmpCodePur(rs.getString(25));
					adpElement.setSuppCodePref(rs.getString(26));
					adpElement.setPurcRate(rs.getDouble(27));
					adpElement.setAcctCodePh(rs.getString(28));
					adpElement.setCctrCodePh(rs.getString(29));
					adpElement.setItemSer(rs.getString(30));
					String mfgType = rs.getString(31);
					if (mfgType != null)
					{
						adpElement.setMfgType(mfgType.trim());
					}
					// 22/06/10 manoharan
					adpElement.setMfgLeadBasis("F");
					adpElement.setBatchSizeLead(0);
					// end 22/06/10 manoharan
					adpElement.setEmpCodePlan(rs.getString("EMP_CODE__PLN"));//Manoj dtd 11/03/2014 
					adpElement.setReorderLevel(rs.getDouble("REO_LEV"));//Manoj dtd 26/03/2015
					rs.close();
				}

				// ***************************** end 04-01-2007 manoharan
			}
			if (adpElement.getSuppSour() == null)
			{
				adpElement.setSuppSour(this.getSuppSour(siteCode, itemCode));
			}
			if (adpElement.getSiteCodeSupp() == null)
			{
				adpElement.setSiteCodeSupp(getSiteCodeSupp(siteCode, itemCode));
			}
			if (adpElement.getOrderOpt() != null && adpElement.getOrderOpt().equals("B") && adpElement.getBatchQtyType() == null)
			{
				adpElement.setBatchQtyType("C");
			}
			if (suppSour.equals("M"))
			{
				itemSer = adpElement.getItemSer();
				sql = "SELECT ACCT_CODE__WP, CCTR_CODE__WP FROM ITEM_ACCT_DETR WHERE ITEM_CODE = ? AND ITEM_SER = ? AND TRAN_TYPE = ' ' ";
				pstmt1 = conn.prepareStatement(sql);
				pstmt1.setString(1, itemCode);
				pstmt1.setString(2, itemSer);
				rs = pstmt1.executeQuery();
				if (rs.next())
				{
					acctCodeWp = rs.getString(1);
					cctrCodeWp = rs.getString(2);
					rs.close();
					pstmt1.close();
				} else
				{
					rs.close();
					pstmt1.close();
					sql = "SELECT ACCT_CODE__WP, CCTR_CODE__WP FROM ITEM_ACCT_DETR WHERE ITEM_SER = ' ' AND ITEM_CODE = ? AND TRAN_TYPE = ' '";
					pstmt1 = conn.prepareStatement(sql);
					pstmt1.setString(1, itemCode);
					rs = pstmt1.executeQuery();
					if (rs.next())
					{
						acctCodeWp = rs.getString(1);
						cctrCodeWp = rs.getString(2);
						rs.close();
						pstmt1.close();
					} else
					{
						rs.close();
						pstmt1.close();
						sql = "SELECT ACCT_CODE__WP, CCTR_CODE__WP FROM ITEM_ACCT_DETR WHERE ITEM_SER = ? AND ITEM_CODE = ' ' AND TRAN_TYPE = ' '";
						pstmt1 = conn.prepareStatement(sql);
						pstmt1.setString(1, itemSer); // itemSer ???
						rs = pstmt1.executeQuery();
						if (rs.next())
						{
							acctCodeWp = rs.getString(1);
							cctrCodeWp = rs.getString(2);
							rs.close();
							pstmt1.close();
						} else
						{
							rs.close();
							pstmt1.close();
							sql = "SELECT ACCT_CODE__WP, CCTR_CODE__WP FROM ITEMSER WHERE ITEM_SER = ? ";
							pstmt1 = conn.prepareStatement(sql);
							pstmt1.setString(1, itemSer);
							rs = pstmt1.executeQuery();
							if (rs.next())
							{
								acctCodeWp = rs.getString(1);
								cctrCodeWp = rs.getString(2);
								rs.close();
								pstmt1.close();
							}
						}
					}
				}
				adpElement.setAcctCodeWp(acctCodeWp);
				adpElement.setCctrCodeWp(cctrCodeWp);
			}
			// set the batch quantity for later use
			sql = "SELECT BATCH_QTY FROM BOM WHERE BOM_CODE = ?";
			pstmtInner = conn.prepareStatement(sql);
			pstmtInner.setString(1, bomCode);
			rsInner = pstmtInner.executeQuery();
			if (rsInner.next())
			{
				adpElement.setBatchQty(rsInner.getDouble(1));
			}
			rsInner.close();
			if (orderOpt.equals("B") && batchQtyType.equals("F") && suppSour.equals("M"))
			{
				// adpElement.setReoQty(adpElement.getBatchQty());
			}
			if (roundReqTo.equals("R"))
			{
				System.out.println("item [" + itemCode + " ] roundReqTo ..[" + roundReqTo + "] setting integral to [" + adpElement.getReoQty() + "]");
				adpElement.setIntegralQty(adpElement.getReoQty());
			}
		} catch (SQLException se)
		{
			System.out.println("SQLException .." + se.getMessage());
			se.printStackTrace();
			errString = se.getMessage();
			throw new ITMException(se);
		} catch (Exception e)
		{
			System.out.println("Exception .." + e.getMessage());
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			if (pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if (pstmt1 != null)
			{
				pstmt1 = null;
			}
			if (pstmtInner != null)
			{
				pstmtInner.close();
				pstmtInner = null;
			}
			if (rs != null)
			{
				rs.close();
				rs = null;
			}
			if (rsInner != null)
			{
				rsInner.close();
				rsInner = null;
			}
		}
		return adpElement;// Moved here as Finally block does not complete
		// normally - jiten -03/11/06
	}

	private String getMfgType(String itemCode,String siteCode, Connection conn2) throws SQLException 
	{  // private String getMfgType(String itemCode, Connection conn2) throws SQLException
		/*
				<item display="Made To Order" data="O"/>
				<item display="Made To Stock" data="S"/>
				<item display="Designed To Order" data="D"/>
				<item display="Bulk Manufacturing" data="F"/>
				<item display="Packing" data="P"/>
				<item display="Other Manufacturing" data="I"/>
		 */

		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String descr="",sql="",mfgType="";


		sql = " select  mfg_type  from  siteitem where site_code = ? and item_code =  ?  ";
		pstmt = conn2.prepareStatement(sql);
		pstmt.setString( 1, siteCode );
		pstmt.setString( 2, itemCode );
		rs = pstmt.executeQuery();
		if (rs.next())
		{
			mfgType = checkNull(rs.getString("mfg_type")).trim();
		}
		rs.close();rs = null;
		pstmt.close();pstmt = null;  
		/*
		if( mfgType == null || mfgType.trim().length() == 0 )
		{
		 sql = " select  mfg_type  from  item  where item_code =  ?  ";
		 pstmt = conn2.prepareStatement(sql);
		 pstmt.setString( 1, itemCode );
		 rs = pstmt.executeQuery();
		 if (rs.next())
		 {
			 mfgType = checkNull(rs.getString("mfg_type")).trim();
		 }
		 rs.close();rs = null;
		 pstmt.close();pstmt = null;
		 */  
		//}
		System.out.println("@@@@@@@@cpatil-itemCode["+itemCode+"]mfgType["+mfgType+"]");
		/*
		if("O".equalsIgnoreCase(mfgType))
		{
			return "Made To Order";
		}
		else if("S".equalsIgnoreCase(mfgType))
		{
			return "Made To Stock";
		}
		else if("D".equalsIgnoreCase(mfgType))
		{
			return "Designed To Order";
		}
		else if("F".equalsIgnoreCase(mfgType))
		{
			return "Bulk Manufacturing";
		}
		else if("P".equalsIgnoreCase(mfgType))
		{
			return "Packing";
		}
		else if("I".equalsIgnoreCase(mfgType))
		{
			return "Other Manufacturing";
		}
		else
		{
			return "";
		}
		 */

		return mfgType;
	}

	private String readFile(String file) throws Exception
	{
		String sqlQry = "";
		try
		{
			// System.out.println("File "+file);
			FileInputStream fin = new FileInputStream(file);
			BufferedReader br = new BufferedReader(new InputStreamReader(fin));
			String tempStr = "";
			while ((tempStr = br.readLine()) != null)
			{
				sqlQry = sqlQry + tempStr;
			}
		} catch (FileNotFoundException fe)
		{
			System.out.println("FileNotFoundException :RunMRPPrcEJB :readFile(String).." + fe.getMessage());
			fe.printStackTrace();
			errString = fe.getMessage();
			throw new ITMException(fe);
		}

		catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :readFile(String).." + e.getMessage());
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		}
		return sqlQry;
	}

	private void populateADPList() throws Exception
	{
		ArrayList tempList = new ArrayList();
		try
		{
			//cpatil-25/08/14-System.out.println("@@@@@@@@ cpatil populateADPList madeToOrder [" + madeToOrder + "]");
			for (int ctr = 0; ctr < adpeList.size(); ctr++)
			{
				ADPElement adpElement = (ADPElement) adpeList.get(ctr);
				System.out.println("ItemCode--["+adpElement.getItemCode());
			}

			if ("0".equals(madeToOrder))
			{
				System.out.println("adpeList.size()-------------"+adpeList.size());
				for (int ctr = 0; ctr < adpeList.size(); ctr++)
				{
					ADPElement adpElement = (ADPElement) adpeList.get(ctr);
					tempList.add(adpElement);
				}
				// adpeList.clear();
				//cpatil-25/08/14-System.out.println("01/04/11 populateADPList madeToOrder [" + madeToOrder + "] tempList.size() [" + tempList.size() + "]");
				for (int ctr = 0; ctr < tempList.size(); ctr++)
				{
					ADPElement adpElement = (ADPElement) tempList.get(ctr);
					// adpElement =
					populateMTODemandSupply(adpElement.getSiteCode(), adpElement.getItemCode(), adpElement);
				}
				tempList.clear();
				tempList = null;
			}
			//cpatil-25/08/14-System.out.println("12/06/14 populateADPList madeToOrder [" + madeToOrder + "] adpeList.size() [" + adpeList.size() + "]");
			if(isDetailReq)
			{
				System.out.println("@@@@cpatil adpList["+adpeList.size()+"]adpeList["+adpeList+"]");
				populateDemandSupply(adpeList);

				//System.out.println("@@@@@@@@@@@ after modify adpeList ----------adpeList["+adpeList+"]----");
				String  itemCodeAdp="",siteCodeAdp="",saleOrderAdp="" ;
				double demandAdp=0,supplyAdp = 0,stockQtyAdp = 0,othSupplyAdp = 0,pendingPOAdp = 0,	pendingDOAdp = 0,pendingIndentAdp = 0,pendingDRAdp = 0;
				double reorderLevel=0;
				for ( int ctr1 = 0; ctr1 < adpeList.size(); ctr1++ )  //Loop for each node of current detail
				{
					ADPElement adpElement = (ADPElement) adpeList.get(ctr1);

					saleOrderAdp = adpElement.getSaleOrder();
					itemCodeAdp = adpElement.getItemCode();
					siteCodeAdp = adpElement.getSiteCode();
					demandAdp = adpElement.getDemand();
					supplyAdp = adpElement.getSupply();
					stockQtyAdp = adpElement.getStockQty();
					othSupplyAdp = adpElement.getOthSupply();
					pendingPOAdp = adpElement.getPendingPO();
					pendingDOAdp = adpElement.getPendingDO();
					pendingIndentAdp = adpElement.getPendingIndent();
					pendingDRAdp = adpElement.getPendingDR();
					reorderLevel= adpElement.getReorderLevel();
					
					
					System.out.println("@@@_ctr1["+ctr1+"]saleOrderAdp==["+saleOrderAdp+"]itemCodeAdp==["+itemCodeAdp+"]siteCodeAdp["+siteCodeAdp+"]demandAdp["+demandAdp+"]supplyAdp["+supplyAdp+"]stockQtyAdp["+stockQtyAdp+"]othSupplyAdp["+othSupplyAdp+"]pendingPOAdp["+pendingPOAdp+"]pendingDOAdp["+pendingDOAdp+"]pendingIndentAdp["+pendingIndentAdp+"]pendingDRAdp["+pendingDRAdp+"]reorderLevel["+reorderLevel+"]");

					if(isDetailReq)
					{
						 System.out.println("@@@@@010415:::itemCodeAdp["+itemCodeAdp+"]demandAdp["+demandAdp+"]-supplyAdp["+supplyAdp+"]+reorderLevel["+reorderLevel+"]");
					 	
						 /*if((demandAdp - supplyAdp) < reorderLevel  )
							{
								adpElement.setDemand(demandAdp-supplyAdp+reorderLevel);
							}*/
						 if(reorderLevel>0)
						 {
							 if( supplyAdp == 0 && checkNull(saleOrderAdp).trim().length() > 0 )
								{
									//demandAdp = demandAdp + reorderLevel ;
									demandAdp = reorderLevel ;
								    adpElement.setDemand(demandAdp);
								
								    boolean mrpFlag = false;
								    ArrayList <TimeMRP>timemrpList=adpElement.getTimeMrpList();
			                         ArrayList <TimeMRP>timemrpListN=new ArrayList<TimeMRP>();
			                         if(timemrpList.size()>0)
			                         {
			                                 for(int k=0;k<timemrpList.size();k++)
			                                 {
			                                         TimeMRP tmp=timemrpList.get(k);
			                                         if( tmp.getDemand() > 0  && mrpFlag == false )
			                                         {
			                                        	 System.out.println("@@@@@010415:::itemCodeAdp["+itemCodeAdp+"] tmp.getDemand()["+tmp.getDemand()+"]-tmp.getSupply()["+tmp.getSupply()+"]+reorderLevel["+reorderLevel+"]");
			                                        	 tmp.setDemand( demandAdp ) ;
			                                        	 System.out.println("@@@@@010415:::tmp.getDemand()["+tmp.getDemand()+"]");
			                                             //tmp.setRunningDemand(reorderLevel);
			                                         	 tmp.setRunningDemand( demandAdp );
			                                         	 System.out.println("@@@@@010415:::tmp.getRunningDemand()["+tmp.getRunningDemand()+"]");
			                                         	mrpFlag = true;
			                                         }
			                                         timemrpListN.add(tmp);
			                                         
			                                 }
			                                 adpElement.SetTimeMRPArr(timemrpListN);
			                         }
								
								}
							 if( supplyAdp > 0)
							 {
								 double netReqd=0,planSupply=0;
									 netReqd=adpElement.getDemand()-adpElement.getSupply();
										planSupply=adpElement.getDemand()-adpElement.getSupply()+reorderLevel;
										System.out.println("netReqd["+netReqd+"]");
										System.out.println("before deduction planSupply["+planSupply+"]");
										if(netReqd>0)
										{
											planSupply=planSupply-netReqd;
										}
										System.out.println("after  deduction planSupply["+planSupply+"]");
										boolean mrpFlag = false;
									    ArrayList <TimeMRP>timemrpList=adpElement.getTimeMrpList();
				                         ArrayList <TimeMRP>timemrpListN=new ArrayList<TimeMRP>();
				                         if(timemrpList.size()>0)
				                         {
				                                 for(int k=0;k<timemrpList.size();k++)
				                                 {
				                                         TimeMRP tmp=timemrpList.get(k);
				                                         System.out.println("3685--tmp.getDemand()["+tmp.getDemand()+"]tmp.getRunningDemand()["+tmp.getRunningDemand()+"]");
				                                         if( tmp.getSupply() > 0  && mrpFlag == false )
				                                         {
				                                        	 System.out.println("@@@@@010415:::itemCodeAdp["+itemCodeAdp+"] tmp.getDemand()["+tmp.getDemand()+"]-tmp.getSupply()["+tmp.getSupply()+"]+reorderLevel["+reorderLevel+"]");
				                                        	 tmp.setDemand(planSupply ) ;
				                                        	 System.out.println("@@@@@010415:::tmp.getDemand()["+tmp.getDemand()+"]");
				                                             //tmp.setRunningDemand(reorderLevel);
				                                         	 tmp.setRunningDemand(adpElement.getDemand()+planSupply );
				                                         	 System.out.println("@@@@@010415:::tmp.getRunningDemand()["+tmp.getRunningDemand()+"]");
				                                         	 System.out.println("3694--tmp.getDemand()["+tmp.getDemand()+"]tmp.getRunningDemand()["+tmp.getRunningDemand()+"]");
				                                         	 System.out.println("3695---adpElement.getDemand()["+adpElement.getDemand()+"]");
				                                         	 adpElement.setDemand(adpElement.getDemand()+planSupply);
				                                         	
				                                         	mrpFlag = true;
				                                         }
				                                         timemrpListN.add(tmp);
				                                         
				                                 }
				                                 adpElement.SetTimeMRPArr(timemrpListN);
				                         }
										//adpElement.setDemand(dueDate,planSupply, adpElement.getSaleOrder(),adpElement.getLineNo());
										adpElement.setReordPlanQty(planSupply);
								 }
						 }
							
							
							
							
						 
						 
						 ArrayList<HashMap<String, ADPElement>> detList=adpElement.getDetList();
						for(int l=0;l<detList.size();l++)
						{
							HashMap<String,ADPElement> detMap=detList.get(l);
							Set keyset=detMap.keySet();
							Iterator<String> itr=keyset.iterator();
							while(itr.hasNext())
							{
								String key=itr.next();
								//cpatil-25/08/14-System.out.println("key----"+key);
								if(key!=null && (checkNull(key).trim()).length()>0)
								{
									System.out.println("inside--detMap.get(key).getItemCode["+detMap.get(key).getItemCode()+"]detMap.get(key).getSiteCode["+detMap.get(key).getSiteCode()+"]detMap.get(key).getPendingPO()["+detMap.get(key).getPendingPO()+"]detMap.get(key).getDemand()["+detMap.get(key).getDemand()+"]detMap.get(key).getSupply()["+detMap.get(key).getSupply()+"]detMap.get(key).getPendingDO["+detMap.get(key).getPendingDO()+"]detMap.get(key).getPendingDR["+detMap.get(key).getPendingDR()+"]detMap.get(key).getPendingIndent["+detMap.get(key).getPendingIndent()+"]detMap.get(key).getStockQty["+detMap.get(key).getStockQty()+"]");
								}
							}
						}
					}
				}

			}
			else
			{
				for (int ctr = 0; ctr < adpeList.size(); ctr++)
				{

					ADPElement adpElement = (ADPElement) adpeList.get(ctr);
					adpElement = populateDemandSupply(adpElement);
					adpeList.set(ctr, adpElement);
					//cpatil-25/08/14-System.out.println("Quarantine stock["+adpElement.getQtStk()+"]");
					//cpatil-25/08/14-System.out.println("SaleSales order set in ADPElement---"+adpElement.getSiteCode()+"---"+adpElement.getItemCode()+"---"+adpElement.getSaleOrder()+"----"+adpElement.getLineNo());
					if(isDetailReq)
					{
						ArrayList<HashMap<String, ADPElement>> detList=adpElement.getDetList();
						for(int l=0;l<detList.size();l++)
						{
							HashMap<String,ADPElement> detMap=detList.get(l);
							Set keyset=detMap.keySet();
							Iterator<String> itr=keyset.iterator();
							while(itr.hasNext())
							{
								String key=itr.next();
								//cpatil-25/08/14-System.out.println("key----"+key);
								if(key!=null && (checkNull(key).trim()).length()>0)
								{
									System.out.println("inside--detMap.get(key).getItemCode["+detMap.get(key).getItemCode()+"]detMap.get(key).getSiteCode["+detMap.get(key).getSiteCode()+"]detMap.get(key).getPendingPO()["+detMap.get(key).getPendingPO()+"]detMap.get(key).getDemand()["+detMap.get(key).getDemand()+"]detMap.get(key).getSupply()["+detMap.get(key).getSupply()+"]detMap.get(key).getPendingDO["+detMap.get(key).getPendingDO()+"]detMap.get(key).getPendingDR["+detMap.get(key).getPendingDR()+"]detMap.get(key).getPendingIndent["+detMap.get(key).getPendingIndent()+"]");
								}
							}
						}
					}


					//System.out.println("Detail level Demand Supply set in ADPElement---"+adpElement.getDetMap());
				}
			} //end if 
		} catch (Exception e)
		{
			throw (e);
		}
	}


	private ADPElement populateDemandSupply(ADPElement adpElement) throws Exception
	{
		double demand = 0;
		double supply = 0;
		java.sql.Timestamp dueDate = null;
		String itemCode = null;
		String siteCode = null;
		// 12/04/10 manoharan MF90BHU001
		double stockQty = 0;
		double othSupply = 0;
		// end 12/04/10 manoharan MF90BHU001

		// Variables declared by gulzar on 4/18/2012
		double pendPOQty = 0;
		double pendDOQty = 0;
		double pendIndQty = 0;
		double pendDRQty = 0;

		// End changes by gulzar on 4/18/2012

		// Variable Declared by Sachin on 24/6/2013

		double availStk = 0;
		double quarntineStk = 0;

		// End Variable Declared by Sachin on 24/6/2013

		Statement stmt = null;
		ResultSet rs = null;
		errString = "";
		String adpQuery = null;
		PreparedStatement pstmt = null;
		String saleOrder = null;
		String lineNo = null;
		//Added By Manoj dtd 31/10/2013
		String tranId="";
		String tranSer="";
		double prevdemand=0;
		double prevsupply=0;
		double prevstockQty=0;
		double prevothSupply=0;
		double prevpendPOQty=0;
		double prevpendDOQty=0;
		double prevpendIndQty=0;
		double prevpendDRQty=0;
		double qtStk=0;//added by Chandrashekar 0n 11-08-14

		try
		{
			itemCode = adpElement.getItemCode();
			siteCode = adpElement.getSiteCode();
			// 01/04/11 manoharan if made to order is selected and item is of
			// made to order
			// don't process here
			System.out.println("populateDemandSupply...called....siteCode--["+siteCode+"]itemCode-["+itemCode+"]itemCodeTo-["+itemCodeTo+"]");
			//cpatil-25/08/14-System.out.println("madeToOrder---"+madeToOrder+"----adpElement.getMfgType()----"+adpElement.getMfgType());
			/* Commented by Manoj dtd 30/12/2013 calling same method for all items
			 if ("0".equals(madeToOrder) && "O".equals(adpElement.getMfgType()))
			{
				return adpElement;
			}*/
			// end 01/04/11 manoharan
			// //cpatil-25/08/14-System.out.println("commonConstants.DB_NAME "+CommonConstants.DB_NAME);
			// 14-02-2007 manoharan
			String sqlFileName = null;
			System.out.println("matPlan---"+matPlan+"----mfgPlan----"+mfgPlan);
			System.out.println("isDetailReq2------["+isDetailReq+"]");
			if (matPlan.equalsIgnoreCase("N") && mfgPlan.equalsIgnoreCase("N"))
			{
				sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "demandsupplyforecastonly";
			}
			else if (matPlan.equalsIgnoreCase("Y") && mfgPlan.equalsIgnoreCase("N"))
			{


				//cpatil-25/08/14-System.out.println("wnName1["+wnName1+"]");
				if(wnName1.trim().equals("w_requirement"))
				{
					sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "demandsupplymaterialReq";
				}
				else
				{
					sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "demandsupplymaterial";
				}
			} else
			{
				//Condition Added By manoj dtd 31/10/2013 to get demand supply at detail level
				//cpatil-25/08/14-System.out.println("isDetailReq------"+isDetailReq);
				if(isDetailReq)
				{
					sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "demandsupplyDetail";	
				}
				else
				{
					sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "demandsupply";	
				}

			}

			//cpatil-25/08/14-System.out.println("sqlFileName---"+sqlFileName);
			// end 14-02-2007 manoharan

			if ((CommonConstants.DB_NAME).equalsIgnoreCase("db2"))
			{
				// System.out.println("Firing DB2 Sql For Site Code :" +
				// siteCode + " Item Code : " + itemCode + " From Date : " +
				// dateFrom + " To Date : "+ dateTo + " StandgOrdTypes : "+
				// standingOrdTypes +" MadeToOrder " +madeToOrder+
				// " MadeToStock : " + madeToStock);
				// 14-02-2007 manoharan
				// String adpQueryOriginal = readFile(CommonConstants.JBOSSHOME
				// + File.separator +"sql" + File.separator +
				// "demandsupplyDB2.sql");
				String adpQueryOriginal = readFile(sqlFileName + "DB2.sql");
				// end 14-02-2007 manoharan

				String strDateFrom = dateFrom.toString();
				strDateFrom = strDateFrom.replaceAll(" ", "-");
				strDateFrom = strDateFrom.replaceAll(":", ".");
				String strDateTo = dateTo.toString();
				strDateTo = strDateTo.replaceAll(" ", "-");
				strDateTo = strDateTo.replaceAll(":", ".");
				/*
				 * // 01-10-2007 manoharan String strRunDate =
				 * runDate.toString(); strRunDate =
				 * strRunDate.replaceAll(" ","-"); strRunDate =
				 * strRunDate.replaceAll(":","."); // end 01-10-2007 manoharan
				 */
				adpQuery = adpQueryOriginal;
				// System.out.println("Afetr Reading File adpQuery..");
				adpQuery = adpQuery.replaceAll("@sitecode@", siteCode);
				adpQuery = adpQuery.replaceAll("@itemcode@", itemCode);
				adpQuery = adpQuery.replaceAll("@fromdate@", dateFromString);
				adpQuery = adpQuery.replaceAll("@todate@", dateToString);
				adpQuery = adpQuery.replaceAll("@ordtypes@", standingOrdTypes);
				adpQuery = adpQuery.replaceAll("@madetoorder@", madeToOrder);
				adpQuery = adpQuery.replaceAll("@madetostock@", madeToStock);
				// 01-10-2007 manoharan
				adpQuery = adpQuery.replaceAll("@rundate@", runDateString);
				// end 01-10-2007 manoharan
			} else if ((CommonConstants.DB_NAME).equalsIgnoreCase("oracle"))
			{
				// 14-02-2007 manoharan
				// String adpQueryOriginal = readFile(CommonConstants.JBOSSHOME
				// + File.separator +"sql" + File.separator +
				// "demandsupplyOracle.sql");
				String adpQueryOriginal = readFile(sqlFileName + "Oracle.sql");
				// end 14-02-2007 manoharan
				adpQuery = adpQueryOriginal;
				// System.out.println("Replacing Values.in SQL.....");
				adpQuery = adpQuery.replaceAll("@sitecode@", siteCode);
				adpQuery = adpQuery.replaceAll("@itemcode@", itemCode);
				adpQuery = adpQuery.replaceAll("@fromdate@", dbDateFrom);
				adpQuery = adpQuery.replaceAll("@todate@", dbDateTo);
				adpQuery = adpQuery.replaceAll("@ordtypes@", standingOrdTypes);
				adpQuery = adpQuery.replaceAll("@madetoorder@", madeToOrder);
				adpQuery = adpQuery.replaceAll("@madetostock@", madeToStock);
				// 01-10-2007 manoharan
				adpQuery = adpQuery.replaceAll("@rundate@", dbRunDate);
				// end 01-10-2007 manoharan
				// System.out.println("Replaced Values.in SQL.....");
			}
			FileOutputStream fout = null;
			BufferedWriter bw = null;
			fout = new FileOutputStream("demandsupply.sql");
			bw = new BufferedWriter(new OutputStreamWriter(fout));
			bw.write(adpQuery);
			bw.close();
			fout.close();

			// stmt = conn.createStatement();
			// System.out.println("Executing Query After Replacement.....");
			// rs = stmt.executeQuery(adpQuery);
			pstmt = conn.prepareStatement(adpQuery);
			rs = pstmt.executeQuery();

			// System.out.println("Query Executed for item : " + itemCode);
			String rsItemCode = "", adpItemcode = "";
			while (rs.next())
			{
				System.out.println("@@@@@@3766 sql executed.....");
				// item code == != sitecode ,item find adpelemt list index demand,
				// supply
				rsItemCode = rs.getString(1);// Added by JIten 02/11/06 as per
				// Manoharan Sir
				dueDate = rs.getTimestamp(2);
				demand = rs.getDouble(3);
				supply = rs.getDouble(4);
				// 12/04/10 manoharan MF90BHU001 stock and other supply to be
				// separated
				stockQty = rs.getDouble(5);
				othSupply = rs.getDouble(6);
				// end 12/04/10 manoharan

				// Changes made by Gulzar on 4/18/2012
				pendDOQty = rs.getDouble(8);
				pendDRQty = rs.getDouble(10);

				pendIndQty = rs.getDouble(9);
				pendPOQty = rs.getDouble(7);
				if(isRequirement)
				{
					qtStk = rs.getDouble(12);
				}
				//cpatil-25/08/14-System.out.println("isDetailReq3------"+isDetailReq);
				if(isDetailReq)
				{
					tranId=rs.getString("tran_id");
					tranSer=rs.getString("tran_ser");
				}
				// End Changes by Gulzar on 4/18/2012

				// 18-11-2006 manoharan if dueDate < dateFrom then set the
				// dueDate as dateFrom

				if (dueDate.compareTo(dateFrom) < 0)
				{
					dueDate = dateFrom;
				}
				// end 18-11-2006 manoharan
				// if else condition added by Jiten as per Manoharan Sir
				// 02/11/06
				//cpatil-25/08/14-System.out.println("2804--isDetailReq------"+isDetailReq+"----"+rsItemCode+"---"+itemCode);
				if (rsItemCode != null && rsItemCode.trim().equalsIgnoreCase(itemCode.trim()))
				{
					System.out.println("dueDate---demand---supply"+dueDate+"---"+demand+"---"+supply);

					//Condition added by Manoj dtd 30/12/2013 to set emand =0 
					if("0".equals(madeToOrder) && "O".equals(adpElement.getMfgType()))
					{
						demand=0;
					}

					if(!isDetailReq)
					{
						adpElement.setDemand(dueDate, demand, "          ", "   ");
					}
					adpElement.setSupply(dueDate, supply);
					// // 12/04/10 manoharan MF90BHU001
					adpElement.setStockQty(dueDate, stockQty);
					adpElement.setOthSupply(dueDate, othSupply);
					// // end 12/04/10 manoharan MF90BHU001
					//
					// // Changes made by Gulzar on 4/18/2012
					adpElement.setPendingPO(dueDate, pendPOQty);
					adpElement.setPendingDO(dueDate, pendDOQty);
					adpElement.setPendingIndent(dueDate, pendIndQty);
					adpElement.setPendingDR(dueDate, pendDRQty);
					if(isRequirement)
					{
						adpElement.setQtStk(qtStk);
					}
					if(isDetailReq)
					{
						/*
						 //Changes by Manoj dtd 31/10/2013 regarding Detail level data
						adpElement.setDemand(dueDate, demand, "          ", "   ");
						adpElement.setSupply(dueDate, supply);
						// // 12/04/10 manoharan MF90BHU001
						adpElement.setStockQty(dueDate, stockQty);
						adpElement.setOthSupply(dueDate, othSupply);
						// // end 12/04/10 manoharan MF90BHU001
						//
						// // Changes made by Gulzar on 4/18/2012
						adpElement.setPendingPO(dueDate, pendPOQty);
						adpElement.setPendingDO(dueDate, pendDOQty);
						adpElement.setPendingIndent(dueDate, pendIndQty);
						adpElement.setPendingDR(dueDate, pendDRQty);
						prevdemand+=demand;
						prevsupply+=supply;
						prevstockQty+=stockQty;
						prevothSupply+=othSupply;
						prevpendPOQty+=pendPOQty;
						prevpendDOQty+=pendDOQty;
						prevpendIndQty+=pendIndQty;
						prevpendDRQty+=pendDRQty;*/

						ADPElement detADPElement=new ADPElement();
						//detADPElement.setDemand(dueDate, demand, "          ", "   ");
						detADPElement.setSupply(dueDate, supply);

						detADPElement.setStockQty(dueDate, stockQty);
						detADPElement.setOthSupply(dueDate, othSupply);
						detADPElement.setPendingPO(dueDate, pendPOQty);
						detADPElement.setPendingDO(dueDate, pendDOQty);
						detADPElement.setPendingIndent(dueDate, pendIndQty);
						detADPElement.setPendingDR(dueDate, pendDRQty);
						//cpatil-25/08/14-System.out.println("Setting SaleOrder in Detail record---"+adpElement.getSaleOrder());
						//cpatil-25/08/14-System.out.println("Setting Line No in Detail record---"+adpElement.getLineNo());
						detADPElement.setSaleOrder(adpElement.getSaleOrder());
						detADPElement.setLineNo(adpElement.getLineNo());
						//cpatil-25/08/14-System.out.println("detADPElement.getPendingPO()----"+detADPElement.getPendingPO());
						HashMap<String, ADPElement> detMap=new HashMap<String, ADPElement>();
						System.out.println("tranId#tranSer----"+tranId+"#"+tranSer);
						detMap.put(tranId+"#"+tranSer, detADPElement);
						//detMap=setAltItemSupply(detMap,altitemMap,adpElement.getItemCode(),conn);
						ArrayList<HashMap<String, ADPElement>> alist=adpElement.getDetList();
						//cpatil-25/08/14-System.out.println("alist.size()-1---"+alist.size());
						if(detMap.size()>0)
						{
							alist.add( detMap);
						}

						//cpatil-25/08/14-System.out.println("alist.size()-2---"+alist.size());
						//adpElement.setDetMap(detMap);
						adpElement.setDetList(alist);
						detMap=null;
						detADPElement=null;
						alist=null;


					}



				} else
				{
					//cpatil-25/08/14-System.out.println("Site Code :: " + siteCode + " rsItemCode :: " + rsItemCode + " Item Code :: " + itemCode);
					int ctr = indexOfADPElement(siteCode, rsItemCode, "          ", "   ");
					// System.out.println("AdpList : "+adpeList.size()+"Index ctr :: "+ctr);//Added
					// by Jiten 09/11/06 Sun
					if (ctr > 0)
					{// if condition added by jiten as per Manoharan Sir
						// 10/11/06
						ADPElement tempADPElement = (ADPElement) adpeList.get(ctr);
						tempADPElement.setDemand(dueDate, demand, "          ", "   ");
						tempADPElement.setSupply(dueDate, supply);
						adpeList.set(ctr, tempADPElement);
					} else if (ctr == -1)
					{// Else if condition added by jiten 10/11/06 as per Tarun
						// Bhai to write for skipped item
						this.fw1.write(siteCode + "	 " + itemCode + "	" + rsItemCode + "\r\n");
					}
				}
				// End addding
				System.out.println(adpElement.getSupply());
				if (demand != 0 || supply != 0)
				{

					if (adpElement.getSuppSour().equals("M"))
						// System.out.println("adpQuery ::"+adpQuery);
						System.out.println("Site Code : " + siteCode + "   Item Code : " + itemCode + "    Due Date : " + dueDate + "     Demand : " + demand + " supply : " + supply);
				}
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			System.out.println("@@@@@@3934:outside itemCodeTo["+itemCodeTo+"]isBomReplace["+isBomReplace+"]adpElement.getItemCode()["+adpElement.getItemCode()+"]");

			/*if(isBomReplace &&  itemCodeTo.equalsIgnoreCase(adpElement.getItemCode()))
			{
				System.out.println("@@@@@@3934:itemCodeTo["+itemCodeTo+"]dueDate["+dueDate+"]bomReplaceDemand["+bomReplaceDemand+"]");
				adpElement.setDemand(dueDate, bomReplaceDemand, "          ", "   ");
			}
			 */
		} catch (SQLException se)
		{
			System.out.println("SQLException :RunMRPPrcEJB : populateDemandSupply(ADPElement).." + se.getMessage());
			System.out.println(adpQuery);
			se.printStackTrace();
			errString = se.getMessage();
			throw new ITMException(se);
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB : populateDemandSupply(ADPElement):...." + e.getMessage() + ":");
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			if (pstmt != null)
			{
				pstmt = null;
			}
			if (rs != null)
			{
				rs = null;
			}
			this.fw1.flush();// Added by jiten 10/11/06
			// System.out.println("populateDemandSupply() finally block......");
			// return adpElement;
		}
		// ResultSetMetaData rsmd = rs.getMetaData();
		// int noOfColumns = rsmd.getColumnCount();

		// return commented & changed by sabyasachi 25-03-2011
		// return adpElement; //Moved here from finaly - jiten - 03/11/06
		return adpElement;
		// end return commented & changed by sabyasachi 25-03-2011
	}

	private void populateDemandSupply(ArrayList adpList) throws Exception
	{
		double demand = 0;
		double supply = 0;
		java.sql.Timestamp dueDate = null;
		String itemCode = null;
		String siteCode = null;
		// 12/04/10 manoharan MF90BHU001
		double stockQty = 0;
		double othSupply = 0;
		// end 12/04/10 manoharan MF90BHU001

		// Variables declared by gulzar on 4/18/2012
		double pendPOQty = 0;
		double pendDOQty = 0;
		double pendIndQty = 0;
		double pendDRQty = 0;

		// End changes by gulzar on 4/18/2012

		// Variable Declared by Sachin on 24/6/2013

		double availStk = 0;
		double quarntineStk = 0;

		// End Variable Declared by Sachin on 24/6/2013

		Statement stmt = null;
		ResultSet rs = null;
		errString = "";
		String adpQuery = null;
		PreparedStatement pstmt = null;
		String saleOrder = null;
		String lineNo = null;
		//Added By Manoj dtd 31/10/2013
		String tranId="";
		String tranSer="";
		double prevdemand=0;
		double prevsupply=0;
		double prevstockQty=0;
		double prevothSupply=0;
		double prevpendPOQty=0;
		double prevpendDOQty=0;
		double prevpendIndQty=0;
		double prevpendDRQty=0;
		double qtStk=0;//added by Chandrashekar 0n 11-08-14
		String siteCodeAdp="",tempitemCodeList="";
		double reorderLevel=0,planSupply=0,netReqd=0;

		try
		{

			System.out.println("@@@@ populateDemandSupply(ArrayList adpList) cpatil adpList["+adpList.size()+"]");
			for ( int ctr1 = 0; ctr1 < adpList.size(); ctr1++ )  //Loop for each node of current detail
			{
				ADPElement adpElement = (ADPElement) adpeList.get(ctr1);

				itemCode = adpElement.getItemCode();
				siteCodeAdp = adpElement.getSiteCode();

				System.out.println("@@@cpatil_sale_order==["+saleOrder+"]itemCode==["+itemCode+"]siteCodeAdp["+siteCodeAdp+"]");
				System.out.println("ctr1=="+ctr1);
				if(ctr1 > 0)
				{
					tempitemCodeList = tempitemCodeList + ",'"+siteCodeAdp+itemCode+"'" ;
				}
				else
				{
					//tempitemCodeList = "'"+siteCode+itemCode+"'" ;
					tempitemCodeList = "'"+siteCodeAdp+itemCode+"'" ;
				}
				//adpElement=null;	//cpatilnull
			}
			System.out.println("@@@@@@@@ before tempitemCodeList==["+tempitemCodeList+"]");

			tempitemCodeList = tempitemCodeList.substring(1, tempitemCodeList.length()-1);

			System.out.println("@@@@@@@@ after tempitemCodeList==["+tempitemCodeList+"]");



			//itemCode = adpElement.getItemCode();
			//siteCode = adpElement.getSiteCode();
			// 01/04/11 manoharan if made to order is selected and item is of
			// made to order
			// don't process here
			//cpatil-25/08/14-System.out.println("siteCode----"+siteCode+"itemCode----"+itemCode);
			//cpatil-25/08/14-System.out.println("madeToOrder---"+madeToOrder+"----adpElement.getMfgType()----"+adpElement.getMfgType());
			/* Commented by Manoj dtd 30/12/2013 calling same method for all items
			 if ("0".equals(madeToOrder) && "O".equals(adpElement.getMfgType()))
			{
				return adpElement;
			}*/
			// end 01/04/11 manoharan
			// //cpatil-25/08/14-System.out.println("commonConstants.DB_NAME "+CommonConstants.DB_NAME);
			// 14-02-2007 manoharan
			String sqlFileName = null;
			System.out.println("matPlan---"+matPlan+"----mfgPlan----"+mfgPlan);
			System.out.println("isDetailReq2------"+isDetailReq);
			if (matPlan.equalsIgnoreCase("N") && mfgPlan.equalsIgnoreCase("N"))
			{
				sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "demandsupplyforecastonly";
			}
			else if (matPlan.equalsIgnoreCase("Y") && mfgPlan.equalsIgnoreCase("N"))
			{


				//cpatil-25/08/14-System.out.println("wnName1["+wnName1+"]");
				if(wnName1.trim().equals("w_requirement"))
				{
					sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "demandsupplymaterialReq";
				}
				else
				{
					sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "demandsupplymaterial";
				}
			} else
			{
				//Condition Added By manoj dtd 31/10/2013 to get demand supply at detail level
				//cpatil-25/08/14-System.out.println("isDetailReq------"+isDetailReq);
				if(isDetailReq)
				{
					sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "demandsupplyDetail";	
				}
				else
				{
					sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "demandsupply";	
				}

			}

			//cpatil-25/08/14-System.out.println("sqlFileName---"+sqlFileName);
			// end 14-02-2007 manoharan

			if ((CommonConstants.DB_NAME).equalsIgnoreCase("db2"))
			{
				// System.out.println("Firing DB2 Sql For Site Code :" +
				// siteCode + " Item Code : " + itemCode + " From Date : " +
				// dateFrom + " To Date : "+ dateTo + " StandgOrdTypes : "+
				// standingOrdTypes +" MadeToOrder " +madeToOrder+
				// " MadeToStock : " + madeToStock);
				// 14-02-2007 manoharan
				// String adpQueryOriginal = readFile(CommonConstants.JBOSSHOME
				// + File.separator +"sql" + File.separator +
				// "demandsupplyDB2.sql");
				String adpQueryOriginal = readFile(sqlFileName + "DB2.sql");
				// end 14-02-2007 manoharan

				String strDateFrom = dateFrom.toString();
				strDateFrom = strDateFrom.replaceAll(" ", "-");
				strDateFrom = strDateFrom.replaceAll(":", ".");
				String strDateTo = dateTo.toString();
				strDateTo = strDateTo.replaceAll(" ", "-");
				strDateTo = strDateTo.replaceAll(":", ".");
				/*
				 * // 01-10-2007 manoharan String strRunDate =
				 * runDate.toString(); strRunDate =
				 * strRunDate.replaceAll(" ","-"); strRunDate =
				 * strRunDate.replaceAll(":","."); // end 01-10-2007 manoharan
				 */
				adpQuery = adpQueryOriginal;
				// System.out.println("Afetr Reading File adpQuery..");
				//adpQuery = adpQuery.replaceAll("@sitecode@", siteCode);
				adpQuery = adpQuery.replaceAll("@itemcode@", tempitemCodeList);
				adpQuery = adpQuery.replaceAll("@fromdate@", dateFromString);
				adpQuery = adpQuery.replaceAll("@todate@", dateToString);
				adpQuery = adpQuery.replaceAll("@ordtypes@", standingOrdTypes);
				adpQuery = adpQuery.replaceAll("@madetoorder@", madeToOrder);
				adpQuery = adpQuery.replaceAll("@madetostock@", madeToStock);
				// 01-10-2007 manoharan
				adpQuery = adpQuery.replaceAll("@rundate@", runDateString);
				// end 01-10-2007 manoharan
			} else if ((CommonConstants.DB_NAME).equalsIgnoreCase("oracle"))
			{
				// 14-02-2007 manoharan
				// String adpQueryOriginal = readFile(CommonConstants.JBOSSHOME
				// + File.separator +"sql" + File.separator +
				// "demandsupplyOracle.sql");
				String adpQueryOriginal = readFile(sqlFileName + "Oracle.sql");
				// end 14-02-2007 manoharan
				adpQuery = adpQueryOriginal;
				// System.out.println("Replacing Values.in SQL.....");
				//adpQuery = adpQuery.replaceAll("@sitecode@", siteCode);
				adpQuery = adpQuery.replaceAll("@itemcode@", tempitemCodeList );
				adpQuery = adpQuery.replaceAll("@fromdate@", dbDateFrom);
				adpQuery = adpQuery.replaceAll("@todate@", dbDateTo);
				adpQuery = adpQuery.replaceAll("@ordtypes@", standingOrdTypes);
				adpQuery = adpQuery.replaceAll("@madetoorder@", madeToOrder);
				adpQuery = adpQuery.replaceAll("@madetostock@", madeToStock);
				// 01-10-2007 manoharan
				adpQuery = adpQuery.replaceAll("@rundate@", dbRunDate);
				// end 01-10-2007 manoharan
				// System.out.println("Replaced Values.in SQL.....");
			}
			FileOutputStream fout = null;
			BufferedWriter bw = null;
			fout = new FileOutputStream("demandsupply.sql");
			bw = new BufferedWriter(new OutputStreamWriter(fout));
			bw.write(adpQuery);
			bw.close();
			fout.close();

			// stmt = conn.createStatement();
			// System.out.println("Executing Query After Replacement.....");
			// rs = stmt.executeQuery(adpQuery);
			pstmt = conn.prepareStatement(adpQuery);
			rs = pstmt.executeQuery();

			// System.out.println("Query Executed for item : " + itemCode);
			String rsItemCode = "", adpItemcode = "",rsSiteCode="";
			HashMap<String, ArrayList<DataBean>> dataMap = new HashMap<String, ArrayList<DataBean>>();
			//	HashMap<K, V>
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
			Timestamp today = new java.sql.Timestamp(System.currentTimeMillis()) ;
			today = java.sql.Timestamp.valueOf(sdf.format(today) + " 00:00:00.000");

			while(rs.next())
			{

				DataBean dataBeanObject = new DataBean();
				rsItemCode = rs.getString(1);
				rsSiteCode = rs.getString(13);
				dueDate=rs.getTimestamp(2);
				if(dueDate.compareTo(today)<0)
				{
					dueDate=today;
				}
				//rsSiteCode = siteCode;
				dataBeanObject.setItemCode(rs.getString(1));
				dataBeanObject.setDueDate(dueDate);
				dataBeanObject.setDemand(rs.getDouble(3));
				dataBeanObject.setSupply(rs.getDouble(4));
				dataBeanObject.setStockQty(rs.getDouble(5));
				dataBeanObject.setOthSupply(rs.getDouble(6));
				dataBeanObject.setPendDOQty(rs.getDouble(8));
				dataBeanObject.setPendDRQty(rs.getDouble(10));

				dataBeanObject.setPendIndQty(rs.getDouble(9));
				dataBeanObject.setPendPOQty(rs.getDouble(7));
				if(isDetailReq)
				{
					tranId=rs.getString("tran_id");
					tranSer=rs.getString("tran_ser");

					dataBeanObject.setTranId(tranId);
					dataBeanObject.setTranSer(tranSer);
				}

				System.out.println("@@@_for setmap:::itemCode==["+rs.getString(1)+"]siteCode["+rs.getString(13)+"]demand["+rs.getDouble(3)+"]supply["+rs.getDouble(4)+"]stockQty["+rs.getDouble(5)+"]othSupply["+rs.getDouble(6)+"]pendingPO["+rs.getDouble(7)+"]pendingDO["+rs.getDouble(8)+"]pendingIndent["+rs.getDouble(9)+"]pendingDR["+rs.getDouble(10)+"]");

				if( dataMap.containsKey(siteCodeAdp+rsItemCode) )
				{
					ArrayList tempAdpElementList =  (ArrayList) dataMap.get(rsSiteCode+rsItemCode);
					tempAdpElementList.add(dataBeanObject);
					dataMap.put(rsSiteCode+rsItemCode,tempAdpElementList); 
					//adpElementMap.put(siteCodeAdp+rsItemCode,adpElementList);
				}
				else
				{
					ArrayList tempAdpElementList =  new ArrayList();
					tempAdpElementList.add(dataBeanObject);
					dataMap.put(rsSiteCode+rsItemCode,tempAdpElementList);
					//adpElementMap.put(siteCodeAdp+rsItemCode, adpElementList);
				}

				dataBeanObject = null;

			}	
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			System.out.println("adpList.size["+adpList.size()+"]adpList["+adpList+"]");
			for( int ctr=0; ctr < adpList.size() ; ctr++ )
			{
				ADPElement adpElement = (ADPElement) adpeList.get(ctr);
				ArrayList adpElementListValueAll = new ArrayList();

				itemCode = adpElement.getItemCode();
				siteCodeAdp = adpElement.getSiteCode();

				//System.out.println("dataMap["+dataMap+"]");
				if( dataMap != null  && dataMap.containsKey(siteCodeAdp+itemCode))
				{
					adpElementListValueAll =  dataMap.get(siteCodeAdp+itemCode);  
				}
				//System.out.println("@@@@@ value get from map.....");
				//System.out.println("adpElementListValueAll.size["+adpElementListValueAll.size()+"]");

				for( int ctrList =0; ctrList < adpElementListValueAll.size(); ctrList++)
				{
					//ArrayList adpElementListValue = new ArrayList();

					DataBean  dataBeanTemp = (DataBean) adpElementListValueAll.get(ctrList);

					System.out.println("@@@_for getmap:::itemCode==["+itemCode+"]siteCode["+siteCodeAdp+"]demand["+dataBeanTemp.getDemand()+"]supply["+dataBeanTemp.getSupply()+"]stockQty["+dataBeanTemp.getStockQty()+"]othSupply["+dataBeanTemp.getOthSupply()+"]pendingPO["+dataBeanTemp.getPendPOQty()+"]pendingDO["+dataBeanTemp.getPendDOQty()+"]pendingIndent["+dataBeanTemp.getPendIndQty()+"]pendingDR["+dataBeanTemp.getPendDRQty()+"]");

					tranId = dataBeanTemp.getTranId();
					tranSer = dataBeanTemp.getTranSer();

					System.out.println("@@@tranId["+tranId+"]tranSer["+tranSer+"]");
					//dueDate = (Timestamp)adpElementListValue.get(1);
					dueDate = (Timestamp) dataBeanTemp.getDueDate();
					if("0".equals(madeToOrder) && "O".equals(adpElement.getMfgType()))
					{
						demand=0;
					}
					else
					{
						//demand = (Double) adpElementListValue.get(2);
						demand = (Double) dataBeanTemp.getDemand();

					}

					//adpElement.setDemand(dueDate, demand, "          ", "   ");
					//adpElement.setDemand(dueDate, demand,  "          ", "   ");
					//adpElement.setSupply(dueDate, supply);
					
					
					reorderLevel=adpElement.getReorderLevel();
					/*if(reorderLevel>0)
					{
						
						netReqd=adpElement.getDemand()-dataBeanTemp.getSupply();
						planSupply=adpElement.getDemand()-dataBeanTemp.getSupply()+reorderLevel;
						System.out.println("netReqd["+netReqd+"]");
						System.out.println("before deduction planSupply["+planSupply+"]");
						if(netReqd>0)
						{
							planSupply=planSupply-netReqd;
						}
						System.out.println("after  deduction planSupply["+planSupply+"]");
						////if(planSupply<=re)
						adpElement.setDemand(dueDate,planSupply, adpElement.getSaleOrder(),adpElement.getLineNo());
						adpElement.setReordPlanQty(planSupply);
					}*/
					
					adpElement.setSupply(dueDate, (Double) dataBeanTemp.getSupply());
					//adpElement.setStockQty(dueDate, stockQty);
					adpElement.setStockQty(dueDate, (Double) dataBeanTemp.getStockQty());
					//adpElement.setOthSupply(dueDate, othSupply);
					adpElement.setOthSupply(dueDate, (Double) dataBeanTemp.getOthSupply());
					//adpElement.setPendingPO(dueDate, pendPOQty);
					adpElement.setPendingPO(dueDate, (Double) dataBeanTemp.getPendPOQty());
					//adpElement.setPendingDO(dueDate, pendDOQty);
					adpElement.setPendingDO(dueDate, (Double) dataBeanTemp.getPendDOQty());
					//adpElement.setPendingIndent(dueDate, pendIndQty);
					adpElement.setPendingIndent(dueDate, (Double) dataBeanTemp.getPendIndQty());
					//adpElement.setPendingDR(dueDate, pendDRQty);
					adpElement.setPendingDR(dueDate, (Double) dataBeanTemp.getPendDRQty());

					if(isDetailReq)
					{
						System.out.println("@@@_for detail getmap:::itemCode==["+itemCode+"]siteCode["+siteCodeAdp+"]demand["+dataBeanTemp.getDemand()+"]supply["+dataBeanTemp.getSupply()+"]stockQty["+dataBeanTemp.getStockQty()+"]othSupply["+dataBeanTemp.getOthSupply()+"]pendingPO["+dataBeanTemp.getPendPOQty()+"]pendingDO["+dataBeanTemp.getPendDOQty()+"]pendingIndent["+dataBeanTemp.getPendIndQty()+"]pendingDR["+dataBeanTemp.getPendDRQty()+"]");

						ADPElement detADPElement=new ADPElement();
						//280115 detADPElement.setDemand(dueDate, demand, "          ", "   ");
						detADPElement.setSupply(dueDate, (Double) dataBeanTemp.getSupply() );

						//System.out.println("@@@@@@@@@@@@detADPElement.getSupply()["+detADPElement.getSupply()+"]");

						detADPElement.setStockQty(dueDate, (Double) dataBeanTemp.getStockQty());
						detADPElement.setOthSupply(dueDate, (Double) dataBeanTemp.getOthSupply());
						detADPElement.setPendingPO(dueDate, (Double) dataBeanTemp.getPendPOQty());
						detADPElement.setPendingDO(dueDate, (Double) dataBeanTemp.getPendDOQty());
						detADPElement.setPendingIndent(dueDate, (Double) dataBeanTemp.getPendIndQty());
						detADPElement.setPendingDR(dueDate, (Double) dataBeanTemp.getPendDRQty());
						//cpatil-25/08/14-System.out.println("Setting SaleOrder in Detail record---"+adpElement.getSaleOrder());
						//cpatil-25/08/14-System.out.println("Setting Line No in Detail record---"+adpElement.getLineNo());
						detADPElement.setSaleOrder(adpElement.getSaleOrder());
						detADPElement.setLineNo(adpElement.getLineNo());
						//cpatil-25/08/14-System.out.println("detADPElement.getPendingPO()----"+detADPElement.getPendingPO());
						HashMap<String, ADPElement> detMap=new HashMap<String, ADPElement>();
						System.out.println("tranId#tranSer----"+tranId+"#"+tranSer);
						detMap.put(tranId+"#"+tranSer, detADPElement);
						ArrayList<HashMap<String, ADPElement>> alist=adpElement.getDetList();
						//cpatil-25/08/14-System.out.println("alist.size()-1---"+alist.size());
						if(detMap.size()>0)
						{
							alist.add( detMap);
						}



						//alist.add(getAltItemSupply(adpElement.getSiteCode(),itemCode));
						//adpElement.setDetMap(detMap);
						//System.out.println("@@@@@@@@detADPElement["+detADPElement+"]");
						adpElement.setDetList(alist);
						//detMap=null;
						//detADPElement=null;
						//alist=null;


					}

					//dataBeanTemp = null;  //cpatilnull

				}
				Set setAltItem=altitemMap.keySet();

				System.out.println("@@@@@@ setAltItem["+setAltItem+"]");

				Iterator itrAltItem=setAltItem.iterator();
				while(itrAltItem.hasNext())
				{
					//System.out.println(" itrAltItem.next()---"+ (String) itrAltItem.next());
					String keyAlttem=(String) itrAltItem.next();
					System.out.println("keyAlttem----"+keyAlttem);

					if( adpElement.getItemCode() != null && adpElement.getItemCode().equalsIgnoreCase(keyAlttem) )
					{	
						ArrayList<String> altItemlist=altitemMap.get(keyAlttem);

						//cpatil-25/08/14-System.out.println("altItemlist.size()----"+altItemlist.size());
						for(int i=0;i<altItemlist.size();i++)
						{
							String altItem[]=altItemlist.get(i).split("@");
							System.out.println("Alternate Item["+altItem[0]+"]");
							adpElement.getDetList().add(getAltItemSupply(adpElement.getSiteCode(),altItem[0],altItem[1]));
						}
					}
					//adpElement.setDetList(alist);


				}


				System.out.println(adpElement.getSupply());
				if (demand != 0 || supply != 0)
				{

					if (adpElement.getSuppSour().equals("M"))
						System.out.println("Site Code : " + siteCode + "   Item Code : " + itemCode + "    Due Date : " + dueDate + "     Demand : " + demand + " supply : " + supply);
				}

				System.out.println("@@@@@@4354:outside itemCodeTo["+itemCodeTo+"]isBomReplace["+isBomReplace+"]adpElement.getItemCode()["+adpElement.getItemCode()+"]");
				if(isBomReplace &&  itemCodeTo.equalsIgnoreCase(adpElement.getItemCode()))
				{
					System.out.println("@@@@@@4357:itemCodeTo["+itemCodeTo+"]dueDate["+dueDate+"]bomReplaceDemand["+bomReplaceDemand+"]");
					adpElement.setDemand(dueDate, bomReplaceDemand, saleOrderReplaceBom,itemCodeTo);
					adpElement.setSaleOrder(saleOrderReplaceBom);
					adpElement.setLineNo(lineNoReplaceBom);
					adpElement.setItemCode(itemCodeTo);
				}


				//System.out.println("@@@@@ in ctr["+ctr+"]adpElement["+adpElement+"]");
				adpeList.set(ctr, adpElement);

				//adpElementListValueAll = null;   //cpatilnull

			}

			System.out.println("@@@@@ adpeList.size()["+adpeList.size()+"]");

		} catch (SQLException se)
		{
			System.out.println("SQLException :RunMRPPrcEJB : populateDemandSupply(ADPElement).." + se.getMessage());
			System.out.println(adpQuery);
			se.printStackTrace();
			errString = se.getMessage();
			throw new ITMException(se);
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB : populateDemandSupply(ADPElement):...." + e.getMessage() + ":");
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			if (pstmt != null)
			{
				pstmt = null;
			}
			if (rs != null)
			{
				rs = null;
			}
			this.fw1.flush();// Added by jiten 10/11/06
		}
	}


	private void populateDemandSupply1(ArrayList adpList) throws Exception  //added by cpatil on 20/11/14
	{
		double demand = 0;
		double supply = 0;
		java.sql.Timestamp dueDate = null;
		String itemCode = null;
		String siteCode = null;
		double stockQty = 0;
		double othSupply = 0;
		double pendPOQty = 0;
		double pendDOQty = 0;
		double pendIndQty = 0;
		double pendDRQty = 0;
		double availStk = 0;
		double quarntineStk = 0;
		Statement stmt = null;
		ResultSet rs = null;
		errString = "";
		String adpQuery = null;
		PreparedStatement pstmt = null;
		String saleOrder = null;
		String lineNo = null;
		String tranId="";
		String tranSer="";
		double prevdemand=0;
		double prevsupply=0;
		double prevstockQty=0;
		double prevothSupply=0;
		double prevpendPOQty=0;
		double prevpendDOQty=0;
		double prevpendIndQty=0;
		double prevpendDRQty=0;
		double qtStk=0; 
		String tempitemCodeList="",siteCodeAdp="";
		try
		{
			System.out.println("@@@@cpatil adpList["+adpList.size()+"]");
			for ( int ctr1 = 0; ctr1 < adpList.size(); ctr1++ )  //Loop for each node of current detail
			{
				ADPElement adpElement = (ADPElement) adpeList.get(ctr1);

				itemCode = adpElement.getItemCode();
				siteCodeAdp = adpElement.getSiteCode();

				System.out.println("@@@cpatil_sale_order==["+saleOrder+"]itemCode==["+itemCode+"]siteCodeAdp["+siteCodeAdp+"]");
				System.out.println("ctr1=="+ctr1);
				if(ctr1 > 0)
				{
					tempitemCodeList = tempitemCodeList + ",'"+siteCodeAdp+itemCode+"'" ;
				}
				else
				{
					//tempitemCodeList = "'"+siteCode+itemCode+"'" ;
					tempitemCodeList = "'"+siteCodeAdp+itemCode+"'" ;
				}
			}
			System.out.println("@@@@@@@@ before tempitemCodeList==["+tempitemCodeList+"]");

			tempitemCodeList = tempitemCodeList.substring(1, tempitemCodeList.length()-1);

			System.out.println("@@@@@@@@ after tempitemCodeList==["+tempitemCodeList+"]");

			String sqlFileName = null;
			System.out.println("matPlan---"+matPlan+"----mfgPlan----"+mfgPlan);
			System.out.println("isDetailReq2------"+isDetailReq);
			if (matPlan.equalsIgnoreCase("N") && mfgPlan.equalsIgnoreCase("N"))
			{
				sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "demandsupplyforecastonly";
			}
			else if (matPlan.equalsIgnoreCase("Y") && mfgPlan.equalsIgnoreCase("N"))
			{


				if(wnName1.trim().equals("w_requirement"))
				{
					sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "demandsupplymaterialReq";
				}
				else
				{
					sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "demandsupplymaterial";
				}
			} else
			{
				sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "demandsupplyDetail";	
			}

			//cpatil-25/08/14-System.out.println("sqlFileName---"+sqlFileName);

			if ((CommonConstants.DB_NAME).equalsIgnoreCase("db2"))
			{
				String adpQueryOriginal = readFile(sqlFileName + "DB2.sql");

				String strDateFrom = dateFrom.toString();
				strDateFrom = strDateFrom.replaceAll(" ", "-");
				strDateFrom = strDateFrom.replaceAll(":", ".");
				String strDateTo = dateTo.toString();
				strDateTo = strDateTo.replaceAll(" ", "-");
				strDateTo = strDateTo.replaceAll(":", ".");
				adpQuery = adpQueryOriginal;
				// System.out.println("Afetr Reading File adpQuery..");
				//adpQuery = adpQuery.replaceAll("@sitecode@", siteCode);
				adpQuery = adpQuery.replaceAll("@itemcode@", tempitemCodeList);
				adpQuery = adpQuery.replaceAll("@fromdate@", dateFromString);
				adpQuery = adpQuery.replaceAll("@todate@", dateToString);
				adpQuery = adpQuery.replaceAll("@ordtypes@", standingOrdTypes);
				adpQuery = adpQuery.replaceAll("@madetoorder@", madeToOrder);
				adpQuery = adpQuery.replaceAll("@madetostock@", madeToStock);
				// 01-10-2007 manoharan
				adpQuery = adpQuery.replaceAll("@rundate@", runDateString);
				// end 01-10-2007 manoharan
			} else if ((CommonConstants.DB_NAME).equalsIgnoreCase("oracle"))
			{
				String adpQueryOriginal = readFile(sqlFileName + "Oracle.sql");
				// end 14-02-2007 manoharan
				adpQuery = adpQueryOriginal;
				// System.out.println("Replacing Values.in SQL.....");
				//adpQuery = adpQuery.replaceAll("@sitecode@", siteCode);
				adpQuery = adpQuery.replaceAll("@itemcode@", tempitemCodeList);
				adpQuery = adpQuery.replaceAll("@fromdate@", dbDateFrom);
				adpQuery = adpQuery.replaceAll("@todate@", dbDateTo);
				adpQuery = adpQuery.replaceAll("@ordtypes@", standingOrdTypes);
				adpQuery = adpQuery.replaceAll("@madetoorder@", madeToOrder);
				adpQuery = adpQuery.replaceAll("@madetostock@", madeToStock);
				// 01-10-2007 manoharan
				adpQuery = adpQuery.replaceAll("@rundate@", dbRunDate);
				// end 01-10-2007 manoharan
				// System.out.println("Replaced Values.in SQL.....");
			}
			FileOutputStream fout = null;
			BufferedWriter bw = null;
			fout = new FileOutputStream("demandsupply.sql");
			bw = new BufferedWriter(new OutputStreamWriter(fout));
			bw.write(adpQuery);
			bw.close();
			fout.close();

			System.out.println("@@@@@@@@ cpatil adpQuery["+adpQuery+"]");
			// stmt = conn.createStatement();
			// System.out.println("Executing Query After Replacement.....");
			// rs = stmt.executeQuery(adpQuery);
			pstmt = conn.prepareStatement(adpQuery);
			rs = pstmt.executeQuery();

			HashMap adpElementMap = new HashMap();
			// System.out.println("Query Executed for item : " + itemCode);
			String rsItemCode = "", adpItemcode = "",rsSiteCode="";
			int updctr=0;
			boolean updFlag=false;
			while (rs.next())
			{
				ArrayList adpElementList = new ArrayList();

				rsItemCode = rs.getString(1);// Added by JIten 02/11/06 as per
				adpElementList.add(rs.getString(1));

				dueDate = rs.getTimestamp(2);
				if (dueDate.compareTo(dateFrom) < 0)
				{
					dueDate = dateFrom;
				}
				adpElementList.add(dueDate);
				//demand = rs.getDouble(3);
				adpElementList.add(rs.getDouble(3));
				//supply = rs.getDouble(4);
				adpElementList.add(rs.getDouble(4));
				//stockQty = rs.getDouble(5);
				adpElementList.add(rs.getDouble(5));
				//othSupply = rs.getDouble(6);
				adpElementList.add(rs.getDouble(6));
				//pendPOQty = rs.getDouble(7);
				adpElementList.add(rs.getDouble(7));
				//pendDOQty = rs.getDouble(8);
				adpElementList.add(rs.getDouble(8));
				//pendIndQty = rs.getDouble(9);
				adpElementList.add(rs.getDouble(9));
				//pendDRQty = rs.getDouble(10);
				adpElementList.add(rs.getDouble(10));

				if(isDetailReq)
				{
					//tranId=rs.getString("tran_id");
					adpElementList.add(rs.getString("tran_id"));
					//tranSer=rs.getString("tran_ser");
					adpElementList.add(rs.getString("tran_ser"));
				}

				if( adpElementMap.containsKey(siteCodeAdp+rsItemCode) )
				{
					ArrayList tempAdpElementList =  (ArrayList) adpElementMap.get(siteCodeAdp+rsItemCode);
					//tempAdpElementList.add(adpElementList);
					//adpElementMap.put(siteCodeAdp+rsItemCode,tempAdpElementList); 
					adpElementMap.put(siteCodeAdp+rsItemCode,adpElementList);
				}
				else
				{
					ArrayList tempAdpElementList =  new ArrayList();
					//tempAdpElementList.add(adpElementList);
					//adpElementMap.put(siteCodeAdp+rsItemCode, tempAdpElementList);
					adpElementMap.put(siteCodeAdp+rsItemCode, adpElementList);
				}
			}

			System.out.println("@@@cpatiladpElementMap["+adpElementMap+"]");
			System.out.println("@@@cpatiladpList.size()["+adpList.size()+"]");

			for( int ctr=0; ctr < adpList.size() ; ctr++ )
			{
				ADPElement adpElement = (ADPElement) adpeList.get(ctr);
				ArrayList adpElementListValueAll = new ArrayList();
				itemCode = adpElement.getItemCode();
				siteCodeAdp = adpElement.getSiteCode();

				// ArrayList adpElementListValue = new ArrayList();

				adpElementListValueAll = (ArrayList) adpElementMap.get(siteCodeAdp+rsItemCode);
				//adpElementListValueAll = (ArrayList) adpElementMap.get(siteCodeAdp+rsItemCode);
				//System.out.println("@@@cpatilitemCode["+itemCode+"]siteCodeAdp["+siteCodeAdp+"]adpElementListValue["+adpElementListValue+"]");
				//ADPElement adpElement = new ADPElement();
				System.out.println("@@@cpatil adpElementListValueAll.size()["+ adpElementListValueAll.size()+"]");
				for( int ctrList=0; ctrList < adpElementListValueAll.size(); ctrList++ )
				{

					ArrayList adpElementListValue = new ArrayList();

					adpElementListValue =  (ArrayList) adpElementListValueAll.get(ctr);
					System.out.println("@@@cpatiladpElementListValue["+adpElementListValue+"]");
					dueDate = (Timestamp)adpElementListValue.get(1);

					if("0".equals(madeToOrder) && "O".equals(adpElement.getMfgType()))
					{
						demand=0;
					}
					else
					{
						demand = (Double) adpElementListValue.get(2);
					}

					//adpElement.setDemand(dueDate, demand, "          ", "   ");
					//280115 adpElement.setDemand(dueDate, demand,  "          ", "   ");
					//adpElement.setSupply(dueDate, supply);
					adpElement.setSupply(dueDate, (Double) adpElementListValue.get(3));
					//adpElement.setStockQty(dueDate, stockQty);
					adpElement.setStockQty(dueDate, (Double) adpElementListValue.get(4));
					//adpElement.setOthSupply(dueDate, othSupply);
					adpElement.setOthSupply(dueDate, (Double) adpElementListValue.get(5));
					//adpElement.setPendingPO(dueDate, pendPOQty);
					adpElement.setPendingPO(dueDate, (Double) adpElementListValue.get(6));
					//adpElement.setPendingDO(dueDate, pendDOQty);
					adpElement.setPendingDO(dueDate, (Double) adpElementListValue.get(7));
					//adpElement.setPendingIndent(dueDate, pendIndQty);
					adpElement.setPendingIndent(dueDate, (Double) adpElementListValue.get(8));
					//adpElement.setPendingDR(dueDate, pendDRQty);
					adpElement.setPendingDR(dueDate, (Double) adpElementListValue.get(9));
					//delete
					//if (rsItemCode != null && rsItemCode.trim().equalsIgnoreCase(itemCode.trim()))
					//{
					System.out.println("dueDate---demand---supply"+dueDate+"---"+demand+"---"+supply);

					if(isDetailReq)
					{
						ADPElement detADPElement=new ADPElement();
						detADPElement.setDemand(dueDate, demand, "          ", "   ");
						//detADPElement.setSupply(dueDate, supply);
						detADPElement.setSupply(dueDate, (Double) adpElementListValue.get(3));
						//detADPElement.setStockQty(dueDate, stockQty);
						detADPElement.setStockQty(dueDate, (Double) adpElementListValue.get(4));
						//detADPElement.setOthSupply(dueDate, othSupply);
						detADPElement.setOthSupply(dueDate, (Double) adpElementListValue.get(5));
						//detADPElement.setPendingPO(dueDate, pendPOQty);
						detADPElement.setPendingPO(dueDate,  (Double) adpElementListValue.get(6));
						//detADPElement.setPendingDO(dueDate, pendDOQty);
						detADPElement.setPendingDO(dueDate, (Double) adpElementListValue.get(7));
						//detADPElement.setPendingIndent(dueDate, pendIndQty);
						detADPElement.setPendingIndent(dueDate, (Double) adpElementListValue.get(8));
						//detADPElement.setPendingDR(dueDate, pendDRQty);
						detADPElement.setPendingDR(dueDate,  (Double) adpElementListValue.get(9));

						detADPElement.setSaleOrder(adpElement.getSaleOrder());
						detADPElement.setLineNo(adpElement.getLineNo());

						HashMap<String, ADPElement> detMap=new HashMap<String, ADPElement>();
						tranId =  ( String ) adpElementListValue.get(10) ;
						tranSer = ( String ) adpElementListValue.get(11) ;

						System.out.println("tranId#tranSer----"+tranId+"#"+tranSer);
						detMap.put(tranId+"#"+tranSer, detADPElement);
						ArrayList<HashMap<String, ADPElement>> alist=adpElement.getDetList();
						//cpatil-25/08/14-System.out.println("alist.size()-1---"+alist.size());
						if(detMap.size()>0)
						{
							alist.add( detMap);
						}

						adpElement.setDetList(alist);
						detMap=null;
						detADPElement=null;
						alist=null;

					}
					//System.out.println("@@@@@ out updctr["+updctr+"]updFlag["+updFlag+"]");
					//if( updFlag == true)


					/*
				else
				{
					//cpatil-25/08/14-System.out.println("Site Code :: " + siteCode + " rsItemCode :: " + rsItemCode + " Item Code :: " + itemCode);
					int ctr = indexOfADPElement(siteCode, rsItemCode, "          ", "   ");
					// System.out.println("AdpList : "+adpeList.size()+"Index ctr :: "+ctr);//Added
					// by Jiten 09/11/06 Sun
					if (ctr > 0)
					{// if condition added by jiten as per Manoharan Sir
						// 10/11/06
						ADPElement tempADPElement = (ADPElement) adpeList.get(ctr);
						tempADPElement.setDemand(dueDate, demand, "          ", "   ");
						tempADPElement.setSupply(dueDate, supply);
						adpeList.set(ctr, tempADPElement);
					} else if (ctr == -1)
					{// Else if condition added by jiten 10/11/06 as per Tarun
						// Bhai to write for skipped item
						this.fw1.write(siteCode + "	 " + itemCode + "	" + rsItemCode + "\r\n");
					}
				}
				// End addding
					 */
					System.out.println(adpElement.getSupply());
					if (demand != 0 || supply != 0)
					{
						if (adpElement.getSuppSour().equals("M"))
							// System.out.println("adpQuery ::"+adpQuery);
							System.out.println("Site Code : " + siteCode + "   Item Code : " + itemCode + "    Due Date : " + dueDate + "     Demand : " + demand + " supply : " + supply);
					}
				}
				//System.out.println("@@@@@ out updctr["+updctr+"]updFlag["+updFlag+"]");
				//if( updFlag == true)
				{
					System.out.println("@@@@@ in ctr["+ctr+"]adpElement["+adpElement+"]");
					adpeList.set(ctr, adpElement);
				} 

			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

		} catch (SQLException se)
		{
			System.out.println("SQLException :RunMRPPrcEJB : populateDemandSupply(ADPElement).." + se.getMessage());
			System.out.println(adpQuery);
			se.printStackTrace();
			errString = se.getMessage();
			throw new ITMException(se);
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB : populateDemandSupply(ADPElement):...." + e.getMessage() + ":");
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			if (pstmt != null)
			{
				pstmt = null;
			}
			if (rs != null)
			{
				rs = null;
			}
			this.fw1.flush();// Added by jiten 10/11/06
		}
	}



	// //////////////////////////////////////////////////////////////////////////
	private void populateMTODemandSupply(String siteCode, String itemCode, ADPElement adpElement) throws Exception
	{
		double demand = 0;
		double supply = 0;
		java.sql.Timestamp dueDate = null;
		// String itemCode = null;
		// String siteCode = null;
		// 12/04/10 manoharan MF90BHU001
		double stockQty = 0;
		double othSupply = 0;
		// end 12/04/10 manoharan MF90BHU001

		// Variables declared by gulzar on 4/18/2012
		double pendPOQty = 0;
		double pendDOQty = 0;
		double pendIndQty = 0;
		double pendDRQty = 0;
		// End changes by gulzar on 4/18/2012

		Statement stmt = null;
		ResultSet rs = null;
		errString = "";
		String adpQuery = null;
		PreparedStatement pstmt = null;
		String saleOrder = null, rsItemCode = "";
		String lineNo = null;

		PreparedStatement pstmt1 = null;
		ResultSet rs1 = null;

		HashMap<String , Double> grossWeightMap = new HashMap<String , Double>();

		try
		{
			// itemCode = adpElement.getItemCode();
			// siteCode = adpElement.getSiteCode();
			// ADPElement adpElement = new ADPElement(); // 01/04/11 manoharan
			// dummy for nothing
			//cpatil-25/08/14-System.out.println(adpElement.getItemCode()+"---"+adpElement.getSiteCode()+"---"+adpElement.getSaleOrder()+"---"+adpElement.getLineNo());
			System.out.println("madeToOrder---"+madeToOrder+"----adpElement.getMfgType()----"+adpElement.getMfgType());
			//if (!"0".equals(madeToOrder) || !"O".equals(adpElement.getMfgType()))
			if ((!"0".equals(madeToOrder) || !"O".equals(adpElement.getMfgType())) && (!isDetailReq && isRequirement))//Changed By manoj dtd 05/08/2014
			{
				return;
			}

			// //cpatil-25/08/14-System.out.println("commonConstants.DB_NAME "+CommonConstants.DB_NAME);
			// 14-02-2007 manoharan
			String sqlFileName = null;
			sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "madeToOrder";
			// end 14-02-2007 manoharan

			// added by Sabyasachi 30-03-2011

			if ((CommonConstants.DB_NAME).equalsIgnoreCase("db2"))
			{
				// System.out.println("Firing DB2 Sql For Site Code :" +
				// siteCode + " Item Code : " + itemCode + " From Date : " +
				// dateFrom + " To Date : "+ dateTo + " StandgOrdTypes : "+
				// standingOrdTypes +" MadeToOrder " +madeToOrder+
				// " MadeToStock : " + madeToStock);
				// 14-02-2007 manoharan
				// String adpQueryOriginal = readFile(CommonConstants.JBOSSHOME
				// + File.separator +"sql" + File.separator +
				// "demandsupplyDB2.sql");
				String adpQueryOriginal = readFile(sqlFileName + "DB2.sql");
				// end 14-02-2007 manoharan

				String strDateFrom = dateFrom.toString();
				strDateFrom = strDateFrom.replaceAll(" ", "-");
				strDateFrom = strDateFrom.replaceAll(":", ".");
				String strDateTo = dateTo.toString();
				strDateTo = strDateTo.replaceAll(" ", "-");
				strDateTo = strDateTo.replaceAll(":", ".");
				/*
				 * // 01-10-2007 manoharan String strRunDate =
				 * runDate.toString(); strRunDate =
				 * strRunDate.replaceAll(" ","-"); strRunDate =
				 * strRunDate.replaceAll(":","."); // end 01-10-2007 manoharan
				 */
				adpQuery = adpQueryOriginal;
				// System.out.println("Afetr Reading File adpQuery..");
				adpQuery = adpQuery.replaceAll("@sitecode@", siteCode);
				adpQuery = adpQuery.replaceAll("@itemcode@", itemCode);
				adpQuery = adpQuery.replaceAll("@fromdate@", dateFromString);
				adpQuery = adpQuery.replaceAll("@todate@", dateToString);
				adpQuery = adpQuery.replaceAll("@ordtypes@", standingOrdTypes);
				adpQuery = adpQuery.replaceAll("@madetoorder@", madeToOrder);
				adpQuery = adpQuery.replaceAll("@madetostock@", madeToStock);
				// 01-10-2007 manoharan
				adpQuery = adpQuery.replaceAll("@rundate@", runDateString);
				// end 01-10-2007 manoharan


			} else if ((CommonConstants.DB_NAME).equalsIgnoreCase("oracle"))
			{
				// 14-02-2007 manoharan
				// String adpQueryOriginal = readFile(CommonConstants.JBOSSHOME
				// + File.separator +"sql" + File.separator +
				// "demandsupplyOracle.sql");
				String adpQueryOriginal = readFile(sqlFileName + "Oracle.sql");
				// end 14-02-2007 manoharan
				adpQuery = adpQueryOriginal;
				// System.out.println("Replacing Values.in SQL.....");
				adpQuery = adpQuery.replaceAll("@sitecode@", siteCode);
				adpQuery = adpQuery.replaceAll("@itemcode@", itemCode);
				adpQuery = adpQuery.replaceAll("@fromdate@", dbDateFrom);
				adpQuery = adpQuery.replaceAll("@todate@", dbDateTo);
				adpQuery = adpQuery.replaceAll("@ordtypes@", standingOrdTypes);
				adpQuery = adpQuery.replaceAll("@madetoorder@", madeToOrder);
				adpQuery = adpQuery.replaceAll("@madetostock@", madeToStock);
				// 01-10-2007 manoharan
				adpQuery = adpQuery.replaceAll("@rundate@", dbRunDate);
				// end 01-10-2007 manoharan
				// System.out.println("Replaced Values.in SQL.....");

			}
			FileOutputStream fout = null;
			BufferedWriter bw = null;
			fout = new FileOutputStream("demandsupply.sql");
			bw = new BufferedWriter(new OutputStreamWriter(fout));
			bw.write(adpQuery);
			bw.close();
			fout.close();

			pstmt = conn.prepareStatement(adpQuery);
			rs = pstmt.executeQuery();
			double grossQty=0;
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
			Timestamp today = new java.sql.Timestamp(System.currentTimeMillis()) ;
			today = java.sql.Timestamp.valueOf(sdf.format(today) + " 00:00:00.000");
			while (rs.next())
			{
				saleOrder = rs.getString(1);
				lineNo = rs.getString(2);
				rsItemCode = rs.getString(3);
				dueDate = rs.getTimestamp(4);
				if(dueDate.compareTo(today)<0)
				{
					dueDate=today;
				}
				demand = rs.getDouble(5);
				supply = rs.getDouble(6);
				stockQty = rs.getDouble(7);
				othSupply = rs.getDouble(8);

				// Changes made by Gulzar on 4/18/2012
				pendPOQty = rs.getDouble(9);
				pendDOQty = rs.getDouble(10);
				pendIndQty = rs.getDouble(11);
				pendDRQty = rs.getDouble(12);
				// End Changes by Gulzar on 4/18/2012
				if(isRequirement)
				{
					siteCode = rs.getString(13);//Added by Chandrashekar on 09-07-2014
				}
				// cpatil start
				//System.out.println("@@@@@saleOrder["+saleOrder+"]["+adpElement.getSaleOrder()+"]lineNo["+lineNo+"]["+adpElement.getLineNo()+"]rsItemCode["+rsItemCode+"]@@@@@@@@@@@");
				//System.out.println("@@@@@@@@@@@sorderList["+sorderList+"]@@@@@@@@@itemCodeList["+itemCodeList+"]");
				//System.out.println("itemCodeList.length()-----"+itemCodeList.isEmpty());
				System.out.println("@@@@@@@@@4884::saleOrder["+saleOrder+"]rsItemCode["+rsItemCode+"]demand["+demand+"]grossWeightMap["+grossWeightMap+"]");
				if(isDetailReq)
				{
					System.out.println("@@@@@@@@@4887::saleOrder["+saleOrder+"]rsItemCode["+rsItemCode+"]itemCodeList["+itemCodeList+"]");
					//if(itemCodeList.length()>0 && !(itemCodeList.indexOf(saleOrder+rsItemCode) > -1 ))
					if( itemCodeList.length()>0 && ( ! "null".equalsIgnoreCase(itemCodeList) )  && !(itemCodeList.indexOf(saleOrder+rsItemCode) > -1 ))
					{
						System.out.println("@@@@@@@@@ for continue........ ");
						//if(!(itemCodeList.indexOf(rsItemCode) > -1 ))
						//{
						grossQty=demand;
						continue;
						//}
					}
					else
					{
						System.out.println("@@@@@@@@@ inside else - rsItemCode["+rsItemCode+"]demand["+demand+"]grossWeightMap["+grossWeightMap+"]");		
						if( grossWeightMap.containsKey(rsItemCode) )
						{
							double tempQty = grossWeightMap.get(rsItemCode);
							System.out.println("@@@@@@@@@rsItemCode["+rsItemCode+"]tempQty["+tempQty+"]+demand["+demand+"]==["+tempQty+demand+"]");
							grossWeightMap.put(rsItemCode, ( tempQty+demand) );
						}
						else
						{	
							grossWeightMap.put(rsItemCode, demand );
						}
						String tmpSO=checkNull(adpElement.getSaleOrder());
						if(tmpSO.trim().length()==0)
						{
							adpeList.remove(adpeList.indexOf(adpElement));
						}

					}
					
				}

				/*//start Added by chandrashekar on 09-07-2014
				System.out.println("siteItemList["+siteItemList+"]"+"Sitecode["+siteCode+"]"+"itemCode["+rsItemCode+"]");
				if(isRequirement)
				{
					if(siteItemList.length()>0 && !(siteItemList.indexOf(siteCode+rsItemCode) > -1 ))
					{
						//if(!(siteItemList.indexOf(rsItemCode) > -1 ))
						//{
						continue;
						//}
					}
				}
				//End Added by chandrashekar on 09-07-2014
				 */				//adpElement.setSaleOrder(saleOrder);
				//adpElement.setLineNo(lineNo);

				// cpatil end
				if (dueDate.compareTo(dateFrom) < 0)
				{
					dueDate = dateFrom;
				}

				//Commented by Manoj dtd 16/12/2014
				/* pstmt1=conn.prepareStatement("SELECT ITEM_CODE FROM BOMDET WHERE BOM_CODE IN(SELECT BOM_CODE FROM BOM WHERE ITEM_CODE=? AND CONFIRMED='Y')");
				pstmt1.setString(1,rsItemCode);
				rs1=pstmt1.executeQuery();
				String bomitemCode="";
				String tmpitemCode="";
				while(rs1.next())
				{
					tmpitemCode=rs1.getString(1);
					for(int ctr=0;ctr<adpeList.size();ctr++)
					{
						ADPElement tempADPElement = (ADPElement) adpeList.get(ctr);
						bomitemCode=tempADPElement.getItemCode();
						//cpatil-25/08/14-System.out.println("bomitemCode----"+bomitemCode+"---tmpitemCode---"+tmpitemCode);
						if(bomitemCode.equalsIgnoreCase(tmpitemCode))
						{
							//cpatil-25/08/14-System.out.println("Setting SaleOrder and lineNo for Semi finish items---"+saleOrder+"---"+lineNo);
							tempADPElement.setSaleOrder(saleOrder);
							tempADPElement.setLineNo(lineNo);
							break;
						}
					}
				}
				rs1.close();
				rs1=null;
				pstmt1.close();
				pstmt1=null;*/

				/*
				 * if(rsItemCode != null &&
				 * rsItemCode.trim().equalsIgnoreCase(itemCode.trim()) &&
				 * (adpElement.getSaleOrder().equals(saleOrder)) &&
				 * (adpElement.getLineNo().equals(lineNo))) {
				 * adpElement.setDemand(dueDate, demand, saleOrder, lineNo);
				 * adpElement.setSupply(dueDate, supply);
				 * adpElement.setStockQty(dueDate, stockQty);
				 * adpElement.setOthSupply(dueDate, othSupply); } else {
				 */
				// 01/04/11 find same item without sales order, if exists remove
				// from array
				/*
				 * int ctr = indexOfADPElement(siteCode,
				 * rsItemCode,"          ","   "); // if(ctr > -1) {
				 * adpeList.remove(ctr); } // end 01/04/11
				 */

				
				int ctr = indexOfADPElement(siteCode, rsItemCode, saleOrder, lineNo);
				System.out.println("01/04/11---BHU saleOrder [" + saleOrder + "]rsItemCode["+rsItemCode+"] itemCode["+itemCode+"]lineNo [" + lineNo + "] ctr [" + ctr + "]  [--"+rsItemCode+"]");

				if (ctr > -1)
				{
					System.out.println("@@@@@@4988 inside if ctr["+ctr+"]dueDate["+dueDate+"]demand["+demand+"]saleOrder["+saleOrder+"]rsItemCode["+rsItemCode+"]");
					ADPElement tempADPElement = (ADPElement) adpeList.get(ctr);
					//cpatil-25/08/14-System.out.println("3155---saleOrder---"+saleOrder+"---lineNo---"+lineNo);
					tempADPElement.setDemand(dueDate, demand, saleOrder, lineNo); // comment on 12/01/15
					/*
					if(!isDetailReq)
					{
						tempADPElement.setDemand(dueDate, demand, saleOrder, rsItemCode);
					}
					 */
					//adpElement.setDemand(dueDate, quantity, saleOrder, itemCode);
					//cpatil-25/08/14-System.out.println("3155---saleOrder---"+saleOrder+"---lineNo---"+lineNo);
					tempADPElement.setSupply(dueDate, supply);
					adpeList.set(ctr, tempADPElement);
				} else if (ctr == -1)
				{
					System.out.println("@@@@@@4999 inside else ctr["+ctr+"]dueDate["+dueDate+"]demand["+demand+"]saleOrder["+saleOrder+"]rsItemCode["+rsItemCode+"]lineNo["+lineNo+"]supply["+supply+"]siteCode["+siteCode+"]");
					ADPElement newADPElement = new ADPElement();
					newADPElement.setSiteCode(siteCode);
					newADPElement.setItemCode(rsItemCode);
					newADPElement = setAdpeValues(newADPElement);
					newADPElement.setSaleOrder(saleOrder);
					newADPElement.setLineNo(lineNo);
					newADPElement.setDemand(dueDate, demand, saleOrder, lineNo);  // comment on 12/01/15
					/*
					if(!isDetailReq)
					{
						newADPElement.setDemand(dueDate, demand, saleOrder, rsItemCode);
					}
					 */
					newADPElement.setSupply(dueDate, supply);

					adpeList.add(newADPElement);
					System.out.println("01/04/11 BHU not found adding saleOrder [" + saleOrder + "] lineNo [" + lineNo + "] ctr [" + ctr + "] rsItemCode ["+rsItemCode+"");
				}
				/*	
				System.out.println("@@@@@@@@@ cpatil---------startadpeList.size()["+adpeList.size()+"]");
				for( int cctrr=0; cctrr < adpeList.size(); cctrr++)
				{
					ADPElement tempADPElement2 = (ADPElement) adpeList.get(cctrr);
					tempADPElement2.setSaleOrder(saleOrder);
					tempADPElement2.setLineNo(lineNo);
					adpeList.set(cctrr, tempADPElement2);
				}
				System.out.println("@@@@@@@@@ cpatil---------end");
				 */	

				// }
			}


			// for gross weight start
			System.out.println("@@@@cpatil grossWeightMap["+grossWeightMap+"]");
			System.out.println("@@@@cpatil adpList["+adpeList.size()+"]["+adpeList+"]");
			String tempItemCode="", tempSiteCode="";
			for ( int ctr1 = 0; ctr1 < adpeList.size(); ctr1++ )  //Loop for each node of current detail
			{
				ADPElement tempAdpElement = (ADPElement) adpeList.get(ctr1);

				tempItemCode = tempAdpElement.getItemCode();
				tempSiteCode = tempAdpElement.getSiteCode();
				System.out.println("@@@cpatil_ctr1["+ctr1+"]tempItemCode==["+tempItemCode+"]tempSiteCode==["+tempSiteCode+"]");

				if(grossWeightMap.containsKey(tempItemCode))
				{
					double tempGrossWeight = grossWeightMap.get(tempItemCode);
					System.out.println("@@@@@4760:tempItemCode["+tempItemCode+"]tempGrossWeight["+tempGrossWeight+"]");
					tempAdpElement.setGrossWeight(tempGrossWeight);
				}

				if( itemCodeTo.equalsIgnoreCase(tempAdpElement.getItemCode()) )
				{	
					//280115	tempAdpElement.setDemand(dateFrom,bomReplaceDemand , saleOrderReplaceBom, lineNoReplaceBom , true );
				}
				adpeList.set( ctr1, tempAdpElement);
				//adpElement=null;	//cpatilnull
			}
			System.out.println("@@@@@@@@ after gross weight updated****** adpeList==["+adpeList+"]********");


			// for gross weight end


			//cpatil-25/08/14-System.out.println("3176----adpElement.getSaleOrder----"+adpElement.getSaleOrder()+"---"+adpElement.getItemCode());
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
			// added by Sabyasachi ends 30-03-2011
		} catch (SQLException se)
		{
			System.out.println("SQLException :RunMRPPrcEJB : populateDemandSupply(ADPElement).." + se.getMessage());
			System.out.println(adpQuery);
			se.printStackTrace();
			errString = se.getMessage();
			throw new ITMException(se);
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB : populateDemandSupply(ADPElement):...." + e.getMessage() + ":");
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			if (pstmt != null)
			{
				pstmt = null;
			}
			if (rs != null)
			{
				rs = null;
			}
			this.fw1.flush();// Added by jiten 10/11/06
			// System.out.println("populateDemandSupply() finally block......");
			// return adpElement;
		}
		// ResultSetMetaData rsmd = rs.getMetaData();
		// int noOfColumns = rsmd.getColumnCount();

		// return commented & changed by sabyasachi 25-03-2011
		// return adpElement; //Moved here from finaly - jiten - 03/11/06
		// return adpElement;
		// end return commented & changed by sabyasachi 25-03-2011
	}

	// //////////////////////////////////////////////////////////////////////////
	private String mrpOptimize() throws RemoteException, ITMException
	{
		String errString = "";
		ADPElement adpElement = null;
		try
		{


			//cpatil-25/08/14-System.out.println("12/06/14  adpeList.size() [" + adpeList.size() + "]");
			for (int ctr = 0; ctr < adpeList.size(); ctr++)
			{
				adpElement = (ADPElement) adpeList.get(ctr);
				System.out.println("3237---"+adpElement.getSiteCode()+"---"+adpElement.getItemCode()+"---"+adpElement.getDemand()+"---"+adpElement.getSupply()+"---"+adpElement.getStockQty()+"---"+adpElement.getSaleOrder());
			}

			for (int cycle = 1; cycle <= processCycle; cycle++)
			{
				System.out.println("12/06/14 Processing level no : [" + cycle + "] of [" + processCycle + "] adpeList.size() ["+ adpeList.size() + "]" );
				// System.out.println("Size of Adpe List : " + adpeList.size());
				for (int adpeCtr = 0; adpeCtr < adpeList.size(); adpeCtr++)
				{
					adpElement = (ADPElement) adpeList.get(adpeCtr);
					if (cycle == 1)
					{
						errString = deleteOldPlan(adpElement.getSiteCode(), adpElement.getItemCode());
						if (errString != null && errString.trim().length() > 0)
						{
							System.out.println("Error While deleting old plan:..." + errString);
							return errString;
						}
					}
					System.out.println("3250---"+adpElement.getSiteCode()+"---"+adpElement.getItemCode()+"---"+adpElement.getDemand()+"---"+adpElement.getSupply()+"---"+adpElement.getStockQty()+"---"+adpElement.getSaleOrder());
					adpElement = mrpOptimize(adpElement);

					adpeList.set(adpeCtr, adpElement);	

					/*if(!isDetailReq)
					{
						adpElement = mrpOptimize(adpElement);
						adpeList.set(adpeCtr, adpElement);	
					}
					else
					{
						if(cycle==1)
						{
							adpElement = mrpOptimize(adpElement);
						}
						else
						{
							adpElement = mrpOptimize(adpElement,cycle);	
						}

						adpeList.set(adpeCtr, adpElement);	
					}*/

				}
				//cpatil-25/08/14-System.out.println("cycle-----"+cycle);
				for (int ctr = 0; ctr < adpeList.size(); ctr++)
				{
					adpElement = (ADPElement) adpeList.get(ctr);
					//cpatil-25/08/14-System.out.println("3263---"+adpElement.getSiteCode()+"---"+adpElement.getItemCode()+"---"+adpElement.getDemand()+"---"+adpElement.getSupply()+"---"+adpElement.getStockQty()+"---"+adpElement.getSaleOrder());
				}

			}
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :mrpOptimize():" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString;
	}

	private ADPElement mrpOptimize(ADPElement adpElement) throws RemoteException, ITMException
	{
		String errString = "";
		java.sql.Timestamp dueDate = null;
		double demand = 0;
		double supply = 0;
		double runningDemand = 0;
		double runningSupply = 0;
		double runningPlanSupply = 0;
		double quantity = 0;
		double batchQty = 0;
		double yieldPerc = 0;
		double minPlanPerc = 0;
		String suppSour;
		String lineType = "B";
		String bomCode = "";
		String siteCode = "";
		String siteCodeSupp = "";
		String itemCode = "";
		String sDueDate = "";
		String orderOpt = "";
		String batchQtyType = "";
		int mfgLeadTime = 0;
		int qcLeadTime = 0;
		// 22/06/10 manoharan
		String mfgLeadBasis = "F";
		double batchSizeLead = 0;
		// end 22/06/10 manoharan
		double reorderLevel=0;
		
		ExplodeBom explodeBomObj = new ExplodeBom();

		demand = adpElement.getDemand();
		supply = adpElement.getSupply();
		suppSour = adpElement.getSuppSour();
		bomCode = adpElement.getBomCode();
		siteCode = adpElement.getSiteCode();
		itemCode = adpElement.getItemCode();
		mfgLeadTime = adpElement.getMfgLeadTime();
		qcLeadTime = adpElement.getQcLeadTime();
		batchQty = adpElement.getBatchQty();
		yieldPerc = adpElement.getYieldPerc();
		batchQtyType = adpElement.getBatchQtyType();
		minPlanPerc = adpElement.getMinPlanPerc();
		// 22/06/10 manoharan
		mfgLeadBasis = adpElement.getMfgLeadBasis();
		batchSizeLead = adpElement.getBatchSizeLead();
		// end 22/06/10 manoharan
		reorderLevel = adpElement.getReorderLevel();
		//if( isBomReplace )
		//{
		//	demand =  bomReplaceDemand;
		//}

		System.out.println("14012009 Optimize site 1 : " + siteCode + " Item : " + itemCode + " Demand : " + demand + "  Supply : " + supply +"bomCode["+bomCode+"]");
		try
		{
			System.out.println("@@@@@ demand["+demand+"]supply["+supply+"]reorderLevel["+reorderLevel+"]");
			//if ((demand - supply) > 0  )
			if ((( supply - demand ) < reorderLevel && reorderLevel>0) || ((demand - supply)>0 && reorderLevel==0)  )
			{
				ArrayList timeMRParr = adpElement.getTimeMrpList();
				System.out.println(" 3323----timeMRParr.size()---"+timeMRParr.size());
				for (int timeCtr = 0; timeCtr < timeMRParr.size(); timeCtr++)
				{
					TimeMRP timeMrp = (TimeMRP) timeMRParr.get(timeCtr);
					runningDemand = timeMrp.getRunningDemand();
					runningSupply = timeMrp.getRunningSupply();
					runningPlanSupply = timeMrp.getRunningPlanSupply();
					System.out.println("3337---runningDemand---"+runningDemand+"---runningSupply---"+runningSupply+"---runningPlanSupply---"+runningPlanSupply);
					if ((suppSour.equals("M")) || (suppSour.equals("C"))) // &&
						// orderOpt.equals("B")
						// )
					{
						//runningPlanSupply = runningPlanSupply / 100 * yieldPerc;// added
						// by
						// jiten
						// as
						// per
						// Manoharan
						// Sir
						// 01/11/06

						if ("N".equalsIgnoreCase(yield)) 
						{
							runningPlanSupply = runningPlanSupply ;
							System.out.println("runningPlanSupply>>>["+runningPlanSupply+"]");
						}
						else
						{
							runningPlanSupply = runningPlanSupply / 100 * yieldPerc;
						}//Added by chandrashekar on 05-Feb-2015

					}
					// 10-04-2006 manoharan
					// end 10-04-2006 manoharan
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getDBDateFormat());
					dueDate = timeMrp.getDueDate();
					sDueDate = simpleDateFormat.format(dueDate);
					quantity = runningDemand - runningSupply - runningPlanSupply;
					System.out.println("@@@@@@5392 quantity["+quantity+"]");
					if (quantity > 0)
					{
						// 28-11-2006 manoharan
						System.out.println("@@@@@@ suppSour ["+suppSour+"]quantity["+quantity+"]");
						if ((suppSour.equals("M")) || (suppSour.equals("C"))) // &&
							// orderOpt.equals("B")
							// )
						{
							//quantity = round((((quantity) * 100) / yieldPerc),3);

							if ("N".equalsIgnoreCase(yield)) 
							{
								quantity = Math.round(quantity );
								System.out.println("quantity>>>>>>>["+quantity+"]");
							}
							else
							{
								System.out.println("@@@@@@@ quantity["+quantity+"] * 100 / yieldPerc["+yieldPerc+"]");
								quantity = Double.parseDouble(getRequiredDecimal((((quantity) * 100) / yieldPerc),3)==null?"0":getRequiredDecimal((((quantity) * 100) / yieldPerc),3));
								System.out.println("5402----quantity----["+quantity+"]");
							}//Added by chandrashekar on 05-Feb-2015

						}
						// 10-04-2006 manoharan
						System.out.println("5404----quantity----["+quantity+"]");
						quantity = calculateQuantity(adpElement, dueDate, quantity);
						System.out.println("5406----quantity----["+quantity+"]");
						/*	ArrayList<String> orderList=adpElement.getOrderList();
						if(orderList.size()>0)
						{
							for(int ct=0;ct<orderList.size();ct++)
							{
								String orderNo=orderList.get(ct);
								StringBuffer xmlString = new StringBuffer("<Root>");
								String retXMLStr = null;
								xmlString.append("<Detail>");
								xmlString.append("<site_code>").append("<![CDATA[").append(siteCode).append("]]>").append("</site_code>");
								xmlString.append("<item_code>").append("<![CDATA[").append(itemCode).append("]]>").append("</item_code>");
								xmlString.append("<line_type>").append("<![CDATA[").append(lineType).append("]]>").append("</line_type>");
								xmlString.append("<quantity>").append("<![CDATA[").append(orderNo.split("@")[2]).append("]]>").append("</quantity>");
								xmlString.append("<bom_code>").append("<![CDATA[").append(bomCode).append("]]>").append("</bom_code>");
								xmlString.append("<due_date>").append("<![CDATA[").append(sDueDate).append("]]>").append("</due_date>");
								xmlString.append("<mfg_lead_time>").append("<![CDATA[").append(mfgLeadTime).append("]]>").append("</mfg_lead_time>");
								xmlString.append("<qc_lead_time>").append("<![CDATA[").append(qcLeadTime).append("]]>").append("</qc_lead_time>");
								xmlString.append("</Detail>");
								xmlString.append("</Root>");
							}
						}*/

					}
					/*
					 * else { System.out.println("Optimize site " + siteCode +
					 * " Item " + itemCode + " runDem " +
					 * decFormat(runningDemand) + " runSup " +
					 * decFormat(runningSupply) + " runPlanSup " +
					 * decFormat(runningPlanSupply) + " cal "+
					 * decFormat(quantity) ); }
					 */

					if (quantity > 0)
					{
						/*********************
						 * if((suppSour.equals("M")) || (suppSour.equals("C")))
						 * //&& orderOpt.equals("B") ) { quantity =
						 * Math.round((quantity * 100) / yieldPerc); } //
						 * 10-04-2006 manoharan
						 **********/
						if (itemCode.trim().equalsIgnoreCase("BD0783"))
						{
							System.out.println("Mrpoptimize site " + siteCode + " Item " + itemCode + " runDem " + decFormat(runningDemand) + " runSup " + decFormat(runningSupply) + " runPlanSup " + decFormat(runningPlanSupply) + " cal " + decFormat(quantity) + " Actual " + decFormat(runningDemand - runningSupply - runningPlanSupply));
						}

						// System.out.println("Actual " +
						// decFormat(runningDemand - runningSupply -
						// runningPlanSupply) + " cal "+ decFormat(quantity) );
						timeMrp.setPlanSupply(quantity);
						adpElement.setSupply(dueDate, 0); // for the sake of
						// updating running
						// demand, supplu &
						// planSupply
						// independent demand
						// ************************************
						// if (suppSour.equals("P") &&
						// adpElement.getSiteCodeSupp().trim() > 0 ) Changed by
						// sudhir
						if (suppSour.equals("P") && adpElement.getSiteCodeSupp() != null && adpElement.getSiteCodeSupp().trim().length() > 0)
						{
							updateIndependentDemand(adpElement.getSiteCodeSupp(), itemCode, quantity, dueDate, siteCode);
						}
						// ???????? independent demand
						// *****************************

						if (suppSour.equals("D"))
						{
							// generate a demand for the supply site
							if (balIntersite.equals("Y"))
							{
								String siteIdst = null;
								siteIdst = getSurplusStockSite(siteCode, itemCode, quantity, surplusList);
								// =
								// wf_get_idst_site(ld_dist_intersite,ld_surplus_ext,ls_site_code,ls_item_code,lc_reo_qty)
								if (siteIdst != null && siteIdst.trim().length() > 0)
								{
									siteCodeSupp = siteIdst;
								}
								if (siteCodeSupp.trim().length() > 0)
								{
									siteCodeSupp = adpElement.getSiteCodeSupp();
								}
								if (siteIdst == null)
								{
									siteCodeSupp = getSiteCodeSupp(siteCode, itemCode);
									System.out.println("SiteCodeSupp " + siteCodeSupp + " if siteCodeSupp is null"); // uttam
								}
							} else
							{
								siteCodeSupp = getSiteCodeSupp(siteCode, itemCode);
							}
							updateSupplySite(siteCodeSupp, itemCode, quantity, dueDate);
						}
						// end 10-04-2006 manoharan
						if (suppSour != null && suppSour.trim().equals("M") && matPlan.trim().equals("Y"))
						{

							// 22/06/10 manoharan to calculate due_date based on
							// batch size
							// if configured as lead time per batch
							if (mfgLeadBasis == null)
							{
								mfgLeadBasis = "F";
							}

							if ("B".equals(mfgLeadBasis) && quantity > batchSizeLead)
							{
								//cpatil-25/08/14-System.out.println("manohar  mfgLeadTime before [" + mfgLeadTime + "]");
								mfgLeadTime = (int) (quantity * mfgLeadTime / batchSizeLead);
								//cpatil-25/08/14-System.out.println("manohar  mfgLeadTime after [" + mfgLeadTime + "]");
							}
							// end 22/06/10 manoharan
							StringBuffer xmlString = new StringBuffer("<Root>");
							String retXMLStr = null;
							xmlString.append("<Detail>");
							xmlString.append("<site_code>").append("<![CDATA[").append(siteCode).append("]]>").append("</site_code>");
							xmlString.append("<item_code>").append("<![CDATA[").append(itemCode).append("]]>").append("</item_code>");
							xmlString.append("<line_type>").append("<![CDATA[").append(lineType).append("]]>").append("</line_type>");
							xmlString.append("<quantity>").append("<![CDATA[").append(quantity).append("]]>").append("</quantity>");
							xmlString.append("<bom_code>").append("<![CDATA[").append(bomCode).append("]]>").append("</bom_code>");
							xmlString.append("<due_date>").append("<![CDATA[").append(sDueDate).append("]]>").append("</due_date>");
							xmlString.append("<mfg_lead_time>").append("<![CDATA[").append(mfgLeadTime).append("]]>").append("</mfg_lead_time>");
							xmlString.append("<qc_lead_time>").append("<![CDATA[").append(qcLeadTime).append("]]>").append("</qc_lead_time>");
							xmlString.append("</Detail>");
							xmlString.append("</Root>");
							// retXMLStr =
							// explodeBomObj.explodeBom(xmlString.toString(),
							// conn).toString();//Commented by Jiiten as per
							// Kandarp Sir 13/11/06 -
							System.out.println("xmlString--------"+xmlString);
							if (isBomReplace)
							{
								System.out.println("12/06/14 manohar xmlString [" + xmlString + "]");
							}

							retXMLStr = explodeBomObj.explodeBom(xmlString.toString()).toString(); // Added
							// by
							// Jiten
							// 13/11/06
							// -

							//Added by Manoj dtd 30/04/2014 to set Alternate items in xml
							/*String tmpAltitemlist="";
							for(int ctr=0;ctr<adpeList.size();ctr++)
							{
								ADPElement tmpADPElement=(ADPElement) adpeList.get(ctr);
								if("A".equalsIgnoreCase(tmpADPElement.getOriginalOrAltitem()))
								{
									tmpAltitemlist+="<Detail><site_code>"+tmpADPElement.getSiteCode()+"</site_code><bom_code>"+tmpADPElement.getBomCode()+"</bom_code><item_code>"+tmpADPElement.getItemCode()+"</item_code><item_Ref>"+tmpADPElement.getItemCode()+"</item_Ref><quantity_Ref>0</quantity_Ref><quantity>0</quantity><due_date>2014-01-06</due_date><exp_lev>1</exp_lev><operation>1</operation><crit_Item>Y</crit_Item><line_type>I</line_type></Detail>";
								}
							}
							retXMLStr=retXMLStr.substring(0, retXMLStr.length()-7);
							retXMLStr=retXMLStr+tmpAltitemlist+"</Root>";*/

							//"<Detail><site_code>PL001</site_code><bom_code>M070400G.1</bom_code><item_code>US15012UVG</item_code><item_Ref>US15012UVG     </item_Ref><quantity_Ref>825.0</quantity_Ref><quantity>528.0</quantity><due_date>2014-01-05</due_date><exp_lev>1.10.</exp_lev><operation>1</operation><crit_Item>Y</crit_Item><line_type>I</line_type></Detail>";


							if (itemCode.trim().equals("BF21135"))
							{
								System.out.println("14012009 itemCode [" + itemCode + "] explodeBomObj  retXMLStr [" + retXMLStr + "]");
							}

							if (xmlString == null || xmlString.toString().trim().length() == 0)
							{
								errString = "XML String is Either null";
								// return //errString;
							} else
							{

								System.out.println("retXMLStr-----"+retXMLStr);
								//cpatil-25/08/14-System.out.println("3474---adpElement.getMfgType()----"+adpElement.getMfgType());
								if(isDetailReq)
								{
									updateDemand(retXMLStr, adpElement.getSaleOrder(), adpElement.getLineNo());
								}
								else
								{
									if ("O".equals(adpElement.getMfgType()))
									{
										updateDemand(retXMLStr, adpElement.getSaleOrder(), adpElement.getLineNo());
									} else
									{
										updateDemand(retXMLStr, "          ", "   ");
										//updateDemand(retXMLStr, adpElement.getSaleOrder(), adpElement.getLineNo());
									}	
								}

							}
						}
					} // inner -- if(runningDemand - runningSupply)
				} // inner -- for(timectr)
			} // outer -- if(demand - supply)
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :mrpOptimize (ADPElement):" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return adpElement;// errString;
	}
	private ADPElement mrpOptimize(ADPElement adpElement,int cycle) throws RemoteException, ITMException
	{
		String errString = "";
		java.sql.Timestamp dueDate = null;
		double demand = 0;
		double supply = 0;
		double runningDemand = 0;
		double runningSupply = 0;
		double runningPlanSupply = 0;
		double quantity = 0;
		double batchQty = 0;
		double yieldPerc = 0;
		double minPlanPerc = 0;
		String suppSour;
		String lineType = "B";
		String bomCode = "";
		String siteCode = "";
		String siteCodeSupp = "";
		String itemCode = "";
		String sDueDate = "";
		String orderOpt = "";
		String batchQtyType = "";
		int mfgLeadTime = 0;
		int qcLeadTime = 0;
		// 22/06/10 manoharan
		String mfgLeadBasis = "F";
		double batchSizeLead = 0;
		// end 22/06/10 manoharan
		ExplodeBom explodeBomObj = new ExplodeBom();

		demand = adpElement.getDemand();
		supply = adpElement.getSupply();
		suppSour = adpElement.getSuppSour();
		bomCode = adpElement.getBomCode();
		siteCode = adpElement.getSiteCode();
		itemCode = adpElement.getItemCode();
		mfgLeadTime = adpElement.getMfgLeadTime();
		qcLeadTime = adpElement.getQcLeadTime();
		batchQty = adpElement.getBatchQty();
		yieldPerc = adpElement.getYieldPerc();
		batchQtyType = adpElement.getBatchQtyType();
		minPlanPerc = adpElement.getMinPlanPerc();
		// 22/06/10 manoharan
		mfgLeadBasis = adpElement.getMfgLeadBasis();
		batchSizeLead = adpElement.getBatchSizeLead();
		// end 22/06/10 manoharan

		//if( isBomReplace )
		//{
		//	demand =  bomReplaceDemand;
		//}

		System.out.println("14012009 Optimize site  2 : " + siteCode + " Item : " + itemCode + " Demand : " + demand + "  Supply : " + supply);
		try
		{
			if ((demand - supply) > 0)
			{
				ArrayList timeMRParr = adpElement.getTimeMrpList();
				//cpatil-25/08/14-System.out.println(" 3323----timeMRParr.size()---"+timeMRParr.size());
				for (int timeCtr = 0; timeCtr < timeMRParr.size(); timeCtr++)
				{
					TimeMRP timeMrp = (TimeMRP) timeMRParr.get(timeCtr);
					runningDemand = timeMrp.getRunningDemand();
					runningSupply = timeMrp.getRunningSupply();
					runningPlanSupply = timeMrp.getRunningPlanSupply();
					System.out.println("3337---runningDemand---"+runningDemand+"---runningSupply---"+runningSupply+"---runningPlanSupply---"+runningPlanSupply);
					if ((suppSour.equals("M")) || (suppSour.equals("C"))) // &&
						// orderOpt.equals("B")
						// )
					{
						runningPlanSupply = runningPlanSupply / 100 * yieldPerc;// added
						// by
						// jiten
						// as
						// per
						// Manoharan
						// Sir
						// 01/11/06
					}
					// 10-04-2006 manoharan
					// end 10-04-2006 manoharan
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getDBDateFormat());
					dueDate = timeMrp.getDueDate();
					sDueDate = simpleDateFormat.format(dueDate);
					quantity = runningDemand - runningSupply - runningPlanSupply;
					if (quantity > 0)
					{
						// 28-11-2006 manoharan
						if ((suppSour.equals("M")) || (suppSour.equals("C"))) // &&
							// orderOpt.equals("B")
							// )
						{
							//quantity = Math.round(((quantity) * 100) / yieldPerc);
							quantity = Double.parseDouble(getRequiredDecimal((((quantity) * 100) / yieldPerc),3)==null?"0":getRequiredDecimal((((quantity) * 100) / yieldPerc),3));
						}
						// 10-04-2006 manoharan
						System.out.println("5702----quantity----["+quantity+"]");
						quantity = calculateQuantity(adpElement, dueDate, quantity);
						System.out.println("5704----quantity----["+quantity+"]");

					}
					/*
					 * else { System.out.println("Optimize site " + siteCode +
					 * " Item " + itemCode + " runDem " +
					 * decFormat(runningDemand) + " runSup " +
					 * decFormat(runningSupply) + " runPlanSup " +
					 * decFormat(runningPlanSupply) + " cal "+
					 * decFormat(quantity) ); }
					 */

					if (quantity > 0)
					{
						/*********************
						 * if((suppSour.equals("M")) || (suppSour.equals("C")))
						 * //&& orderOpt.equals("B") ) { quantity =
						 * Math.round((quantity * 100) / yieldPerc); } //
						 * 10-04-2006 manoharan
						 **********/
						if (itemCode.trim().equalsIgnoreCase("BD0783"))
						{
							System.out.println("Mrpoptimize site " + siteCode + " Item " + itemCode + " runDem " + decFormat(runningDemand) + " runSup " + decFormat(runningSupply) + " runPlanSup " + decFormat(runningPlanSupply) + " cal " + decFormat(quantity) + " Actual " + decFormat(runningDemand - runningSupply - runningPlanSupply));
						}

						// System.out.println("Actual " +
						// decFormat(runningDemand - runningSupply -
						// runningPlanSupply) + " cal "+ decFormat(quantity) );
						timeMrp.setPlanSupply(quantity);
						adpElement.setSupply(dueDate, 0); // for the sake of
						// updating running
						// demand, supplu &
						// planSupply
						// independent demand
						// ************************************
						// if (suppSour.equals("P") &&
						// adpElement.getSiteCodeSupp().trim() > 0 ) Changed by
						// sudhir
						if (suppSour.equals("P") && adpElement.getSiteCodeSupp() != null && adpElement.getSiteCodeSupp().trim().length() > 0)
						{
							updateIndependentDemand(adpElement.getSiteCodeSupp(), itemCode, quantity, dueDate, siteCode);
						}
						// ???????? independent demand
						// *****************************

						if (suppSour.equals("D"))
						{
							// generate a demand for the supply site
							if (balIntersite.equals("Y"))
							{
								String siteIdst = null;
								siteIdst = getSurplusStockSite(siteCode, itemCode, quantity, surplusList);
								// =
								// wf_get_idst_site(ld_dist_intersite,ld_surplus_ext,ls_site_code,ls_item_code,lc_reo_qty)
								if (siteIdst != null && siteIdst.trim().length() > 0)
								{
									siteCodeSupp = siteIdst;
								}
								if (siteCodeSupp.trim().length() > 0)
								{
									siteCodeSupp = adpElement.getSiteCodeSupp();
								}
								if (siteIdst == null)
								{
									siteCodeSupp = getSiteCodeSupp(siteCode, itemCode);
									System.out.println("SiteCodeSupp " + siteCodeSupp + " if siteCodeSupp is null"); // uttam
								}
							} else
							{
								siteCodeSupp = getSiteCodeSupp(siteCode, itemCode);
							}
							updateSupplySite(siteCodeSupp, itemCode, quantity, dueDate);
						}
						// end 10-04-2006 manoharan
						if (suppSour != null && suppSour.trim().equals("M") && matPlan.trim().equals("Y"))
						{

							// 22/06/10 manoharan to calculate due_date based on
							// batch size
							// if configured as lead time per batch
							if (mfgLeadBasis == null)
							{
								mfgLeadBasis = "F";
							}

							if ("B".equals(mfgLeadBasis) && quantity > batchSizeLead)
							{
								//cpatil-25/08/14-System.out.println("manohar  mfgLeadTime before [" + mfgLeadTime + "]");
								mfgLeadTime = (int) (quantity * mfgLeadTime / batchSizeLead);
								//cpatil-25/08/14-System.out.println("manohar  mfgLeadTime after [" + mfgLeadTime + "]");
							}
							// end 22/06/10 manoharan
							StringBuffer xmlString = new StringBuffer("<Root>");
							String retXMLStr = null;
							xmlString.append("<Detail>");
							xmlString.append("<site_code>").append("<![CDATA[").append(siteCode).append("]]>").append("</site_code>");
							xmlString.append("<item_code>").append("<![CDATA[").append(itemCode).append("]]>").append("</item_code>");
							xmlString.append("<line_type>").append("<![CDATA[").append(lineType).append("]]>").append("</line_type>");
							xmlString.append("<quantity>").append("<![CDATA[").append(quantity).append("]]>").append("</quantity>");
							xmlString.append("<bom_code>").append("<![CDATA[").append(bomCode).append("]]>").append("</bom_code>");
							xmlString.append("<due_date>").append("<![CDATA[").append(sDueDate).append("]]>").append("</due_date>");
							xmlString.append("<mfg_lead_time>").append("<![CDATA[").append(mfgLeadTime).append("]]>").append("</mfg_lead_time>");
							xmlString.append("<qc_lead_time>").append("<![CDATA[").append(qcLeadTime).append("]]>").append("</qc_lead_time>");
							xmlString.append("</Detail>");
							xmlString.append("</Root>");
							// retXMLStr =
							// explodeBomObj.explodeBom(xmlString.toString(),
							// conn).toString();//Commented by Jiiten as per
							// Kandarp Sir 13/11/06 -
							System.out.println("xmlString--------"+xmlString);
							if (isBomReplace)
							{
								System.out.println("12/06/14 manohar xmlString [" + xmlString + "]");
							}

							retXMLStr = explodeBomObj.explodeBom(xmlString.toString()).toString(); // Added
							// by
							// Jiten
							// 13/11/06
							// -

							//Added by Manoj dtd 30/04/2014 to set Alternate items in xml
							/*String tmpAltitemlist="";
							for(int ctr=0;ctr<adpeList.size();ctr++)
							{
								ADPElement tmpADPElement=(ADPElement) adpeList.get(ctr);
								if("A".equalsIgnoreCase(tmpADPElement.getOriginalOrAltitem()))
								{
									tmpAltitemlist+="<Detail><site_code>"+tmpADPElement.getSiteCode()+"</site_code><bom_code>"+tmpADPElement.getBomCode()+"</bom_code><item_code>"+tmpADPElement.getItemCode()+"</item_code><item_Ref>"+tmpADPElement.getItemCode()+"</item_Ref><quantity_Ref>0</quantity_Ref><quantity>0</quantity><due_date>2014-01-06</due_date><exp_lev>1</exp_lev><operation>1</operation><crit_Item>Y</crit_Item><line_type>I</line_type></Detail>";
								}
							}
							retXMLStr=retXMLStr.substring(0, retXMLStr.length()-7);
							retXMLStr=retXMLStr+tmpAltitemlist+"</Root>";*/

							//"<Detail><site_code>PL001</site_code><bom_code>M070400G.1</bom_code><item_code>US15012UVG</item_code><item_Ref>US15012UVG     </item_Ref><quantity_Ref>825.0</quantity_Ref><quantity>528.0</quantity><due_date>2014-01-05</due_date><exp_lev>1.10.</exp_lev><operation>1</operation><crit_Item>Y</crit_Item><line_type>I</line_type></Detail>";


							if (itemCode.trim().equals("BF21135"))
							{
								System.out.println("14012009 itemCode [" + itemCode + "] explodeBomObj  retXMLStr [" + retXMLStr + "]");
							}

							if (xmlString == null || xmlString.toString().trim().length() == 0)
							{
								errString = "XML String is Either null";
								// return //errString;
							} else
							{

								System.out.println("retXMLStr-----"+retXMLStr);
								//cpatil-25/08/14-System.out.println("3474---adpElement.getMfgType()----"+adpElement.getMfgType());
								if(isDetailReq)
								{
									/*ArrayList<String> orderList=new ArrayList<String>();
									orderList=adpElement.getOrderList();
									if(orderList.size()>0)
									{
									for(int ctr=0;ctr<orderList.size();ctr++)
									{
										String orderNo=orderList.get(ctr);
										System.out.println("orderNo.split(@)[0] ["+orderNo.split("@")[0]+"]");
										System.out.println("orderNo.split(@)[0] ["+orderNo.split("@")[1]+"]");
										updateDemand(retXMLStr, orderNo.split("@")[0], orderNo.split("@")[1]);
									}
									}
									else
									{
										System.out.println("adpElement.getSaleOrder() ["+adpElement.getSaleOrder()+"]");
										System.out.println("adpElement.getLineNo() ["+adpElement.getLineNo()+"]");
										updateDemand(retXMLStr, adpElement.getSaleOrder(), adpElement.getLineNo());
									}*/
									updateDemand(retXMLStr, adpElement.getSaleOrder(), adpElement.getLineNo());
								}
								else
								{
									if ("O".equals(adpElement.getMfgType()))
									{
										updateDemand(retXMLStr, adpElement.getSaleOrder(), adpElement.getLineNo());
									} else
									{
										updateDemand(retXMLStr, "          ", "   ");
										//updateDemand(retXMLStr, adpElement.getSaleOrder(), adpElement.getLineNo());
									}	
								}

							}
						}
					} // inner -- if(runningDemand - runningSupply)
				} // inner -- for(timectr)
			} // outer -- if(demand - supply)
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :mrpOptimize (ADPElement):" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return adpElement;// errString;
	}
	private void updateSupplySite(String siteCode, String itemCode, double quantity, java.sql.Timestamp dueDate) throws ITMException, Exception
	{
		ADPElement adpElement;
		int found = -1;
		try
		{
			for (int adpeCtr = 0; adpeCtr < adpeList.size(); adpeCtr++)
			{
				adpElement = (ADPElement) adpeList.get(adpeCtr);
				if (adpElement.getItemCode().trim().equals(itemCode.trim()) && adpElement.getSiteCode().trim().equals(siteCode.trim()))
				{
					adpElement.setDemand(dueDate, quantity, "          ", "   ");
					found = adpeCtr;
					adpeList.set(adpeCtr, adpElement);
					break;
				}
			}
			if (found == -1)
			{
				adpElement = new ADPElement();
				adpElement.setItemCode(itemCode);
				adpElement.setSiteCode(siteCode);
				adpElement = setAdpeValues(adpElement);
				adpElement.setDemand(dueDate, quantity, "          ", "   ");
				adpeList.add(adpElement);
			}
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :mrpOptimize():" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}

	}

	private void updateIndependentDemand(String siteCode, String itemCode, double quantity, java.sql.Timestamp dueDate, String siteCodeCust) throws ITMException, Exception
	{
		ADPElement adpElement;
		int found = -1;
		try
		{
			for (int adpeCtr = 0; adpeCtr < adpeList.size(); adpeCtr++)
			{
				adpElement = (ADPElement) adpeList.get(adpeCtr);
				if (adpElement.getItemCode().trim().equals(itemCode.trim()) && adpElement.getSiteCode().trim().equals(siteCode.trim()))
				{
					adpElement.setIndependentDemand(dueDate, quantity);
					adpElement.setSiteCodeCust(siteCodeCust);
					found = adpeCtr;
					adpeList.set(adpeCtr, adpElement);
					break;
				}
			}
			if (found == -1)
			{
				adpElement = new ADPElement();
				adpElement.setItemCode(itemCode);
				adpElement.setSiteCode(siteCode);
				adpElement = setAdpeValues(adpElement);
				adpElement.setIndependentDemand(dueDate, quantity);
				adpElement.setSiteCodeCust(siteCodeCust);
				adpeList.add(adpElement);
			}
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :mrpOptimize():" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}

	}

	private double calculateQuantity(ADPElement adpElement, java.sql.Timestamp dueDate, double reqQty) throws ITMException, Exception
	{
		double demand = 0;
		double supply = 0;
		double batchQty = 0;
		double yieldPerc = 0;
		double minPlanPerc = 0;
		double integralQty = 0;
		double reoQty = 0;
		String suppSour;
		String batchQtyType = "";
		String orderOpt = "";
		int minStkDay = 0;

		double runningDemand = 0;
		double runningSupply = 0;
		double stkLevel = 0;
		double chkOrdQty = 0;
		//int multiplier = 1;
		double multiplier = 1;
		double reqQtyOriginal = reqQty;
		double reorderLevel=0;//Manoj dtd 26/03/15
		demand = adpElement.getDemand();
		supply = adpElement.getSupply();
		batchQty = adpElement.getBatchQty();
		yieldPerc = adpElement.getYieldPerc();
		minPlanPerc = adpElement.getMinPlanPerc();
		integralQty = adpElement.getIntegralQty();
		reoQty = adpElement.getReoQty();
		suppSour = adpElement.getSuppSour();
		batchQtyType = adpElement.getBatchQtyType();
		orderOpt = adpElement.getOrderOpt();
		minStkDay = adpElement.getMinStkDay();
		reorderLevel=adpElement.getReorderLevel();
		
		System.out.println("25022010 Item " + adpElement.getItemCode() + " integralQty " + decFormat(integralQty) + " req qty " + decFormat(reqQty) + " Batch Qty " + decFormat(batchQty)+"reorderLevel["+reorderLevel+"]");
		if (minStkDay > 0 && mrpDynMinStk.equals("Y"))
		{
			stkLevel = getStkLevel(adpElement, dueDate);
		} else
		{
			/*if(reorderLevel>0)   //010415
			{
				stkLevel=reorderLevel;
			}
			else
			{*/
				stkLevel = adpElement.getMinQty();
			//}
			if (minOrderChk.equals("Y"))
			{
				chkOrdQty = adpElement.getMinOrderQty();
			} else
			{
				chkOrdQty = stkLevel;
			}
		}

		System.out.println("25022010 1-> chkOrdQty " + decFormat(chkOrdQty) + " reqQty " + decFormat(reqQty) + " stkLevel  " + decFormat(stkLevel) + " reoQty " + decFormat(reoQty));

		System.out.println("@@@@1 reqQty" + decFormat(reqQty) + " reorderLevel " + decFormat(reorderLevel) );
		/*if (reqQty < reorderLevel && reorderLevel > 0)  // added by cpatil on 30/03/15
		{
			reqQty = reorderLevel;
		}*/
		System.out.println("@@@@2 reqQty" + decFormat(reqQty) );
		if (reqQty > chkOrdQty && chkOrdQty > 0)
		{
			if (minOrderChk.equals("Y"))
			{
				multiplier = new Double(Math.ceil((reqQty + stkLevel) / integralQty)).intValue();
				System.out.println("25022010 2->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
			} else
			{
				if (mfgPlan.equals("N") && matPlan.equals("N"))
				{
					multiplier = new Double(Math.ceil(((reqQty + stkLevel)) / integralQty)).intValue();
					System.out.println("25022010 3->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
				} else
				{
					if (reqQty > 0 && reqQty > Math.floor(reqQty))
					{
						if (integralQty > 1)
						{
							multiplier = new Double(Math.ceil((reqQty + stkLevel) / integralQty)).intValue();
							System.out.println("25022010 4->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
						} else
						{
							multiplier = new Double(Math.ceil(reqQty + stkLevel)).intValue();// (new
							// Double(reqQty
							// +
							// stkLevel).intValue())
							// +
							// 1;
							// //
							// 25/02/10
							System.out.println("25022010 5->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
						}
					} else
					{
						multiplier = new Double(Math.ceil((reqQty + stkLevel) / integralQty)).intValue();
						System.out.println("25022010 6->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
					}
				}
			}
		}
		integralQty = multiplier * integralQty;
		multiplier = 1;
		System.out.println("25022010 7->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
		if (integralQty > reoQty)
		{
			reoQty = integralQty;
		}
		System.out.println("25022010 8->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
		if (reoQty == 0)
		{
			reoQty = reqQty + stkLevel;
		}
		System.out.println("25022010 8->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
		if (minOrderChk.equals("Y"))
		{
			multiplier = new Double(Math.ceil((stkLevel + reqQty) / reoQty)).intValue();
			System.out.println("25022010 9->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
		} else
		{
			if (mfgPlan.equals("N") && matPlan.equals("N"))
			{
				multiplier = new Double(Math.ceil((reqQty + stkLevel) / reoQty)).intValue();
				System.out.println("25022010 10->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
			} else
			{
				if (reqQty > 0 && reqQty > Math.floor(reqQty))
				{
					if (reoQty > 1)
					{
						multiplier = new Double(Math.ceil((reqQty + stkLevel) / reoQty)).intValue();
						System.out.println("25022010 11->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
					} else
					{
						//multiplier = new Double(Math.ceil(reqQty + stkLevel)).intValue(); // 25/02/10
						multiplier = new Double(getRequiredDecimal((reqQty + stkLevel),3)); // 25/02/10
						System.out.println("25022010 12->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
					}
				} else
				{

					multiplier = new Double(Math.ceil((reqQty + stkLevel) / reoQty)).intValue();
					System.out.println("25022010 13->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");

				}
			}
		}
		if (minOrderChk.equals("Y"))
		{
			if (reqQty < chkOrdQty && adpElement.getMinQty() < reoQty)
			{
				reqQty = reoQty;
				System.out.println("25022010 14->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
			} else
			{
				reqQty = reoQty * multiplier;
				System.out.println("25022010 15->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
			}
		} else
		{
			reqQty = reoQty * multiplier;
			System.out.println("25022010 16->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
		}

		if (orderOpt.equals("B") && !batchQtyType.equals("V"))
		{

			multiplier = 0;
			if (reqQty > batchQty)
			{
				if (getMod(reqQty, batchQty) > 0)
				{
					if (getMod(reqQty, batchQty) >= (batchQty * minPlanPerc / 100))
					{
						multiplier = new Double(Math.floor(reqQty / batchQty)).intValue() + 1;
						System.out.println("25022010 17->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
					} else
					{
						multiplier = new Double(Math.floor(reqQty / batchQty)).intValue();
						System.out.println("25022010 18->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
					}
				} else
				{
					multiplier = new Double(Math.floor(reqQty / batchQty)).intValue();
					System.out.println("25022010 19->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
				}
			} else
			{
				// 26/12/07 manoharan consider min_plan_perc
				if (reqQty >= (batchQty * minPlanPerc / 100))
				{
					multiplier = 1;
					System.out.println("25022010 20->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
				} else
				{
					multiplier = 0;
					System.out.println("25022010 21->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
				}

			}
			reqQty = multiplier * batchQty;
			System.out.println("25022010 22->Item [" + adpElement.getItemCode() + "] reqQty [" + reqQty + "] reoQty [" + reoQty + "]] integralQty [" + integralQty + "] multiplier [" + multiplier + "]");
		}

		System.out.println("25022010 23->Item [ return value --- reqQty [" + reqQty + "] ");
		return reqQty;
	}

	private double getMod(double total, double batch) throws ITMException, Exception
	{
		int multiplier = 0;
		multiplier = new Double(Math.floor(total / batch)).intValue();
		return total - (multiplier * batch);
	}

	private double getStkLevel(ADPElement adpElement, java.sql.Timestamp dueDate) throws ITMException, Exception
	{
		TimeMRP timeMRP = null;
		int timeEle = -1, ctr;
		ArrayList timeMRPArr = adpElement.getTimeMrpList();
		java.sql.Timestamp tmpDate;
		double retValue = 0;
		try
		{
			if (timeMRPArr.size() > 0)
			{
				for (ctr = 0; ctr < timeMRPArr.size(); ctr++)
				{
					timeMRP = (TimeMRP) timeMRPArr.get(ctr);
					if (timeMRP.getDueDate() != null)
					{
						if (timeMRP.getDueDate().equals(dueDate))
						{
							timeEle = ctr;
							break;
						}
					}
				}
			}
			if (timeEle > -1)
			{
				java.sql.Timestamp uptoDate = null;

				Calendar calen = Calendar.getInstance();
				calen.setTimeInMillis(dueDate.getTime());
				calen.add(Calendar.DAY_OF_MONTH, adpElement.getMinStkDay());
				uptoDate.setTime(calen.getTimeInMillis());

				for (ctr = timeEle; ctr < timeMRPArr.size(); ctr++)
				{
					timeMRP = (TimeMRP) timeMRPArr.get(timeEle);
					tmpDate = timeMRP.getDueDate();
					if (tmpDate.compareTo(uptoDate) <= 0)
					{
						retValue += timeMRP.getDemand();
					} else
					{
						break;
					}
				}
			}
		} catch (Exception e)
		{
			System.out.println("Exception :adpeLEMENT : updateTimeMrp(Date, supply, demand):...." + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return retValue;
	}

	/* Add by sachin on 24/6/13 */

	private List<Double> getStock(String siteCode, String itemCode, Connection conn) throws ITMException
	{
		List<Double> arrayList = new ArrayList<Double>();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		double availStk = 0;
		double quarantineStk = 0;
		double pendingIndentQty = 0;
		double pendingPOQty = 0;
		try
		{

			String sql = "select sum(quantity) " + "from   stock A, Location B , Invstat  C " + "where  a.loc_code = b.loc_code " + "And    b.inv_stat = c.inv_stat " + "And    (case when c.stat_type is null then ' ' else c.stat_type end) <> 'S' " + "And    c.available = 'Y' " + "And    a.item_code = ? " + "And    a.site_code = ? " + "And    a.quantity > 0";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			pstmt.setString(2, siteCode);

			rs = pstmt.executeQuery();
			if (rs.next())
			{
				availStk = rs.getDouble(1);
			}
			arrayList.add(availStk);
			System.out.println(" Available Stock is =" + availStk);
			pstmt.close();
			pstmt = null;
			rs.close();
			rs = null;

			sql = "select sum(quantity) " + "from   stock A, Location B , Invstat  C " + "where  a.loc_code = b.loc_code " + "And    b.inv_stat = c.inv_stat " + "And    (case when c.stat_type is null then ' ' else c.stat_type end) <> 'S' " + "And    c.available = 'N' " + "And    a.item_code = ? " + "And    a.site_code = ? " + "And    a.quantity > 0";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			pstmt.setString(2, siteCode);

			rs = pstmt.executeQuery();
			if (rs.next())
			{
				quarantineStk = rs.getDouble(1);

			}
			arrayList.add(quarantineStk);

			System.out.println(" Quarantine Stock is =" + quarantineStk);
			pstmt.close();
			pstmt = null;
			rs.close();
			rs = null;

			sql = "select fn_pind_qty (?,?) " + " from dual";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			pstmt.setString(2, siteCode);

			rs = pstmt.executeQuery();
			if (rs.next())
			{
				pendingIndentQty = rs.getDouble(1);
			}
			arrayList.add(pendingIndentQty);

			System.out.println(" Pending Indent Qty is =" + pendingIndentQty);

			pstmt.close();
			pstmt = null;
			rs.close();
			rs = null;

			sql = "select  fn_ppo_qty (?,?) " + " from dual";

			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, itemCode);
			pstmt.setString(2, siteCode);

			rs = pstmt.executeQuery();
			if (rs.next())
			{
				pendingPOQty = rs.getDouble(1);
			}
			arrayList.add(pendingPOQty);

			System.out.println(" Pending PO Qty is =" + pendingPOQty);
			pstmt.close();
			pstmt = null;
			rs.close();
			rs = null;
		} catch (SQLException se)
		{
			System.out.println("SQLException :RunMRPPrcEJB : getQuarantineStk(SiteCode,ItemCode,Conncetion).." + se.getMessage());
			se.printStackTrace();
			errString = se.getMessage();
			throw new ITMException(se);
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB : getQuarantineStk(SiteCode,ItemCode,Conncetion):...." + e.getMessage() + ":");
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			if (pstmt != null)
			{
				pstmt = null;
			}
			if (rs != null)
			{
				rs = null;
			}

		}
		return arrayList;
	}

	/* End Add by sachin on 24/6/13 */


	private void updateDemand(String xmlString) throws ITMException, Exception
	{
		updateDemand(xmlString, "          ", "   ");
	}

	private void updateDemand(String xmlString, String saleOrder, String lineNo) throws ITMException, Exception
	{
		Document dom;
		String siteCode = null;
		String itemCode = null;
		double quantity = 0;
		String lineType = null;
		String sdate = null;
		java.sql.Timestamp dueDate = null;
		NodeList nodeList = null;
		Node parentNode = null;
		Node childNode = null;
		String nodeName = null;
		String nodeValue = null;
		int totalNodes = 0;
		int ctr = 0;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		int count = 0;
		ADPElement adpElement = null;

		/* Addded by sachin on 25/6/13 */

		List<Double> stockList = null;
		String descr = "";
		String unit = "";
		double finlQtyFrItm = 0;
		String itmCodeReq = "";
		double qtyForItm = 0;
		HashMap<String, Double> qtyMap = new HashMap<String, Double>();

		double availStk = 0, quarntineStk = 0, pendPOQty = 0, pendIndQty = 0, netReqQty = 0;

		/* End Addded by sachin on 25/6/13 */

		try
		{
			System.out.println("In updateDemand xmlString [" + xmlString + "]");
			dom = genericUtility.parseString(xmlString);
			nodeList = dom.getElementsByTagName("Detail");
			totalNodes = nodeList.getLength();

			for (ctr = 0; ctr < totalNodes; ctr++)
			{

				Node node = nodeList.item(ctr);
				nodeName = node.getNodeName();
				Node valueNode = node.getFirstChild();
				while (valueNode != null)
				{
					nodeName = valueNode.getNodeName();
					if( valueNode.getFirstChild() != null )
					{
						nodeValue = valueNode.getFirstChild().getNodeValue();
						if (nodeName.equals("site_code"))
						{
							siteCode = nodeValue;
						}
						if (nodeName.equals("item_code"))
						{
							itemCode = nodeValue;
						}
						if (nodeName.equals("quantity"))
						{
							quantity = Double.parseDouble(nodeValue);
						}
						if (nodeName.equals("line_type"))
						{
							lineType = nodeValue;
						}
						if (nodeName.equals("due_date"))
						{
							dueDate = java.sql.Timestamp.valueOf(nodeValue + " 00:00:00");
							sdate = nodeValue;
						}
					}
					valueNode = valueNode.getNextSibling();

				}
				if (isBomReplace)
				{
					System.out.println("12/06/14 itemCode [" + itemCode + "] dueDate [" + dueDate + "] quantity [" + quantity + "]");
				}
				sql = "SELECT CASE WHEN ITEM_CODE__PLAN IS NULL THEN ITEM_CODE ELSE ITEM_CODE__PLAN END " + " FROM ITEM WHERE ITEM_CODE = ?";

				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, itemCode);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					itemCode = rs.getString(1);

				}
				rs.close();
				pstmt.close();
				//int index = indexOfADPElement(siteCode, itemCode, "          ", "   ");//Commented by manoj dtd 19/11/2013
				//cpatil-25/08/14-System.out.println("4040---siteCode----"+siteCode+"---itemCode---"+itemCode+"---saleOrder---"+saleOrder+"---lineNo---"+lineNo);
				int index=0;
				if(isDetailReq)
				{
					index = indexOfADPElement(siteCode, itemCode);	

				}
				else
				{
					index = indexOfADPElement(siteCode, itemCode, saleOrder,lineNo);
				}
				System.out.println("4072----index---"+index);
				/*if (isBomReplace)
				{
					//cpatil-25/08/14-System.out.println("12/06/14 index [" + index+ "] itemCode [" + itemCode + "] dueDate [" + dueDate + "] quantity [" + quantity + "] saleOrder [" + saleOrder + "] lineNo [" + lineNo +"]");
					if (index == -1)
					{
						ADPElement adpElementN = new ADPElement();
						adpElementN.setSiteCode(siteCode);
						adpElementN.setItemCode(itemCode);
						adpElementN = setAdpeValues(adpElementN);
						adpElementN.setSaleOrder(saleOrder);
						adpElementN.setLineNo(lineNo);
						//String parentBom = itemCodeDetailMap.get(itemCode) == null ? "":itemCodeDetailMap.get(itemCode).toString();
						//itemCodeDetailMap.put(itemCode, parentBom+"@"+adpElementN.getBomCode());
						adpElementN.setDemand(dueDate,quantity , saleOrder, lineNo );
						adpElementN.setbomSet( itemCodeDetailMap );
						adpeList.add(adpElementN);
					}
				}*/
				if (index != -1)
				{
					adpElement = (ADPElement) adpeList.get(index);
					//ADPElement tmpadpElement=new ADPElement();
					//tmpadpElement=adpElement;
					//cpatil-25/08/14-System.out.println("adpElement.getItemCode()----"+adpElement.getItemCode()+"saleOrder----"+saleOrder+"---adpElement.getSuppSour()---"+adpElement.getSuppSour());

					if(isDetailReq)
					{
						if (isBomReplace)
						{
							//cpatil-25/08/14-System.out.println("12/06/14 setting demand 1 itemCode [" + itemCode + "] dueDate [" + dueDate + "] quantity [" + quantity + "] saleOrder [" + saleOrder + "] lineNo [" + lineNo +"]");
						}
						System.out.println("12/06/14 setting demand 1 itemCode [" + itemCode + "] dueDate [" + dueDate + "] quantity [" + quantity + "] saleOrder [" + saleOrder + "] lineNo [" + lineNo +"]");
						ArrayList<String> orderList=new ArrayList<String>();
						orderList=adpElement.getOrderList();
						orderList.add(saleOrder+"@"+itemCode+"@"+quantity);
						adpElement.setOrderList(orderList);
						System.out.println("6447--adpElement.getSaleOrder()["+adpElement.getSaleOrder()+"]");
						//System.out.println("adpElement.getSaleOrder()["+adpElement.getSaleOrder()+"]");

						if(isBomReplace)
						{
							adpElement.setDemand(dueDate, quantity, "          ", "   ");
							//adpElement.setDemand(dueDate, quantity, saleOrder, itemCode);
						}
						else
						{
							adpElement.setDemand(dueDate, quantity, saleOrder, itemCode);
						}
						System.out.println("6459--adpElement.getTimeMrpList().size()"+adpElement.getTimeMrpList().size());
						adpeList.set(index, adpElement);

						/*ADPElement newADPElement = new ADPElement();
						newADPElement.setSiteCode(siteCode);
						newADPElement.setItemCode(itemCode);
						newADPElement = setAdpeValues(newADPElement);
						newADPElement.setSaleOrder(saleOrder);
						newADPElement.setLineNo(lineNo);
						newADPElement.setSupply(dueDate, adpElement.getSupply());
						newADPElement.setDemand(dueDate, quantity, saleOrder, lineNo);
						//adpeList.remove(index);
						//adpeList.set(index,newADPElement);
						adpElement.setSupply(dueDate,-1*quantity);


						adpeList.add(newADPElement);*/

					}
					else
					{
						if (saleOrder == null || saleOrder.trim().length() == 0 || !"M".equals(adpElement.getSuppSour()))
							//if (saleOrder == null || saleOrder.trim().length() == 0 )
						{
							// adpElement = (ADPElement)adpeList.get(index);
							//adpElement.setDemand(dueDate, quantity, "          ", "   ");//Commented by Manoj dtd 19/11/2013 to set Sales order and line no
							if (isBomReplace)
							{
								//cpatil-25/08/14-System.out.println("12/06/14 setting demand 2 itemCode [" + itemCode + "] dueDate [" + dueDate + "] quantity [" + quantity + "] saleOrder [" + saleOrder + "] lineNo [" + lineNo +"]");
							}
							adpElement.setDemand(dueDate, quantity, saleOrder, lineNo);
							adpeList.set(index, adpElement);



						} 
						else

						{
							if (isBomReplace)
							{
								System.out.println("12/06/14 adding demand 1 itemCode [" + itemCode + "] dueDate [" + dueDate + "] quantity [" + quantity + "] saleOrder [" + saleOrder + "] lineNo [" + lineNo +"]");
							}
							ADPElement newADPElement = new ADPElement();
							newADPElement.setSiteCode(siteCode);
							newADPElement.setItemCode(itemCode);
							newADPElement = setAdpeValues(newADPElement);
							newADPElement.setSaleOrder(saleOrder);
							newADPElement.setLineNo(lineNo);
							if(isBomReplace)
							{
								adpElement.setDemand(dueDate, quantity, "          ", "   ");
							}
							else
							{
								newADPElement.setDemand(dueDate, quantity, saleOrder, lineNo);
							}
							adpeList.add(newADPElement);

						}
					}
					//tmpadpList.add()

					/* added by sachin */
					if (wnName.trim().equals("w_requirement"))
					{
						if (!qtyMap.isEmpty())
						{
							if (qtyMap.containsKey(itemCode))
							{
								qtyForItm = qtyMap.get(itemCode);
								quantity = quantity + qtyForItm;
							}
						}
						//cpatil-25/08/14-System.out.println("puting data into hash map item code and quantity is :== " + itemCode + " :" + quantity);
						qtyMap.put(itemCode, quantity);
					}
					/* End added by sachin */

				} else
				{
					if (isBomReplace)
					{
						//cpatil-25/08/14-System.out.println("12/06/14 No index found for Site Code : " + siteCode + " & Item Code : " + itemCode);
					}
				}
			}

			/* added by sachin on 26/06/13 */
			//if (wnName.trim().equals("w_requirement"))
			System.out.println("checkNull(wnName)-------"+checkNull(wnName));
			if ("w_requirement".equalsIgnoreCase(checkNull(wnName)))
			{
				xmlDataString = new StringBuffer("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><Root>");
				Iterator it = qtyMap.keySet().iterator();
				while (it.hasNext())
				{
					itmCodeReq = (String) it.next();
					finlQtyFrItm = qtyMap.get(itmCodeReq);
					//cpatil-25/08/14-System.out.println("item code (key)=" + itmCodeReq + " value is =" + finlQtyFrItm);
					stockList = this.getStock(siteCode, itmCodeReq, conn);

					for (int i = 0; i < stockList.size(); i++)
					{
						if (i == 0)
						{
							availStk = stockList.get(i);
						}
						if (i == 1)
						{
							quarntineStk = stockList.get(i);
						}
						if (i == 2)
						{
							pendIndQty = stockList.get(i);

						}
						if (i == 3)
						{
							pendPOQty = stockList.get(i);
						}
					}
					netReqQty = finlQtyFrItm -(availStk + quarntineStk);
					if(netReqQty <0 )
					{
						netReqQty=0;
					}

					sql = "select descr,unit  from item where item_code= ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, itmCodeReq);
					rs = pstmt.executeQuery();

					if (rs.next())
					{
						descr = checkNull(rs.getString("descr"));
						unit = checkNull(rs.getString("unit"));
					}
					pstmt.close();
					rs.close();
					pstmt = null;
					rs = null;

					count++;
					xmlDataString.append("<Detail" + context + " domID='" + count + "' >\r\n");
					xmlDataString.append("<item_code protect = '1'>").append("<![CDATA[").append(itmCodeReq).append("]]>").append("</item_code>\r\n");
					xmlDataString.append("<description protect = '1'>").append("<![CDATA[").append(descr).append("]]>").append("</description>\r\n");
					xmlDataString.append("<unit protect = '1'>").append("<![CDATA[").append(unit).append("]]>").append("</unit>\r\n");
					xmlDataString.append("<quantity protect = '1'>").append("<![CDATA[").append(getRequiredDecimal(finlQtyFrItm, 3)).append("]]>").append("</quantity>\r\n");
					xmlDataString.append("<avail_qty protect = '1'>").append("<![CDATA[").append(getRequiredDecimal(availStk, 3)).append("]]>").append("</avail_qty>\r\n");
					xmlDataString.append("<qty protect = '1'>").append("<![CDATA[").append(getRequiredDecimal(quarntineStk, 3)).append("]]>").append("</qty>\r\n");
					xmlDataString.append("<net_req_qty protect = '1'>").append("<![CDATA[").append(getRequiredDecimal(netReqQty, 3)).append("]]>").append("</net_req_qty>\r\n");
					xmlDataString.append("<pind_qty protect = '1'>").append("<![CDATA[").append(getRequiredDecimal(pendIndQty, 3)).append("]]>").append("</pind_qty>\r\n");
					xmlDataString.append("<ppo_qty protect = '1'>").append("<![CDATA[").append(getRequiredDecimal(pendPOQty, 3)).append("]]>").append("</ppo_qty>\r\n");
					xmlDataString.append("</Detail" + context + ">");
				}
				xmlDataString.append("</Root>");
				System.out.println("XML String For Requirement =" + xmlDataString.toString());
			}


			/* End Added by sachin on 26/06/13 */
		} catch (Exception e)
		{
			System.out.println("Exception : XML String : " + xmlString);
			System.out.println("Exception :RunMRPPrcEJB : updateDemand(String).." + e.getMessage());
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		}

	}

	private int indexOfADPElement(String siteCode, String itemCode, String saleOrder, String lineNo) throws ITMException, Exception
	{
		int retVal = -1, ctr = 0;
		ADPElement adpElement = null;
		if (saleOrder == null || saleOrder.trim().length() == 0)
		{
			saleOrder = "          ";
		}
		if (lineNo == null || lineNo.trim().length() == 0)
		{
			lineNo = "   ";
		}
		System.out.println("adpeList.size()------" + adpeList.size());
		for (ctr = 0; ctr < adpeList.size(); ctr++)
		{
			adpElement = (ADPElement) adpeList.get(ctr);
			System.out.println("adpElement------getSiteCode" + adpElement.getSiteCode());
			System.out.println("adpElement------getItemCode" + adpElement.getItemCode());
			System.out.println("adpElement------getSaleOrder" + adpElement.getSaleOrder());
			System.out.println("adpElement------getLineNo" + adpElement.getLineNo());
			System.out.println("siteCode["+siteCode+"]itemCode["+itemCode+"]saleOrder["+saleOrder+"]lineNo["+lineNo+"]");
			//if ((adpElement.getSiteCode().equals(siteCode)) && (adpElement.getItemCode().equals(itemCode)) && (adpElement.getSaleOrder().equals(saleOrder)) && (adpElement.getLineNo().equals(lineNo)))
			if ((  adpElement.getSiteCode().equals(siteCode)) && (adpElement.getItemCode().equals(itemCode)) && (adpElement.getSaleOrder().equals(saleOrder)) && ( (adpElement.getLineNo()==null?"":adpElement.getLineNo()).equals(lineNo)))
			{
				retVal = ctr;
				break;
			}
		}
		return retVal;
	}
	private int indexOfADPElement(String siteCode, String itemCode) throws ITMException, Exception
	{
		int retVal = -1, ctr = 0;
		ADPElement adpElement = null;

		//cpatil-25/08/14-System.out.println("adpeList.size()------" + adpeList.size());
		for (ctr = 0; ctr < adpeList.size(); ctr++)
		{
			adpElement = (ADPElement) adpeList.get(ctr);
			//cpatil-25/08/14-System.out.println("adpElement------" + adpElement.getSiteCode() + "----" + adpElement.getItemCode());
			if ((adpElement.getSiteCode().equals(siteCode)) && (adpElement.getItemCode().equals(itemCode)))
			{
				retVal = ctr;
				break;
			}
		}
		return retVal;
	}

	private String populateInterSiteDistance() throws ITMException, Exception
	{
		String siteCode = "";
		String siteCodeFrom = "";
		double distance = 0;
		Statement stmt = null;
		ResultSet rs = null;
		try
		{
			stmt = conn.createStatement();
			String sql = "SELECT SITE_CODE, SITE_CODE__FROM, DISTANCE " + "FROM DIST_INTERSITE_OPTIONS  " + "ORDER BY SITE_CODE ASC," + "DISTANCE ASC";
			rs = stmt.executeQuery(sql);
			while (rs.next())
			{
				InterSiteDistance interSite = new InterSiteDistance();
				siteCode = rs.getString(1);
				siteCodeFrom = rs.getString(2);
				distance = rs.getDouble(3);

				interSite.setSiteCode(siteCode);
				interSite.setSiteCodeFrom(siteCodeFrom);
				interSite.setDistance(distance);

				interSiteList.add(interSite);
			}
			rs.close();
			stmt.close();
		} catch (SQLException e)
		{
			System.out.println("SQLException : populateInterSiteDistance() : " + e.getMessage());
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			throw new ITMException(e);
		} catch (Exception e)
		{
			System.out.println("Exception :populateInterSiteDistance():" + e.getMessage() + ":");
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			throw new ITMException(e);
		} finally
		{
			if (stmt != null)
			{
				stmt = null;
			}
			if (rs != null)
			{
				rs = null;
			}
			// Commented by Jiten as the block is not required - Jiten 03/11/06
			/*
			 * if( (errString != null) && (errString.trim().length() > 0) ) {
			 * System.out.println("Error String :===> "+errString); return
			 * errString; } else { return errString; }
			 */
		}
		return errString;// Moved here as Finally block does not complete
		// normally - jiten -03/11/06
	}

	private double getDistance(String siteCodeFrom, String siteCodeTo) throws ITMException, Exception
	{
		InterSiteDistance interSite = null;
		int interSiteEle = -1;
		for (int index = 0; index < interSiteList.size(); index++)
		{
			interSite = (InterSiteDistance) (interSiteList.get(index));

			if ((interSite.getSiteCodeFrom().trim().equals(siteCodeFrom.trim())) && (interSite.getSiteCode().trim().equals(siteCodeTo.trim())))
			{
				interSiteEle = index;
				break;
			} else if ((interSite.getSiteCodeFrom().trim().equals(siteCodeTo.trim())) && (interSite.getSiteCode().trim().equals(siteCodeFrom.trim())))
			{
				interSiteEle = index;
				break;
			}
		}
		if (interSiteEle == -1)
		{
			//cpatil-25/08/14-System.out.println("Site Code From/To not found in intersite distance");
			return -1;
		} else
		{
			return interSite.getDistance();
		}
	}

	private void populateSurplusList() throws ITMException, Exception
	{
		ADPElement adpElement = null;
		SurplusStock surplusStock = null;
		double surplusQuantity = 0;
		String siteCode = "";
		String itemCode = "";
		for (int index = 0; index < adpeList.size(); index++)
		{
			adpElement = (ADPElement) adpeList.get(index);
			if (adpElement.getSupply() > adpElement.getMaxQty())
			{
				surplusStock = new SurplusStock();
				siteCode = adpElement.getSiteCode();
				itemCode = adpElement.getItemCode();
				surplusQuantity = adpElement.getSupply() - adpElement.getMaxQty();
				surplusStock.setSiteCode(siteCode);
				surplusStock.setItemCode(itemCode);
				surplusStock.setSurplusQuantity(surplusQuantity);
				surplusList.add(surplusStock);
				surplusListOriginal.add(surplusStock);
			}
		}
	}

	private String getSurplusStockSite(String siteCode, String itemCode, double Qty, ArrayList surplusList) throws ITMException, Exception
	{
		String siteCodeFrom = null;
		SurplusStock surplusStock = null;
		InterSiteDistance intersiteDistance = null;
		String surplusSiteCode = null;
		for (int ctr = 0; ctr < interSiteList.size(); ctr++)
		{
			intersiteDistance = (InterSiteDistance) interSiteList.get(ctr);
			if (intersiteDistance.getSiteCode().trim().equals(siteCode.trim()))
			{
				siteCodeFrom = intersiteDistance.getSiteCodeFrom();
				for (int index = 0; index < surplusList.size(); index++)
				{
					surplusStock = (SurplusStock) surplusList.get(index);
					if ((surplusStock.getSiteCode().trim().equals(siteCodeFrom.trim())) && (surplusStock.getItemCode().trim().equals(itemCode.trim())))
					{
						if (Qty <= surplusStock.getSurplusQuantity())
						{
							surplusSiteCode = siteCodeFrom;
							break;
						}
					}
				}
				if (surplusSiteCode != null)
				{
					break;
				}
			}
		}
		return surplusSiteCode;
	}

	void cleanup()
	{
		itemCodeMap.clear();
		siteCodeMap.clear();
		itemHashMap.clear();
		adpeList.clear();
		interSiteList.clear();
		surplusList.clear();
		surplusListOriginal.clear();
		indList.clear();
		mpsList.clear();
		indDemList.clear();
		disList.clear();
	}

	public String getDateFromTimeStamp(java.sql.Timestamp timeStampDate, String targetFormat) throws ITMException, Exception
	{
		String retStrDate = null;
		try
		{
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(targetFormat);
			retStrDate = simpleDateFormat.format(timeStampDate);
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :getDateFromTimeStamp(TimeStampDate) " + e);
			throw new ITMException(e);
		}
		return retStrDate;
	}

	public String deleteOldPlan(String siteCode, String itemCode) throws ITMException, Exception
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String mfgType = "";
		String sqlMpsOrder, sqlWorkOrder;
		String sqlIndent;
		String sqlDistDemand;
		int rowsDeleted = 0;
		boolean isbomReplaceFlag = false;
		try
		{
			genericUtility = GenericUtility.getInstance();

			if( conn == null)
			{
				isbomReplaceFlag= true;
				ConnDriver connDriver = new ConnDriver();
				conn = connDriver.getConnectDB("DriverITM");
			}

			sqlIndent = "DELETE FROM INDENT " + "WHERE SITE_CODE = ? " + "AND ITEM_CODE IN (" + "SELECT CASE WHEN ITEM_CODE__PLAN IS NULL THEN ITEM_CODE ELSE ITEM_CODE__PLAN END " + "FROM ITEM " + "WHERE ITEM_CODE = ? ) " + "AND STATUS = 'U' " + "AND IND_TYPE = 'M' ";

			sqlMpsOrder = "DELETE FROM MPS_ORDER " + "WHERE SITE_CODE = ? " + "AND ITEM_CODE = ? "+ " AND STATUS in ('M')";//Manoj dtd 14/07/2014 Status Changed from N to M

			sqlWorkOrder = "DELETE FROM WORKORDER " + "WHERE SITE_CODE = ? " + "AND ITEM_CODE = ? " + " AND  STATUS in ('M')";   // replace ORDER_TYPE inplace of STATUS column  ... 17/06/14...
			sqlDistDemand = "DELETE FROM DIST_DEMAND " + " WHERE STATUS = 'P' " + "AND SITE_CODE  = ? " + "AND ITEM_CODE = ? ";

			if (matPlan.equals("Y"))
			{
				pstmt = conn.prepareStatement(sqlIndent);
				pstmt.setString(1, siteCode);
				pstmt.setString(2, itemCode);
				rowsDeleted = pstmt.executeUpdate();
				System.out.println("Rows Deleted in Indent :" + rowsDeleted);
				conn.commit();
				pstmt.close();
			}

			if (mfgPlan.equals("Y"))
			{
				pstmt = conn.prepareStatement(sqlMpsOrder);
				pstmt.setString(1, siteCode);
				pstmt.setString(2, itemCode);
				rowsDeleted = pstmt.executeUpdate();
				System.out.println("Rows Deleted in MpsOrder :" + rowsDeleted);
				conn.commit();
				pstmt.close();
				pstmt = conn.prepareStatement("select mfg_type from siteitem where site_code=? and item_code=? ");
				pstmt.setString(1, siteCode);
				pstmt.setString(2, itemCode);
				rs = pstmt.executeQuery();
				while (rs.next())
				{
					mfgType = rs.getString(1);
				}
				rs.close();
				rs = null;
				pstmt.close();
				pstmt = null;
				// comment code for not deleting workorder 
				if (mfgType != null && ((mfgType.trim()).equalsIgnoreCase("O")))
				{
					pstmt = conn.prepareStatement(sqlWorkOrder);
					pstmt.setString(1, siteCode);
					pstmt.setString(2, itemCode);
					rowsDeleted = pstmt.executeUpdate();
					System.out.println("Rows Deleted in WorkOrder :" + rowsDeleted);
					conn.commit();
					pstmt.close();
				}

			}

			if (disPlan.equals("Y"))
			{
				pstmt = conn.prepareStatement(sqlDistDemand);
				pstmt.setString(1, siteCode);
				pstmt.setString(2, itemCode);
				rowsDeleted = pstmt.executeUpdate();
				System.out.println("Rows Deleted in DistDemand :" + rowsDeleted);
				conn.commit();
				pstmt.close();
			}

			if( isbomReplaceFlag == true )
			{
				conn.close();
				conn = null;
			}

		} catch (SQLException e)
		{
			System.out.println("SQLException :RunMRPPrcEJB : deleteOldPlan().." + e.getMessage());
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB : deleteOldPlan() : " + e.getMessage());
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			if (pstmt != null)
			{
				pstmt = null;
			}
			// return errString;
		}
		return errString;// Moved here as Finally block does not complete
		// normally - jiten -03/11/06
	}

	private String generatePlanDemand() throws ITMException, Exception
	{
		ADPElement adpElement = null;

		try
		{
			for (int adpeCtr = 0; adpeCtr < adpeList.size(); adpeCtr++)
			{
				adpElement = (ADPElement) adpeList.get(adpeCtr);
				//cpatil-25/08/14-System.out.println("4571---adpElement----"+adpElement.getSiteCode()+"---"+adpElement.getItemCode()+"---"+adpElement.getDemand()+"---"+adpElement.getSupply());
			}
			for (int adpeCtr = 0; adpeCtr < adpeList.size(); adpeCtr++)
			{
				adpElement = (ADPElement) adpeList.get(adpeCtr);
				//cpatil-25/08/14-System.out.println("01/04/11 SO adpeCtr [" + adpeCtr + "] SO [" + adpElement.getSaleOrder() + "]");
				errString = generatePlanDemand(adpElement);
				if (errString != null && errString.trim().length() > 0)
				{
					System.out.println("Error While generating Plan Demand for " + adpElement.getItemCode() + "..." + errString);
					return errString;
				}
			}
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :CreatePlanDemand ():" + e.getMessage() + ":");
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		}
		return errString;
	}

	private String generatePlanDemand(ADPElement adpElement) throws ITMException, Exception
	{
		PreparedStatement pstmtMpsOrder = null;
		PreparedStatement pstmtIndent = null;
		PreparedStatement pstmtDistDemand = null;
		double runningDemand = 0;
		double runningSupply = 0;
		double runningPlanSupply = 0;
		try
		{

			java.sql.Timestamp dueDate = null;
			java.sql.Timestamp curDate = null;
			java.sql.Timestamp chgDate = new java.sql.Timestamp(System.currentTimeMillis());
			double reqQty = 0;
			double balQty = 0;
			double createQty = 0;
			double independentDemand = 0;

			double demand = adpElement.getDemand();
			double supply = adpElement.getSupply();
			String itemCode = adpElement.getItemCode();
			String siteCode = adpElement.getSiteCode();
			String suppSour = adpElement.getSuppSour();
			String bomCode = adpElement.getBomCode();
			double minQty = adpElement.getMinQty();
			int minStkDay = adpElement.getMinStkDay();
			double reoQty = adpElement.getReoQty();
			int purLeadTime = adpElement.getPurLeadTime();
			int qcLeadTime = adpElement.getQcLeadTime();
			double integralQty = adpElement.getIntegralQty();
			String itemStru = adpElement.getItemStru();
			String siteCodeSupp = adpElement.getSiteCodeSupp();
			String siteCodePlan = adpElement.getSiteCodePlan();
			String batchQtyType = adpElement.getBatchQtyType();
			double minOrderQty = adpElement.getMinOrderQty();
			int maxStkDay = adpElement.getMaxStkDay();
			double maxQty = adpElement.getMaxQty();
			String orderOpt = adpElement.getOrderOpt();
			double yieldPerc = adpElement.getYieldPerc();
			String masterSch = adpElement.getMasterSch();
			int mfgLeadTime = adpElement.getMfgLeadTime();
			double minPlanPerc = adpElement.getMinPlanPerc();
			double batchQty = adpElement.getBatchQty();
			String unit = adpElement.getUnit();
			String itemDescr = adpElement.getItemDescr();
			String mfgType = adpElement.getMfgType();
			ArrayList timeMRParr = adpElement.getTimeMrpList();

			curDate = new java.sql.Timestamp(System.currentTimeMillis());
			SimpleDateFormat sdt = new SimpleDateFormat("yyyy-MM-dd");
			curDate = java.sql.Timestamp.valueOf(sdt.format(curDate) + " 00:00:00.000");
			java.sql.Timestamp horizonDate = null;

			int multiplier = 0;

			String errString = "";
			// check stk_opt
			if (getStkOpt(itemCode, siteCode).equals("0"))
			{
				return "";
			}
			if (demand - supply <= 0)
			{
				return "";
			}
			for (int timeCtr = 0; timeCtr < timeMRParr.size(); timeCtr++)
			{
				TimeMRP timeMrp = (TimeMRP) timeMRParr.get(timeCtr);
				runningDemand = timeMrp.getRunningDemand();
				runningSupply = timeMrp.getRunningSupply();
				runningPlanSupply = timeMrp.getRunningPlanSupply();
				independentDemand = timeMrp.getIndependentDemand();
				dueDate = timeMrp.getDueDate();
				System.out.println("@@@@ before MrpClubbingHorizon["+MrpClubbingHorizon+"]horizonDate["+horizonDate+"]dueDate["+dueDate+"]itemCode["+itemCode+"]");
				if (MrpClubbingHorizon > 0)
				{
					Calendar calen = Calendar.getInstance();
					calen.setTime(dueDate);
					calen.add(Calendar.DAY_OF_MONTH, MrpClubbingHorizon);
					horizonDate = new java.sql.Timestamp(System.currentTimeMillis());
					horizonDate.setTime(((java.util.Date) calen.getTime()).getTime());
					System.out.println("@@@@ inside1 MrpClubbingHorizon["+MrpClubbingHorizon+"]horizonDate["+horizonDate+"]dueDate["+dueDate+"]");
				} else
					// 02/05/11 manoharan
				{
					horizonDate = dueDate;
					System.out.println("@@@@ inside2 MrpClubbingHorizon["+MrpClubbingHorizon+"]horizonDate["+horizonDate+"]dueDate["+dueDate+"]");
				}
				System.out.println("@@@@ after MrpClubbingHorizon["+MrpClubbingHorizon+"]horizonDate["+horizonDate+"]dueDate["+dueDate+"]");
				reqQty = timeMrp.getPlanSupply(); // runningDemand -
				// runningSupply -
				// runningPlanSupply;
				System.out.println("@@@@@@cpatil-reqQty["+reqQty+"]orderOpt["+orderOpt+"]independentDemand["+independentDemand+"]batchQty["+batchQty+"]");
				if (reqQty > 0)
				{
					// System.out.println("Plan  Supply :" + reqQty +
					// " Orderopt " + orderOpt + " Suppsour " + suppSour +
					// " Mfg Type " + mfgType + " Made To Order " + madeToOrder
					// + "Mfg Plan " + mfgPlan );

					if (dueDate.compareTo(curDate) < 0)
					{
						dueDate = curDate;
						horizonDate = dueDate;
					}

					// if (suppSour.equals("D") && disPlan.equals("Y") &&
					// siteCodeSupp != null && siteCodeSupp.trim().length() > 0
					// )
					if (independentDemand > 0)
					{
						// independent demand to be created
						if (orderOpt.equals("B"))
						{
							if (independentDemand > batchQty)
							{
								if (independentDemand % batchQty > 0)
								{
									// multiplier = ((int)Math.floor(reqQty /
									// batchQty)) + 1;
									multiplier = new Double(Math.floor(independentDemand / batchQty)).intValue() + 1;
								} else
								{
									// multiplier = (int)Math.floor(reqQty /
									// batchQty);
									multiplier = new Double(Math.floor(independentDemand / batchQty)).intValue();
								}
							} else
							{
								multiplier = 1;
							}
							//cpatil-25/08/14-System.out.println("@@@@@@cpatil-multiplier["+multiplier+"]");
							createQty = batchQty;
							for (int planCtr = 0; planCtr < multiplier; planCtr++)
							{
								IndependentDemand indDem = new IndependentDemand();
								indDem.tranDate = curDate;
								indDem.siteCode = siteCode;
								indDem.itemCode = itemCode;
								indDem.planDueDate = dueDate;
								indDem.dueDate = dueDate;
								indDem.quantity = createQty;
								indDem.quantityStdUom = createQty;
								indDem.convQtyStdUom = 1;
								indDem.unit = unit;
								indDem.unitStd = unit;
								indDem.status = "O";
								indDem.siteCodeCust = adpElement.getSiteCodeCust();

								indDemList.add(indDem);

							}
							//cpatil-25/08/14-System.out.println("@@@@@@cpatil-indDemList["+indDemList+"]");
						} else if (orderOpt.equals("C"))
						{
							int findEle = -1;
							IndependentDemand indDem = null;
							if (indDemList.size() > 0)
							{
								// check for the last ones existence if found
								// add the demand to that
								for (int listCtr = indDemList.size() - 1; listCtr > 0; listCtr--)
								{
									indDem = (IndependentDemand) indDemList.get(listCtr);
									if (indDem.itemCode.trim() == itemCode.trim() && indDem.siteCode.trim() == siteCode.trim() && indDem.siteCodeCust.trim() == adpElement.getSiteCodeCust().trim() && (dueDate.compareTo(horizonDate) <= 0))
									{
										findEle = listCtr;
										break;
									}
								}
							}
							if (findEle >= 0)
							{
								indDem.quantity += independentDemand;
								indDem.quantityStdUom += independentDemand;
								indDemList.set(findEle, indDem);
							} else
							{
								IndependentDemand newIndDem = new IndependentDemand();
								newIndDem.tranDate = curDate;
								newIndDem.siteCode = siteCode;
								newIndDem.itemCode = itemCode;
								newIndDem.planDueDate = dueDate;
								newIndDem.dueDate = dueDate;
								newIndDem.quantity = independentDemand;
								newIndDem.quantityStdUom = independentDemand;
								newIndDem.convQtyStdUom = 1;
								newIndDem.unit = unit;
								newIndDem.unitStd = unit;
								newIndDem.status = "O";
								newIndDem.siteCodeCust = adpElement.getSiteCodeCust();

								indDemList.add(newIndDem);
							}
							//cpatil-25/08/14-System.out.println("@@@@@@cpatil22-indDemList["+indDemList+"]");
						}

					} // (suppSour.equals("D") && disPlan.equals("Y") &&
					// siteCodeSupp != null && siteCodeSupp.trim().length() >
					// 0 )

					// else if (( suppSour.equals("P") || suppSour.equals("C")
					// )&& matPlan.equals("Y") )
					System.out.println("15032014---suppSour----"+suppSour+"---matPlan---"+matPlan+"---mfgPlan---"+mfgPlan+"---");
					System.out.println("suppSour["+suppSour+"]mfgType["+mfgType+"]"+"orderOpt["+orderOpt+"]batchQtyType["+batchQtyType+"]");
					System.out.println("Indent creation Plan  Supply :" +
							reqQty + " Orderopt " + orderOpt + " Suppsour " +
							suppSour + " Mat Plan " + matPlan +" batchQty "+batchQty+" batchQtyType "+batchQtyType);
					if ((suppSour.equals("P") || suppSour.equals("C")) && matPlan.equals("Y"))
					{
						//System.out.println("Indent creation Plan  Supply :" +
						//reqQty + " Orderopt " + orderOpt + " Suppsour " +
						//suppSour + " Mat Plan " + matPlan +" batchQty "+batchQty+" batchQtyType "+batchQtyType);
						// independent demand to be created
						if (orderOpt.equals("B"))
						{
							if (reqQty > batchQty)
							{
								if (reqQty % batchQty > 0)
								{
									// multiplier = ((int)Math.floor(reqQty /
									// batchQty)) + 1;
									multiplier = new Double(Math.floor(reqQty / batchQty)).intValue() + 1;
								} else
								{
									// multiplier = (int)Math.floor(reqQty /
									// batchQty);
									multiplier = new Double(Math.floor(reqQty / batchQty)).intValue();
								}
							} else
							{
								multiplier = 1;
							}

							createQty = batchQty;
							for (int planCtr = 0; planCtr < multiplier; planCtr++)
							{
								Indent indent = new Indent();
								indent.indDate = curDate;
								indent.deptCode = deptCodeMfg;
								indent.planDueDate = dueDate;
								indent.reqDate = dueDate;
								indent.itemCode = itemCode;
								indent.itemDescr = itemDescr;
								indent.quantity = batchQty;
								indent.quantityStdUom = batchQty;
								indent.unitInd = unit;
								indent.unitStd = unit;
								indent.siteCode = siteCode;
								indent.siteCodeDlv = siteCode;
								indent.siteCodeAcct = siteCode;
								indent.aprCode = adpElement.getAprCode();
								indent.acctCode = adpElement.getAcctCodePh();
								indent.cctrCode = adpElement.getCctrCodePh();
								indent.empCodePur = adpElement.getEmpCodePur();
								//indent.empCodeReq = adpElement.getEmpCodePur();
								indent.empCodeReq = adpElement.getEmpCodePlan();//Manoj dtd 11/03/2014 to set EmpCode Plan in Emp_code__req
								indent.suppCodePref = adpElement.getSuppCodePref();
								indent.purcRate = adpElement.getPurcRate();
								;
								indent.packCode = adpElement.getPackCode();
								indent.chgDate = chgDate;
								indent.chgUser = userId;
								indent.chgTerm = userId;
								indent.purLeadTime = purLeadTime;
								indent.convQtyStdUom = 1;
								indent.itemSer=adpElement.getItemSer();//Added by manoj dtd 11/03/2014
								indList.add(indent);
							}
							//cpatil-25/08/14-System.out.println("@@@@@@cpatil333-indList["+indList+"]");
						} else if (orderOpt.equals("C"))
						{
							int findEle = -1;
							Indent indent = null;
							if (indList.size() > 0)
							{
								// check for the last ones existence if found
								// add the demand to that
								for (int listCtr = indList.size() - 1; listCtr > 0; listCtr--)
								{
									indent = (Indent) indList.get(listCtr);
									if (indent.itemCode.trim() == itemCode.trim() && indent.siteCode.trim() == siteCode.trim() && (dueDate.compareTo(horizonDate) <= 0))
									{
										findEle = listCtr;
										break;
									}
								}
							}
							//cpatil-25/08/14-System.out.println("findEle-----"+findEle);
							if (findEle >= 0)
							{
								indent.quantity += reqQty;
								indent.quantityStdUom += reqQty;
								indList.set(findEle, indent);
							} else
							{
								Indent newIndent = new Indent();
								newIndent.indDate = curDate;
								newIndent.deptCode = deptCodeMfg;
								newIndent.planDueDate = dueDate;
								newIndent.reqDate = dueDate;
								newIndent.itemCode = itemCode;
								newIndent.itemDescr = itemDescr;
								newIndent.quantity = reqQty;
								newIndent.quantityStdUom = reqQty;
								newIndent.unitInd = unit;
								newIndent.unitStd = unit;
								newIndent.siteCode = siteCode;
								newIndent.siteCodeDlv = siteCode;
								newIndent.siteCodeAcct = siteCode;
								newIndent.aprCode = adpElement.getAprCode();
								newIndent.acctCode = adpElement.getAcctCodePh();
								newIndent.cctrCode = adpElement.getCctrCodePh();
								newIndent.empCodePur = adpElement.getEmpCodePur();
								//newIndent.empCodeReq = adpElement.getEmpCodePur();
								newIndent.empCodeReq = adpElement.getEmpCodePlan();//Manoj dtd 11/03/2014 to set EmpCode Plan in Emp_code__req
								newIndent.suppCodePref = adpElement.getSuppCodePref();
								newIndent.purcRate = adpElement.getPurcRate();
								;
								newIndent.packCode = adpElement.getPackCode();
								newIndent.chgDate = chgDate;
								newIndent.chgUser = userId;
								newIndent.chgTerm = userId;
								newIndent.purLeadTime = purLeadTime;
								newIndent.convQtyStdUom = 1;

								// System.out.println("Indent creation for :" +
								// itemCode + " " + decFormat(reqQty) );
								newIndent.itemSer=adpElement.getItemSer();//Added by manoj dtd 11/03/2014
								indList.add(newIndent);
							}
						}
						//cpatil-25/08/14-System.out.println("orderOpt--------"+orderOpt+"---");
					} // (( suppSour.equals("P") || suppSour.equals("C") )&&
					// matPlan.equals("Y") )
					else if (suppSour.equals("M") && mfgPlan.equals("Y"))
					{
						// IF ITEM IS MADE TO ORDER AND IF MADE TO STOCK OPTION
						// IS SELECTED THEN
						// SKIP CREATION OF WORKORDER......AT GNL 10/4/02 BY
						// MANOJ AS PER KANDARP
						System.out.println("madeToOrder["+madeToOrder+"]mfgType["+mfgType+"]");
						if (madeToOrder.equals("1") && mfgType != null && mfgType.trim().equals("O"))
						{
							System.out.println("Returning value");
							return "";
						}
						// batchQtyType != v added as per Manoharan Sir - Jiten
						// - 02/11/06
						System.out.println("6912--orderOpt["+orderOpt+"]batchQtyType["+batchQtyType+"reqQty["+reqQty+"]batchQty["+batchQty+"]");
						if (orderOpt.equals("B") && !(batchQtyType.equalsIgnoreCase("V")))
						{
							System.out.println("11012008 Req Qty : " + reqQty + " batch Qty :" + batchQty + " Min Plan :" + minPlanPerc);
							if (reqQty > batchQty)
							{
								if (reqQty % batchQty > 0)
								{
									if ((reqQty % batchQty) >= (batchQty * minPlanPerc / 100))
									{
										// multiplier = ((int)Math.floor(reqQty
										// / batchQty)) + 1;
										multiplier = new Double(Math.floor(reqQty / batchQty)).intValue() + 1;
									} else
									{
										// multiplier = (int)Math.floor(reqQty /
										// batchQty);
										multiplier = new Double(Math.floor(reqQty / batchQty)).intValue();
									}
								} else
								{
									// multiplier = (int)Math.floor(reqQty /
									// batchQty);
									multiplier = new Double(Math.floor(reqQty / batchQty)).intValue();
								}
							} else
							{
								if (reqQty >= (batchQty * minPlanPerc / 100))
								{
									multiplier = 1;
								}
							}

							createQty = batchQty;
							if (itemCode.trim().equalsIgnoreCase("BD0783"))
							{
								//cpatil-25/08/14-System.out.println("11012008 Mulitplier : " + multiplier + " Batch Qty " + decFormat(batchQty) + " Req Qty : " + decFormat(reqQty) + " Item : " + itemCode + " Site " + siteCode);
							}
							System.out.println("11012008 Mulitplier : " + multiplier + " Batch Qty " + decFormat(batchQty) + " Req Qty : " + decFormat(reqQty) + " Item : " + itemCode + " Site " + siteCode);
							for (int planCtr = 0; planCtr < multiplier; planCtr++)
							{
								MPSOrder mpsOrder = new MPSOrder();

								mpsOrder.ordType = adpElement.getMfgType();
								mpsOrder.itemCode = itemCode;
								mpsOrder.siteCode = siteCode;
								mpsOrder.quantity = batchQty;
								mpsOrder.ordDate = curDate;
								mpsOrder.planDueDate = dueDate;
								// ld_worder.setitem(ll_row, "MRP_RUN_ID",
								// ls_org_tran_id)
								// ld_worder.setitem(ll_row, "ADDN_ORDER",
								// trim(ls_addntranid))

								String tempSORef="";
								System.out.println(" for addnOrder code itemCode["+itemCode+"] parentItemMap 1 ["+parentItemMap+"]");
								if(  parentItemMap.containsKey(itemCode) )
								{
									String tempParentItem =  parentItemMap.get(itemCode).toString(); 
									System.out.println("@@@@@@@tempParentItem1["+tempParentItem+"]");
									if( tempParentItem != null && tempParentItem.trim().length() > 0 )
									{
										do
										{
											System.out.println("@@@@@@@tempParentItem2["+tempParentItem+"]");
											if( tempParentItem != null && tempParentItem.trim().length() > 0 )
											{
												if( soItemListMap.size() > 0 )
												{	
													if( soItemListMap.containsKey(tempParentItem))
													{
														tempSORef =  checkNull(soItemListMap.get(tempParentItem)+"").toString();
														mpsOrder.addnOrder=tempSORef;
														break;
													}else
													{
														String tempValue = tempParentItem;
														tempParentItem =  parentItemMap.get(tempParentItem)== null?"":checkNull(parentItemMap.get(tempParentItem)+"").toString();//checknull added by mnaoj dtd 03/04/2015
														System.out.println("@@@@@tempParentItem["+tempParentItem+"]tempValue["+tempValue+"]");
														if(tempValue.equalsIgnoreCase(tempParentItem) )
														{
															break;
														}
													}
												}
												else
												{
													break;
												}
											}
										}
										while (  parentItemMap.containsKey(tempParentItem)  );
									}
								}
								else
								{
									mpsOrder.addnOrder=  checkNull(soItemListMap.get(itemCode)+"").toString();//checknull added by mnaoj dtd 03/04/2015
								}
								System.out.println("@@@@@@@@@itemCode 2 ["+itemCode+"] tempSORef["+tempSORef+"]");

								//mpsList.add(mpsOrder);

								//String refSaleOrder="";
								/*ArrayList<String> addnOrderList =  adpElement.getOrderList();
								for( int ordCnt=0; ordCnt < addnOrderList.size(); ordCnt++ )
								{
									String temp = addnOrderList.get(ordCnt);
									String[]  addnOrderArray =   temp.split("@");

									if( addnOrderArray.length ==3 )
									{
										refSaleOrder =  refSaleOrder + addnOrderArray[0] + ",";
									}
								}
								System.out.println("@@@@@ refSaleOrder["+refSaleOrder+"]  for addnOrder code end");
								mpsOrder.addnOrder=refSaleOrder;

								if(  refSaleOrder == null || refSaleOrder.trim().length()==0 )*/
								{
									/*if( locGroupList != null )
								{
									System.out.println("@@@@@ locGroupList["+locGroupList+"]");
									String locGroupLst[]=locGroupList.split(",");
									System.out.println("@@@@@ locGroupLst.length["+locGroupLst.length+"]");
									for(int i=0;i<locGroupLst.length;i++)
									{
										String SOrder="";
										String tempLocGroup=locGroupLst[i];
										System.out.println("@@@@@ tempLocGroup["+tempLocGroup+"]");
										String tempLocGroupArr[]=tempLocGroup.split("@");
										if( tempLocGroupArr.length > 0 )
										{
											SOrder=tempLocGroupArr[0];
											refSaleOrder =  refSaleOrder + SOrder + ",";
										}

										System.out.println("@@@@@7530 refSaleOrder["+refSaleOrder+"]");


									}
									System.out.println("@@@@@final refSaleOrder["+refSaleOrder+"]");
									mpsOrder.addnOrder=refSaleOrder;
								}*/

								}


								mpsOrder.dueDate = dueDate;
								mpsOrder.status = "P";
								mpsOrder.statusDate = curDate;
								mpsOrder.yieldPerc = yieldPerc;
								mpsOrder.routeCode = adpElement.getRouteCode();
								mpsOrder.bomCode = adpElement.getBomCode();
								// ld_worder.setitem(ll_row, "proj_code",
								// ls_proj_code)
								mpsOrder.chgDate = chgDate;
								mpsOrder.chgUser = userId;
								mpsOrder.chgTerm = userId;
								mpsOrder.unit = unit;
								mpsOrder.acctCodeWp = adpElement.getAcctCodeWp();
								mpsOrder.cctrCodeWp = adpElement.getCctrCodeWp();
								mpsOrder.curBatchQty = batchQty;
								// ld_worder.setitem(ll_row, "std_qty",
								// lc_create_qty) // 04-07-03
								// ld_worder.setitem(ll_row, "demand_qty",
								// lc_actualdemand)
								// 01/04/11 manoharan
								//cpatil-25/08/14-System.out.println("01/04/11 setting SO in MPS A [" + adpElement.getSaleOrder() + "]");
								mpsOrder.saleOrder = adpElement.getSaleOrder();
								mpsOrder.lineNo = adpElement.getLineNo();
								mpsOrder.mfgType = adpElement.getMfgType();
								// end 01/04/11 manoharan



								mpsList.add(mpsOrder);
								System.out.println("@@@@2103152:mpsOrder.quantity["+mpsOrder.quantity+"]mpsList["+mpsList.size()+"]");
							}
						}
						// Condition to be added as per Manoharan Sir - Jiten
						// 02/11/06
						// Else if condition added by Jiten as per Manoharan Sir
						// - 03/11/06
						else if (orderOpt.equals("B") && batchQtyType.equalsIgnoreCase("V"))
						{
							System.out.println("reqQty["+reqQty+"]batchQty["+batchQty+"]");
							if (reqQty >= batchQty)
							{
								System.out.println("2");
								// Below block is commented as per Manoharan Sir
								// - Jiten - 03/11/06
								/*
								 * if ( reqQty % batchQty > 0) { if ( (reqQty %
								 * batchQty) >= (batchQty * minPlanPerc / 100 ))
								 * { //multiplier = ((int)Math.floor(reqQty /
								 * batchQty)) + 1; multiplier = new
								 * Double(Math.floor(reqQty /
								 * batchQty)).intValue() + 1; } else {
								 * //multiplier = (int)Math.floor(reqQty /
								 * batchQty); multiplier = new
								 * Double(Math.floor(reqQty /
								 * batchQty)).intValue(); } }
								 */
								// else
								// {
								// multiplier = (int)Math.floor(reqQty /
								// batchQty);
								multiplier = new Double(Math.floor(reqQty / batchQty)).intValue();
								balQty = reqQty - (multiplier * batchQty);
								// }
								// End Comment
							} else
							{
								// if (reqQty >= (batchQty * minPlanPerc / 100
								// ))
								// {
								// multiplier = 1;
								// }
								balQty = reqQty;
								multiplier = 0;
							}
							createQty = batchQty;
							if (itemCode.trim().equalsIgnoreCase("BD0783"))
							{
								//cpatil-25/08/14-System.out.println("11012008 Mulitplier : " + multiplier + " Batch Qty " + decFormat(batchQty) + " Req Qty : " + decFormat(reqQty) + " Item : " + itemCode + " Site " + siteCode);
							}
							System.out.println("11012008 Mulitplier : " + multiplier + " Batch Qty " + decFormat(batchQty) + " Req Qty : " + decFormat(reqQty) + " Item : " + itemCode + " Site " + siteCode);
							for (int planCtr = 0; planCtr < multiplier; planCtr++)
							{
								MPSOrder mpsOrder = new MPSOrder();

								mpsOrder.ordType = adpElement.getMfgType();
								mpsOrder.itemCode = itemCode;
								mpsOrder.siteCode = siteCode;
								mpsOrder.quantity = batchQty;
								mpsOrder.ordDate = curDate;
								mpsOrder.planDueDate = dueDate;
								// ld_worder.setitem(ll_row, "MRP_RUN_ID",
								// ls_org_tran_id)
								// ld_worder.setitem(ll_row, "ADDN_ORDER",
								// trim(ls_addntranid))
								mpsOrder.dueDate = dueDate;
								mpsOrder.status = "P";
								mpsOrder.statusDate = curDate;
								mpsOrder.yieldPerc = yieldPerc;
								mpsOrder.routeCode = adpElement.getRouteCode();
								mpsOrder.bomCode = adpElement.getBomCode();
								// ld_worder.setitem(ll_row, "proj_code",
								// ls_proj_code)
								mpsOrder.chgDate = chgDate;
								mpsOrder.chgUser = userId;
								mpsOrder.chgTerm = userId;
								mpsOrder.unit = unit;
								mpsOrder.acctCodeWp = adpElement.getAcctCodeWp();
								mpsOrder.cctrCodeWp = adpElement.getCctrCodeWp();
								mpsOrder.curBatchQty = batchQty;
								// ld_worder.setitem(ll_row, "std_qty",
								// lc_create_qty) // 04-07-03
								// ld_worder.setitem(ll_row, "demand_qty",
								// lc_actualdemand)
								// 01/04/11 manoharan
								//cpatil-25/08/14-System.out.println("01/04/11 setting SO in MPS 0 [" + adpElement.getSaleOrder() + "]");
								mpsOrder.saleOrder = adpElement.getSaleOrder();
								mpsOrder.lineNo = adpElement.getLineNo();
								mpsOrder.mfgType = adpElement.getMfgType();
								// end 01/04/11 manoharan

								mpsList.add(mpsOrder);
								System.out.println("@@@@2103151:mpsOrder.quantity["+mpsOrder.quantity+"]mpsList["+mpsList.size()+"]");
							}
							// below block added as per Manoharan Sir - jiten
							// 03/11/06 - For remaining reqQty
							// reqQty = reqQty - (batchQty * multiplier);
							// if(reqQty > 0){
							if (balQty > 0)
							{
								MPSOrder mpsOrder = new MPSOrder();

								mpsOrder.ordType = adpElement.getMfgType();
								mpsOrder.itemCode = itemCode;
								mpsOrder.siteCode = siteCode;
								mpsOrder.quantity = balQty;
								mpsOrder.ordDate = curDate;
								mpsOrder.planDueDate = dueDate;
								mpsOrder.dueDate = dueDate;
								mpsOrder.status = "P";
								mpsOrder.statusDate = curDate;
								mpsOrder.yieldPerc = yieldPerc;
								mpsOrder.routeCode = adpElement.getRouteCode();
								mpsOrder.bomCode = adpElement.getBomCode();
								mpsOrder.chgDate = chgDate;
								mpsOrder.chgUser = userId;
								mpsOrder.chgTerm = userId;
								mpsOrder.unit = unit;
								mpsOrder.acctCodeWp = adpElement.getAcctCodeWp();
								mpsOrder.cctrCodeWp = adpElement.getCctrCodeWp();
								mpsOrder.curBatchQty = balQty;
								// 01/04/11 manoharan
								//cpatil-25/08/14-System.out.println("01/04/11 setting SO in MPS 1 [" + adpElement.getSaleOrder() + "]");
								mpsOrder.saleOrder = adpElement.getSaleOrder();
								mpsOrder.lineNo = adpElement.getLineNo();
								mpsOrder.mfgType = adpElement.getMfgType();
								// end 01/04/11 manoharan

								// start
								String tempSORef="";
								System.out.println(" for addnOrder code itemCode["+itemCode+"] parentItemMap 3 ["+parentItemMap+"]");
								if(  parentItemMap.containsKey(itemCode) )
								{
									String tempParentItem =  parentItemMap.get(itemCode).toString(); 
									System.out.println("@@@@@@@tempParentItem1["+tempParentItem+"]");
									if( tempParentItem != null && tempParentItem.trim().length() > 0 )
									{
										do
										{
											System.out.println("@@@@@@@tempParentItem2["+tempParentItem+"]");
											if( tempParentItem != null && tempParentItem.trim().length() > 0 )
											{
												if( soItemListMap.size() > 0 )
												{	
													if( soItemListMap.containsKey(tempParentItem))
													{
														tempSORef =  soItemListMap.get(tempParentItem).toString();
														mpsOrder.addnOrder=tempSORef;
														break;
													}else
													{
														String tempValue = tempParentItem;
														tempParentItem =  parentItemMap.get(tempParentItem)== null?"":parentItemMap.get(tempParentItem).toString();
														System.out.println("@@@@@tempParentItem["+tempParentItem+"]tempValue["+tempValue+"]");
														if(tempValue.equalsIgnoreCase(tempParentItem) )
														{
															break;
														}
													}
												}
												else
												{
													break;
												}
											}
										}
										while (  parentItemMap.containsKey(tempParentItem)  );
									}
								}
								else
								{
									mpsOrder.addnOrder=  soItemListMap.get(itemCode).toString();
								}
								System.out.println("@@@@@@@@@itemCode 3 ["+itemCode+"] tempSORef["+tempSORef+"]");

								// end
								mpsList.add(mpsOrder);
								System.out.println("@@@@210315:mpsOrder.quantity["+mpsOrder.quantity+"]mpsList["+mpsList.size()+"]");
							}
							// Jiten - End 03/11/06
						} else if (orderOpt.equals("C"))
						{
							System.out.println("@@@@210315 adpElement.getMfgType()["+adpElement.getMfgType()+"]");
							int findEle = -1;
							MPSOrder mpsOrder = null;
							if (!"O".equals(adpElement.getMfgType())) // 01/04/11
								// manoharan
								// in case
								// made to
								// order
								// not to
								// club
							{
								System.out.println("@@@@210315 mpsList.size()["+mpsList.size()+"]");
								if (mpsList.size() > 0)
								{
									// check for the last ones existence if
									// found add the demand to that
									for (int listCtr = mpsList.size() - 1; listCtr >= 0; listCtr--)
									{
										mpsOrder = (MPSOrder) mpsList.get(listCtr);
										System.out.println("dueDate["+dueDate+"]");
										System.out.println("horizonDate["+horizonDate+"]");
										System.out.println("dueDate.compareTo(horizonDate)["+dueDate.compareTo(horizonDate)+"]");
										System.out.println("mpsOrder.itemCode.trim()["+mpsOrder.itemCode.trim()+"]itemCode.trim()["+itemCode.trim()+"]");
										System.out.println("mpsOrder.siteCode.trim()["+mpsOrder.siteCode.trim()+"]siteCode.trim()["+siteCode.trim()+"]");
										if (mpsOrder.itemCode.trim().equalsIgnoreCase(itemCode.trim()) && mpsOrder.siteCode.trim().equalsIgnoreCase(siteCode.trim()) && (dueDate.compareTo(horizonDate) <= 0))
										{
											findEle = listCtr;
											System.out.println("@@@@@findEle1["+findEle+"]");
											break;
										}
									}
								}
							}
							System.out.println("@@@@@findEle2["+findEle+"]");
							if (findEle >= 0)
							{
								mpsOrder.quantity += reqQty;
								mpsOrder.curBatchQty += reqQty;
								mpsList.set(findEle, mpsOrder);
							} else
							{
								mpsOrder = new MPSOrder();

								mpsOrder.ordType = adpElement.getMfgType();
								mpsOrder.itemCode = itemCode;
								mpsOrder.siteCode = siteCode;
								mpsOrder.quantity = reqQty;
								mpsOrder.ordDate = curDate;
								mpsOrder.planDueDate = dueDate;
								mpsOrder.dueDate = dueDate;
								mpsOrder.status = "P";
								mpsOrder.statusDate = curDate;
								mpsOrder.yieldPerc = yieldPerc;
								mpsOrder.routeCode = adpElement.getRouteCode();
								mpsOrder.bomCode = adpElement.getBomCode();
								mpsOrder.chgDate = chgDate;
								mpsOrder.chgUser = userId;
								mpsOrder.chgTerm = userId;
								mpsOrder.unit = unit;
								mpsOrder.acctCodeWp = adpElement.getAcctCodeWp();
								mpsOrder.cctrCodeWp = adpElement.getCctrCodeWp();
								mpsOrder.curBatchQty = reqQty;
								// 01/04/11 manoharan
								//cpatil-25/08/14-System.out.println("01/04/11 setting SO in MPS 2 [" + adpElement.getSaleOrder() + "]");
								mpsOrder.saleOrder = adpElement.getSaleOrder();
								mpsOrder.lineNo = adpElement.getLineNo();
								mpsOrder.mfgType = adpElement.getMfgType();
								// end 01/04/11 manoharan

								System.out.println(" for addnOrder code");
								/*ArrayList<String> addnOrderList =  adpElement.getOrderList();
								String refSaleOrder="";
								for( int ordCnt=0; ordCnt < addnOrderList.size(); ordCnt++ )
								{
									String temp = addnOrderList.get(ordCnt);
									String[]  addnOrderArray =   temp.split("@");

									if( addnOrderArray.length ==3 )
									{
										refSaleOrder =  refSaleOrder + addnOrderArray[0] + ",";
									}
								}
								System.out.println("@@@@@ refSaleOrder["+refSaleOrder+"]  for addnOrder code end");
								mpsOrder.addnOrder=refSaleOrder;

								if(  refSaleOrder == null || refSaleOrder.trim().length()==0 )
								{
								refSaleOrder="";
								if( locGroupList != null )
								{
									System.out.println("@@@@@ locGroupList["+locGroupList+"]");
									String locGroupLst[]=locGroupList.split(",");
									System.out.println("@@@@@ locGroupLst.length["+locGroupLst.length+"]");
									for(int i=0;i<locGroupLst.length;i++)
									{
										String SOrder="";
										String tempLocGroup=locGroupLst[i];
										System.out.println("@@@@@ tempLocGroup["+tempLocGroup+"]");
										String tempLocGroupArr[]=tempLocGroup.split("@");
										if( tempLocGroupArr.length > 0 )
										{
											SOrder=tempLocGroupArr[0];
											refSaleOrder =  refSaleOrder + SOrder + ",";
										}

										System.out.println("@@@@@7793 refSaleOrder["+refSaleOrder+"]");


									}
									System.out.println("@@@@@final refSaleOrder["+refSaleOrder+"]");
									mpsOrder.addnOrder=refSaleOrder;
								}
								}
								 */

								String tempSORef="";
								System.out.println(" for addnOrder code itemCode["+itemCode+"] parentItemMap 2 ["+parentItemMap+"]");
								if(  parentItemMap.containsKey(itemCode) )
								{
									String tempParentItem =  parentItemMap.get(itemCode).toString(); 
									System.out.println("@@@@@@@tempParentItem1["+tempParentItem+"]");
									if( tempParentItem != null && tempParentItem.trim().length() > 0 )
									{
										do
										{
											System.out.println("@@@@@@@tempParentItem2["+tempParentItem+"]");
											if( tempParentItem != null && tempParentItem.trim().length() > 0 )
											{
												if( soItemListMap.size() > 0 )
												{	
													if( soItemListMap.containsKey(tempParentItem))
													{
														tempSORef =  soItemListMap.get(tempParentItem).toString();
														mpsOrder.addnOrder=tempSORef;
														break;
													}else
													{
														String tempValue = tempParentItem;
														tempParentItem =  parentItemMap.get(tempParentItem)== null?"":parentItemMap.get(tempParentItem).toString();
														System.out.println("@@@@@tempParentItem["+tempParentItem+"]tempValue["+tempValue+"]");
														if(tempValue.equalsIgnoreCase(tempParentItem) )
														{
															break;
														}
													}
												}
												else
												{
													break;
												}
											}
										}
										while (  parentItemMap.containsKey(tempParentItem)  );
									}
								}
								else
								{
									if( soItemListMap.containsKey(itemCode) )
									{
										mpsOrder.addnOrder= soItemListMap.get(itemCode) == null ?"": soItemListMap.get(itemCode).toString();
									}
								}
								System.out.println("@@@@@@@@@itemCode 2 ["+itemCode+"] tempSORef["+tempSORef+"]");

								mpsList.add(mpsOrder);

								System.out.println("@@@@2103153:mpsOrder.quantity["+mpsOrder.quantity+"]mpsList["+mpsList.size()+"]");
							}
						}

					} // ( suppSour.equals("M") && mfgPlan.equals("Y"))
					else if (suppSour.equals("D") && disPlan.equals("Y"))
					{

						siteCodeSupp = " ";
						if (balIntersite.equals("Y"))
						{
							String siteIdst = null;
							siteIdst = getSurplusStockSite(siteCode, itemCode, reqQty, surplusListOriginal);
							// =
							// wf_get_idst_site(ld_dist_intersite,ld_surplus_ext,ls_site_code,ls_item_code,lc_reo_qty)
							if (siteIdst != null && siteIdst.trim().length() > 0)
							{
								siteCodeSupp = siteIdst;
							}
						}
						//
						if (siteCodeSupp == null || siteCodeSupp.trim().length() == 0)
						{
							siteCodeSupp = adpElement.getSiteCodeSupp();
						}

						DistDemand distDemand = new DistDemand();

						distDemand.tranDate = curDate;
						distDemand.itemCode = itemCode;
						distDemand.siteCode = siteCode;
						distDemand.siteCodeSrc = siteCodeSupp;
						distDemand.planDueDate = dueDate;
						distDemand.dueDate = dueDate;
						distDemand.qtyRequired = reqQty;
						distDemand.unit = unit;
						distDemand.status = "P";
						distDemand.dueDateOrd = dueDate;
						distDemand.chgDate = chgDate;
						distDemand.chgUser = userId;
						distDemand.chgTerm = userId;

						disList.add(distDemand);
						/*
						 * if (siteCodeSupp != null &&
						 * siteCodeSupp.trim().length() > 0 ) { // independent
						 * demand to be created if (orderOpt.equals("B")) { if
						 * (reqQty > batchQty) { if (reqQty % batchQty > 0) {
						 * //multiplier = ((int)Math.floor(reqQty / batchQty)) +
						 * 1; multiplier = new Double(Math.floor(reqQty /
						 * batchQty)).intValue() + 1; } else { // multiplier =
						 * (int)Math.floor(reqQty / batchQty); multiplier = new
						 * Double(Math.floor(reqQty / batchQty)).intValue(); } }
						 * else { multiplier = 1; }
						 * 
						 * createQty = batchQty; for (int planCtr = 0; planCtr <
						 * multiplier; planCtr++) { IndependentDemand indDem =
						 * new IndependentDemand(); indDem.tranDate = curDate;
						 * indDem.siteCode = siteCodeSupp; indDem.itemCode =
						 * itemCode; indDem.planDueDate = dueDate;
						 * indDem.dueDate = dueDate; indDem.quantity =
						 * createQty; indDem.quantityStdUom = createQty;
						 * indDem.convQtyStdUom = 1; indDem.unit = unit;
						 * indDem.unitStd = unit; indDem.status = "O";
						 * indDem.siteCodeCust = siteCode;
						 * 
						 * indDemList.add(indDem); } } else if (
						 * orderOpt.equals("C") ) { int findEle = -1;
						 * IndependentDemand indDem = null; if (
						 * indDemList.size() > 0) { // check for the last ones
						 * existence if found add the demand to that for ( int
						 * listCtr = indDemList.size() -1; listCtr > 0;
						 * listCtr-- ) { indDem =
						 * (IndependentDemand)indDemList.get(listCtr); if
						 * (indDem.itemCode.trim() == itemCode.trim() &&
						 * indDem.siteCode.trim() == siteCodeSupp.trim() &&
						 * indDem.siteCodeCust.trim() == siteCode.trim() &&
						 * (dueDate.compareTo(horizonDate) <= 0)) { findEle =
						 * listCtr; break; } } } if (findEle >= 0) {
						 * indDem.quantity += reqQty; indDem.quantityStdUom +=
						 * reqQty; indDemList.set(findEle, indDem); } else {
						 * IndependentDemand newIndDem = new
						 * IndependentDemand(); newIndDem.tranDate = curDate;
						 * newIndDem.siteCode = siteCodeSupp; newIndDem.itemCode
						 * = itemCode; newIndDem.planDueDate = dueDate;
						 * newIndDem.dueDate = dueDate; newIndDem.quantity =
						 * reqQty; newIndDem.quantityStdUom = reqQty;
						 * newIndDem.convQtyStdUom = 1; newIndDem.unit = unit;
						 * newIndDem.unitStd = unit; newIndDem.status = "O";
						 * newIndDem.siteCodeCust = siteCode;
						 * 
						 * indDemList.add(newIndDem); } }
						 * 
						 * }
						 */
					} // ( suppSour.equals("D") && disPlan.equals("Y"))

				} // reqQty > 0
			} // end for
		} // End of try
		catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB : CreatePlanDemand(ADPElement adpElement) : " + e.getMessage());
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			if (pstmtMpsOrder != null)
			{
				pstmtMpsOrder = null;
			}
			if (pstmtIndent != null)
			{
				pstmtIndent = null;
			}
			if (pstmtDistDemand != null)
			{
				pstmtDistDemand = null;
			}
			// System.out.println("Size of Indent List : [" + indList.size() +
			// "]");
			// System.out.println("Size of IndDem List : [" + indDemList.size()
			// + "]");
			// System.out.println("Size of Mps    List : [" + mpsList.size() +
			// "]");
			// System.out.println("Size of Dis    List : [" + disList.size() +
			// "]");

		}
		return errString;// Moved here from finally as it does not complete
		// normally - jiten - 03/11/06

	}

	private String InsertPlanDemand() throws Exception
	{
		String errString = "";
		// System.out.println("In Insert Plan Demand()");

		//cpatil-25/08/14-System.out.println("Ind Dem List Size out :" + indDemList.size());
		if (indDemList.size() > 0)
		{
			//cpatil-25/08/14-System.out.println("Ind Dem List Size :" + indDemList.size());
			errString = InsertPlanDemand("W_INDEPENDENT_DEMAND", indDemList);
			if (errString != null && errString.trim().length() > 0)
			{
				System.out.println("Error While Inserting independent Demand" + errString);
				return errString;
			}
		}
		if (indList.size() > 0 && genIndent.equalsIgnoreCase("Y"))
		{
			// System.out.println("Ind List Size :" + mpsList.size());
			errString = InsertPlanDemand("W_INDENT", indList);
			if (errString != null && errString.trim().length() > 0)
			{
				System.out.println("Error While Inserting independent Demand" + errString);
				return errString;
			}
		}
		if (mpsList.size() > 0)
		{
			errString = InsertPlanDemand("W_MPS_ORDER", mpsList);
			if (errString != null && errString.trim().length() > 0)
			{
				System.out.println("Error While Inserting mps order" + errString);
				return errString;
			}
		}
		if (disList.size() > 0)
		{
			// System.out.println("Dis List Size :" + mpsList.size());
			errString = InsertPlanDemand("W_DIST_DEMAND", disList);
			if (errString != null && errString.trim().length() > 0)
			{
				System.out.println("Error While Inserting Dist. Demand" + errString);
				return errString;
			}
		}
		return "";
	}

	private String getStkOpt(String itemCode, String siteCode) throws Exception
	{
		PreparedStatement pstmt = null;
		String sql = "";
		ResultSet rs = null;
		String stkOpt = "";
		try
		{

			sql = "SELECT STK_OPT FROM SITEITEM WHERE SITE_CODE = ? AND ITEM_CODE = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, siteCode);
			pstmt.setString(2, itemCode);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				stkOpt = rs.getString(1);
			} else
			{
				rs.close();
				pstmt.close();
				sql = "SELECT STK_OPT FROM ITEM WHERE ITEM_CODE = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, itemCode);
				rs = pstmt.executeQuery();
				if (rs.next())
				{
					stkOpt = rs.getString(1);
				}
			}
			rs.close();
			pstmt.close();
		} catch (SQLException e)
		{
			System.out.println("SQLException :RunMRPPrcEJB :getBomCode(String siteCode, String ItemCode).." + e.getMessage());
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		}

		catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :getBomCode(String siteCode, String ItemCode).." + e.getMessage());
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			if (pstmt != null)
			{
				pstmt = null;
			}
			if (rs != null)
			{
				rs = null;
			}
			// return stkOpt;
		}
		return stkOpt; // Moved here from finally block - jiten -03/11/06
	}

	private String decFormat(double num)
	{
		NumberFormat nf = new DecimalFormat("##############0.000");
		nf.setMaximumFractionDigits(3);
		// nf.setMaximumIntegerDigits(10);
		return nf.format(num);
	}

	private String InsertPlanDemand(String winName, java.util.ArrayList list) throws ITMException, Exception
	{
		PreparedStatement pstmtMpsOrder = null;
		PreparedStatement pstmtIndent = null;
		PreparedStatement pstmtDistDemand = null;
		PreparedStatement pstmtIndDemand = null;
		PreparedStatement pstmtKeyStr = null;
		PreparedStatement pstmtWorkOrder = null;
		ResultSet rs = null;

		String xmlValues = "";
		String keyStringQuery = null;

		String tranId = "";
		String ordType = "";
		String itemCode = "";
		String itemSer = "";
		String siteCode = "";
		String mrpRunId = "";
		String addnOrder = "";
		String routeCode = "";
		String bomCode = "";
		String projCode = "";
		String unit = "";
		String acctCodeWp = "";
		String cctrCodeWp = "";
		String indNo = "";
		final String indType = "M";
		String itemDescr = "";
		String unitInd = "";
		String unitStd = "";
		String siteCodeDlv = "";
		String siteCodeAcct = "";
		String siteCodeCust = "";
		String aprCode = "";
		final String priority = "R";
		String acctCode = "";
		String cctrCode = "";
		String empCodePur = "";
		String empCodeReq = "";
		String suppCodePref = "";
		String packCode = "";
		String siteCodeSrc = "";
		final String status = "P";

		double quantity = 0;
		double yieldPerc = 0;
		double purLeadTime = 0;
		double ordQuantity = 0;
		double purcRate = 0;
		double qtyRequired = 0;
		double quantityStdUom = 0;
		double convQtyStdUom = 1;

		String ordDateStr = "";
		String planDueDateStr = "";
		String dueDateStr = "";
		String statusDateStr = "";
		String chgDateStr = "";
		String indDateStr = "";
		String reqDateStr = "";
		String tranDateStr = "";
		String dueDateOrdStr = "";

		java.sql.Timestamp ordDate = null;
		java.sql.Timestamp planDueDate = null;
		java.sql.Timestamp dueDate = null;
		java.sql.Timestamp statusDate = null;
		java.sql.Timestamp chgDate = null;
		java.sql.Timestamp indDate = null;
		java.sql.Timestamp reqDate = null;
		java.sql.Timestamp tranDate = null;
		java.sql.Timestamp dueDateOrd = null;

		MPSOrder mpsOrder = null;
		Indent indent = null;
		DistDemand distDemand = null;
		IndependentDemand independentDemand = null;

		String mpsKeyStr = null;
		String indKeyStr = null;
		String indDemKeyStr = null;
		String disDemKeyStr = null;

		String tranIdIndDemand = null;
		String tranIdDistDemand = null;
		String tranIdIndent = null;
		String tranIdMpsOrder = null;
		// variables added by sabyasachi 30-03-11
		String saleOrder = "";
		String lineNo = "";
		String woKeyStr = null;
		String workOrder = null;
		PreparedStatement pstmtworkOrder = null;
		String sqlWorkOrder = null;
		// variables added by sabyasachi ends 30-03-11
		DistCommon dcommon=new DistCommon();
		String lotSL="",WOtranId="";
		ArrayList<Double> noArtList = new ArrayList<Double>();
		ArrayList<Double> netWeightList = new ArrayList<Double>();
		double noArt=0,netWeight=0;


		try
		{
			System.out.println("@@@@@@@@@cpatil:InsertPlanDemand called----winName["+winName+"] list["+list+"]--------");

			/*
			 * keyStringQuery =
			 * "SELECT KEY_STRING FROM TRANSETUP WHERE TRAN_WINDOW = ? ";
			 * pstmtKeyStr = conn.prepareStatement(keyStringQuery);
			 * pstmtKeyStr.setString(1,"w_mps_order"); rs =
			 * pstmtKeyStr.executeQuery(); if(rs.next()) { mpsKeyStr =
			 * rs.getString("KEY_STRING"); rs.close(); }
			 */
			lotSL=dcommon.getDisparams("999999","MFG_LOT_SL",conn);
			keyStringQuery = "SELECT KEY_STRING FROM TRANSETUP WHERE TRAN_WINDOW = 'w_mps_order' ";
			pstmtKeyStr = conn.prepareStatement(keyStringQuery);
			rs = pstmtKeyStr.executeQuery();
			if (rs.next())
			{
				mpsKeyStr = rs.getString("KEY_STRING");
				rs.close();
			}
			pstmtKeyStr.close(); // temporary
			// pstmtKeyStr.clearParameters();
			keyStringQuery = "SELECT KEY_STRING FROM TRANSETUP WHERE TRAN_WINDOW = ? ";
			pstmtKeyStr = conn.prepareStatement(keyStringQuery);
			pstmtKeyStr.setString(1, "w_indent");
			rs = pstmtKeyStr.executeQuery();
			if (rs.next())
			{
				indKeyStr = rs.getString("KEY_STRING");
				rs.close();
			}
			pstmtKeyStr.clearParameters();
			pstmtKeyStr.setString(1, "w_independent_demand");
			rs = pstmtKeyStr.executeQuery();
			if (rs.next())
			{
				indDemKeyStr = rs.getString("KEY_STRING");
				rs.close();
			}
			pstmtKeyStr.clearParameters();
			pstmtKeyStr.setString(1, "w_dist_demand");
			rs = pstmtKeyStr.executeQuery();
			if (rs.next())
			{
				disDemKeyStr = rs.getString("KEY_STRING");
				rs.close();
			}
			pstmtKeyStr.clearParameters();
			pstmtKeyStr.setString(1, "w_worder");
			rs = pstmtKeyStr.executeQuery();
			if (rs.next())
			{
				woKeyStr = rs.getString("KEY_STRING");
			}
			rs.close();
			rs = null;
			pstmtKeyStr.close();
			pstmtKeyStr = null;

			// 24/07/08 manoharan
			// SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());

			sqlWorkOrder = "INSERT INTO WORKORDER(TRAN_ID,ORDER_TYPE,ITEM_CODE,SITE_CODE, " + "QUANTITY,ORD_DATE,PLAN_DUE_DATE,MRP_RUN_ID, " + "ADDN_ORDER,DUE_DATE,STATUS,STATUS_DATE,YIELD_PERC,ROUTE_CODE, " + "BOM_CODE,PROJ_CODE,CHG_DATE,CHG_USER,CHG_TERM,UNIT, " + "ACCT_CODE__WP,CCTR_CODE__WP,CURRENT_BATCH_QTY,UNIT__STD," + " STD_QTY,CONV__QTY_STDUOM,SALE_ORDER,LINE_NO,WORK_ORDER,LOT_SL,NO_ART,NET_WEIGHT,LOC_GROUP ) " + "VALUES ( ?, ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? ," + " ? , ? , ? ,?, ?, ?, ?, ?, ?, ?, ?, ?)";

			//pstmtWorkOrder = conn.prepareStatement(sqlWorkOrder);

			String sqlMpsOrder = "INSERT INTO MPS_ORDER(TRAN_ID,ORDER_TYPE,ITEM_CODE,SITE_CODE, " + "QUANTITY,ORD_DATE,PLAN_DUE_DATE,MRP_RUN_ID, " + "ADDN_ORDER,DUE_DATE,STATUS,STATUS_DATE,YIELD_PERC,ROUTE_CODE, " + "BOM_CODE,PROJ_CODE,CHG_DATE,CHG_USER,CHG_TERM,UNIT, " + "ACCT_CODE__WP,CCTR_CODE__WP,CURRENT_BATCH_QTY,UNIT__STD,STD_QTY,CONV__QTY_STDUOM,SALE_ORDER,LINE_NO) " + "VALUES ( ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? ," + " ? , ? , ? ,?, ?, ?,?,?)";

			pstmtMpsOrder = conn.prepareStatement(sqlMpsOrder);

			String sqlIndent = "INSERT INTO INDENT(IND_NO,IND_DATE,IND_TYPE,DEPT_CODE, " + "PLAN_DUE_DATE,REQ_DATE,ITEM_CODE,ITEM_DESCR, " + "QUANTITY,QUANTITY__STDUOM,ORD_QTY,UNIT__IND,UNIT__STD,SITE_CODE, " + "SITE_CODE__DLV,SITE_CODE__ACCT,APR_CODE,PRIORITY,ACCT_CODE, " + "CCTR_CODE,EMP_CODE__PUR,EMP_CODE__REQ,SUPP_CODE__PREF,PURC_RATE," + "PACK_CODE,STATUS,CHG_DATE,CHG_USER,CHG_TERM,PUR_LEAD_TIME,CONV__QTY_STDUOM,SITE_CODE__DES,SITE_CODE__BIL) " + "VALUES ( ? , ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? , ? ," + " ?,?,? )";
			pstmtIndent = conn.prepareStatement(sqlIndent);

			String sqlDistDemand = "INSERT INTO DIST_DEMAND(TRAN_ID,TRAN_DATE,SITE_CODE,ITEM_CODE, " + "PLAN_DUE_DATE,DUE_DATE,QTY_REQUIRED,UNIT,SITE_CODE__SOURCE, " + "STATUS,DUE_DATE__ORD,CHG_DATE,CHG_USER,CHG_TERM) " + "VALUES ( ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? , " + " ? , ? , ? , ? )";
			pstmtDistDemand = conn.prepareStatement(sqlDistDemand);

			String sqlIndDemand = "INSERT INTO INDEPENDENT_DEMAND(TRAN_ID, TRAN_DATE, SITE_CODE, ITEM_CODE, " + "QUANTITY, UNIT, CONV__QTY_STDUOM, QUANTITY__STD_UOM, UNIT__STD, DUE_DATE, " + "STATUS, SITE_CODE__CUST, CHG_DATE, CHG_USER, CHG_TERM, PLAN_DUE_DATE ) " + "VALUES( ? , ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? , ? ," + " ? , ? , ? , ? ) ";
			pstmtIndDemand = conn.prepareStatement(sqlIndDemand);

			// String tranDate = this.genericUtility.getValidDateString(new
			// java.util.Date().toString(),
			// this.genericUtility.getDBDateFormat(),this.genericUtility.getApplDateFormat());
			System.out.println("@@@@@@@@ 8117 winName["+winName+"]");
			if (winName.equalsIgnoreCase("W_MPS_ORDER"))
			{
				// System.out.println("W_MPS_ORDER");
				for (int count = 0; count < list.size(); count++)
				{

					mpsOrder = (MPSOrder) list.get(count);

					ordType = mpsOrder.ordType;
					// 30/06/10 manoharan
					if (ordType == null || ordType.trim().length() == 0)
					{
						ordType = "O";
					}
					itemCode = mpsOrder.itemCode;
					siteCode = mpsOrder.siteCode;
					quantity = mpsOrder.quantity;
					ordDate = mpsOrder.ordDate;
					ordDateStr = sdf.format(mpsOrder.ordDate);
					planDueDateStr = sdf.format(mpsOrder.planDueDate);
					planDueDate = mpsOrder.planDueDate;
					mrpRunId = mpsOrder.mrpRunId;
					addnOrder = mpsOrder.addnOrder;
					dueDate = mpsOrder.dueDate;
					dueDateStr = sdf.format(mpsOrder.dueDate);
					statusDate = mpsOrder.statusDate;
					statusDateStr = sdf.format(mpsOrder.statusDate);
					yieldPerc = mpsOrder.yieldPerc;
					routeCode = mpsOrder.routeCode;
					bomCode = mpsOrder.bomCode;
					projCode = mpsOrder.projCode;
					chgDate = mpsOrder.chgDate;
					chgDateStr = sdf.format(mpsOrder.chgDate);
					unit = mpsOrder.unit;
					acctCodeWp = mpsOrder.acctCodeWp;
					cctrCodeWp = mpsOrder.cctrCodeWp;
					// added by sabyasachi 30-03-11
					saleOrder = mpsOrder.saleOrder;
					lineNo = mpsOrder.lineNo;

					if( "".equalsIgnoreCase(projCode) || ( projCode != null &&  projCode.trim().length() == 0 ))  //FK_WORKORDER_PROJ added for exception
					{
						projCode = null;
					}

					//cpatil-25/08/14-System.out.println("@@@@@@@@@@@projCode["+projCode+"]");
					// added by sabyasachi ends 30-03-11
					// 20/01/09 manoharan
					// xmlValues
					// ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
					xmlValues = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><Root>";
					xmlValues = xmlValues + "<Header></Header>";
					xmlValues = xmlValues + "<Detail1>";
					xmlValues = xmlValues + "<tran_id><![CDATA[]]></tran_id>";
					xmlValues = xmlValues + "<work_order><![CDATA[]]></work_order>";
					xmlValues = xmlValues + "<order_type><![CDATA[" + ordType + "]]></order_type>";
					xmlValues = xmlValues + "<item_code><![CDATA[" + itemCode + "]]></item_code>";
					xmlValues = xmlValues + "<site_code><![CDATA[" + siteCode + "]]></site_code>";
					xmlValues = xmlValues + "<quantity><![CDATA[" + quantity + "]]></quantity>";
					xmlValues = xmlValues + "<ord_date><![CDATA[" + ordDateStr + "]]></ord_date>";
					xmlValues = xmlValues + "<plan_due_date><![CDATA[" + planDueDateStr + "]]></plan_due_date>";
					xmlValues = xmlValues + "<mrp_run_id><![CDATA[" + mrpRunId + "]]></mrp_run_id>";
					xmlValues = xmlValues + "<addn_order><![CDATA[" + addnOrder + "]]></addn_order>";
					xmlValues = xmlValues + "<due_date><![CDATA[" + dueDateStr + "]]></due_date>";
					xmlValues = xmlValues + "<status><![CDATA[" + status + "]]></status>";
					xmlValues = xmlValues + "<status_date><![CDATA[" + statusDateStr + "]]></status_date>";
					xmlValues = xmlValues + "<yield_perc><![CDATA[" + yieldPerc + "]]></yield_perc>";
					xmlValues = xmlValues + "<route_code><![CDATA[" + routeCode + "]]></route_code>";
					xmlValues = xmlValues + "<bom_code><![CDATA[" + bomCode + "]]></bom_code>";
					xmlValues = xmlValues + "<proj_code><![CDATA[" + projCode + "]]></proj_code>";
					xmlValues = xmlValues + "<chg_date><![CDATA[" + chgDateStr + "]]></chg_date>";
					xmlValues = xmlValues + "<chg_user><![CDATA[" + chgUser + "]]></chg_user>";
					xmlValues = xmlValues + "<chg_term><![CDATA[" + chgTerm + "]]></chg_term>";
					xmlValues = xmlValues + "<unit><![CDATA[" + unit + "]]></unit>";
					xmlValues = xmlValues + "<acct_code__wp><![CDATA[" + acctCodeWp + "]]></acct_code__wp>";
					xmlValues = xmlValues + "<cctr_code__wp><![CDATA[" + cctrCodeWp + "]]></cctr_code__wp>";
					xmlValues = xmlValues + "<current_batch_qty><![CDATA[" + quantity + "]]></current_batch_qty>";
					xmlValues = xmlValues + "</Detail1></Root>";
					System.out.println("@@@@@@@@@@@@@@@@@ 8196 winName["+winName+"]mfgType["+mpsOrder.mfgType+"]yieldPerc["+yieldPerc+"]");
					if ("O".equals(mpsOrder.mfgType))
					{
						pstmtWorkOrder = conn.prepareStatement(sqlWorkOrder);
						
						noArt = 0 ;
						netWeight = 0 ;

						System.out.println("for workorder...itemCode["+itemCode+"]addnOrder["+addnOrder+"]");
						System.out.println("for workorder...["+workOrder+"]bomCode["+bomCode+"]ordType["+ordType+"]");
						workOrder = getUniqueKey(xmlValues, mpsKeyStr, "work_order", "W-ORD");
						pstmtWorkOrder.setString(1, workOrder);
						pstmtWorkOrder.setString(2, ordType);   // commented for inserting order type as M ... on 17/06/14
						//pstmtWorkOrder.setString(2, "M");    // again revert changes on 17/06/14
						pstmtWorkOrder.setString(3, itemCode);
						pstmtWorkOrder.setString(4, siteCode);
						pstmtWorkOrder.setDouble(5, quantity);
						pstmtWorkOrder.setTimestamp(6, ordDate);
						pstmtWorkOrder.setTimestamp(7, planDueDate);
						pstmtWorkOrder.setString(8, mrpRunId);
						pstmtWorkOrder.setString(9, addnOrder);
						pstmtWorkOrder.setTimestamp(10, dueDate);
						pstmtWorkOrder.setString(11, "M");  // set M instead of P 17/06/14 
						pstmtWorkOrder.setTimestamp(12, statusDate);
						pstmtWorkOrder.setDouble(13, yieldPerc);
						pstmtWorkOrder.setString(14, routeCode);
						pstmtWorkOrder.setString(15, bomCode);
						pstmtWorkOrder.setString(16, projCode);
						pstmtWorkOrder.setTimestamp(17, chgDate);
						pstmtWorkOrder.setString(18, chgUser);
						pstmtWorkOrder.setString(19, chgTerm);
						pstmtWorkOrder.setString(20, unit);
						pstmtWorkOrder.setString(21, acctCodeWp);
						pstmtWorkOrder.setString(22, cctrCodeWp);
						pstmtWorkOrder.setDouble(23, quantity);
						pstmtWorkOrder.setString(24, unit);
						pstmtWorkOrder.setDouble(25, quantity);
						pstmtWorkOrder.setDouble(26, 1);
						if (saleOrder != null && saleOrder.trim().length() > 0)
						{
							pstmtWorkOrder.setString(27, saleOrder);
						} else
						{
							pstmtWorkOrder.setNull(27, java.sql.Types.CHAR);
						}
						if (lineNo != null && lineNo.trim().length() > 0)
						{
							pstmtWorkOrder.setString(28, lineNo);
						} else
						{
							pstmtWorkOrder.setNull(28, java.sql.Types.CHAR);
						}
						pstmtWorkOrder.setString(29, workOrder);
						pstmtWorkOrder.setString(30,lotSL);

						// added by cpatil on 23/03/15 in urse  --- start
						noArtList = dcommon.getConvQuantityFact(unit, "NOS", itemCode, quantity, 0, conn);
						if( noArtList.size() == 2 )
						{
							System.out.println("@@@@@noArtList["+noArtList.toString()+"]");
							noArt =  Double.parseDouble(noArtList.get(1)+"");
						}
						netWeightList = dcommon.getConvQuantityFact(unit, "KGS", itemCode, quantity, 0, conn);
						if( netWeightList.size() == 2 )
						{
							System.out.println("@@@@@netWeightList["+netWeightList.toString()+"]");
							netWeight = Double.parseDouble( netWeightList.get(1)+"");
						}
						pstmtWorkOrder.setDouble(31, noArt);
						pstmtWorkOrder.setDouble(32, netWeight);

						if( isDetailReq )
						{
							System.out.println("@@@@@final---locGroupMap["+locGroupMap+"]]");
							String tempLocGroup="";

							Set s1=locGroupMap.entrySet(); 
							Iterator itr=s1.iterator();
							while(itr.hasNext())
							{ 
								Map.Entry m=(Map.Entry)itr.next(); 
								{ 
									String keyListStr =  m.getKey().toString(); 
									tempLocGroup =    locGroupMap.get(keyListStr).toString();
									break;
								}
							}
							pstmtWorkOrder.setString(33,tempLocGroup);
						}
						else
						{
							pstmtWorkOrder.setString(33,"");
						}

						// end

					//	pstmtWorkOrder.addBatch();  //
						
						int rcnt =  pstmtWorkOrder.executeUpdate();
						 System.out.println("@@@ rcnt["+rcnt+"]");
						 pstmtWorkOrder.close();
						 pstmtWorkOrder = null;

						WOtranId = workOrder;
					} else
					{
						System.out.println("for MpsOrder...itemCode["+itemCode+"]addnOrder["+addnOrder+"]");
						tranIdMpsOrder = getUniqueKey(xmlValues, mpsKeyStr, "tran_id", "W-MPS");
						pstmtMpsOrder.setString(1, tranIdMpsOrder);
						pstmtMpsOrder.setString(2, ordType);
						pstmtMpsOrder.setString(3, itemCode);
						pstmtMpsOrder.setString(4, siteCode);
						pstmtMpsOrder.setDouble(5, quantity);
						pstmtMpsOrder.setTimestamp(6, ordDate);
						pstmtMpsOrder.setTimestamp(7, planDueDate);
						pstmtMpsOrder.setString(8, mrpRunId);
						pstmtMpsOrder.setString(9, addnOrder);
						pstmtMpsOrder.setTimestamp(10, dueDate);
						pstmtMpsOrder.setString(11, "M");//Manoj dtd 14/07/2014 Status Changed from P to M
						pstmtMpsOrder.setTimestamp(12, statusDate);
						pstmtMpsOrder.setDouble(13, yieldPerc);
						pstmtMpsOrder.setString(14, routeCode);
						pstmtMpsOrder.setString(15, bomCode);
						pstmtMpsOrder.setString(16, projCode);
						pstmtMpsOrder.setTimestamp(17, chgDate);
						pstmtMpsOrder.setString(18, chgUser);
						pstmtMpsOrder.setString(19, chgTerm);
						pstmtMpsOrder.setString(20, unit);
						pstmtMpsOrder.setString(21, acctCodeWp);
						pstmtMpsOrder.setString(22, cctrCodeWp);
						pstmtMpsOrder.setDouble(23, quantity);
						pstmtMpsOrder.setString(24, unit);
						pstmtMpsOrder.setDouble(25, quantity);
						pstmtMpsOrder.setDouble(26, 1);
						if (saleOrder != null && saleOrder.trim().length() > 0)
						{
							pstmtMpsOrder.setString(27, saleOrder);
						} else
						{
							pstmtMpsOrder.setNull(27, java.sql.Types.CHAR);
						}
						if (lineNo != null && lineNo.trim().length() > 0)
						{
							pstmtMpsOrder.setString(28, lineNo);
						} else
						{
							pstmtMpsOrder.setNull(28, java.sql.Types.CHAR);
						}

						// **************pstmtMpsOrder.setDouble(25, demandQty);
						pstmtMpsOrder.addBatch();

						WOtranId = tranIdMpsOrder;
					}

					// System.out.println("Inserting mpsorder # " + count +
					// " : " + tranIdMpsOrder);

					HashMap valueMap = new HashMap();

					valueMap.put("item_code", itemCode);
					valueMap.put("site_code", siteCode);
					valueMap.put("ord_type", ordType);
					valueMap.put("quantity", quantity);
					valueMap.put("tran_ser", "Work Order");
					valueMap.put("tran_id", WOtranId);
					valueMap.put("unit",unit);

					valueMap.put("due_date1",ordDateStr);

					IPD_MPS_ORDER.add(valueMap);
					//cpatil-25/08/14-System.out.println("IPD_MPS_ORDER valueMap["+valueMap+"]");
				}
				//cpatil-25/08/14-System.out.println("@@@@@cpatil:IPD_MPS_ORDER["+IPD_MPS_ORDER+"]");
			} 
			else if (winName.equalsIgnoreCase("W_INDENT"))
			{
				//cpatil-25/08/14-System.out.println("@@@@@cpatil_W_INDENT_list.size()["+list.size()+"]");
				for (int count = 0; count < list.size(); count++)
				{
					indent = (Indent) list.get(count);

					indDateStr = sdf.format(indent.indDate);
					indDate = indent.indDate;
					planDueDateStr = sdf.format(indent.planDueDate);
					planDueDate = indent.planDueDate;
					reqDate = indent.reqDate;
					reqDateStr = sdf.format(indent.reqDate);
					itemCode = indent.itemCode;
					itemDescr = indent.itemDescr;
					quantity = indent.quantity;
					quantityStdUom = indent.quantityStdUom;
					unitInd = indent.unitInd;
					unitStd = indent.unitStd;
					siteCode = indent.siteCode;
					siteCodeDlv = indent.siteCodeDlv;
					siteCodeAcct = indent.siteCodeAcct;
					aprCode = indent.aprCode;
					acctCode = indent.acctCode;
					cctrCode = indent.cctrCode;
					empCodePur = indent.empCodePur;
					empCodeReq = indent.empCodeReq;
					suppCodePref = indent.suppCodePref;
					purcRate = indent.purcRate;
					packCode = indent.packCode;
					chgDateStr = sdf.format(indent.chgDate);
					chgDate = indent.chgDate;
					purLeadTime = indent.purLeadTime;
					convQtyStdUom = indent.convQtyStdUom;
					itemSer= indent.itemSer;//Added by Manoj dtd 11/03/2014
					//cpatil-25/08/14-System.out.println("Item Series During Indent Generation---"+itemSer);

					// 20/01/09 manoharan
					// xmlValues
					// ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
					//Added by Manoj dtd 11/03/2014 to set Account Code
					FinCommon fcommon=new FinCommon();
					String stracctDet=fcommon.getAcctDetrTtype(itemCode,itemSer,"IN",indType,conn);
					//cpatil-25/08/14-System.out.println("stracctDet----"+stracctDet);
					String acctDetArray[]=stracctDet.split(",");
					//Condition Added by manoj dtd 25/06/2014 to handle accountcode
					if(acctDetArray.length>0)
					{
						if(acctDetArray.length==1)
						{
							acctCode=acctDetArray[0];
							cctrCode="";
						}
						else if(acctDetArray.length==2)
						{
							acctCode=acctDetArray[0];
							cctrCode=acctDetArray[1];
						}

					}
					else
					{
						acctCode="";
						cctrCode="";
					}
					//acctCode=acctDetArray[0];
					//cctrCode=acctDetArray[1];
					fcommon=null;
					//Ended by Manoj dtd 11/03/2014 to set Account Code
					xmlValues = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><Root>";
					xmlValues = xmlValues + "<Header></Header>";
					xmlValues = xmlValues + "<Detail1>";
					xmlValues = xmlValues + "<ind_no><![CDATA[]]></ind_no>";
					xmlValues = xmlValues + "<ind_date><![CDATA[" + indDateStr + "]]></ind_date>";
					xmlValues = xmlValues + "<ind_type><![CDATA[" + indType + "]]></ind_type>";
					xmlValues = xmlValues + "<dept_code><![CDATA[" + deptCodeMfg + "]]></dept_code>";
					xmlValues = xmlValues + "<plan_due_date><![CDATA[" + planDueDateStr + "]]></plan_due_date>";
					xmlValues = xmlValues + "<req_date><![CDATA[" + reqDate + "]]></req_date>";
					xmlValues = xmlValues + "<item_code><![CDATA[" + itemCode + "]]></item_code>";
					xmlValues = xmlValues + "<item_desc><![CDATA[" + itemDescr + "]]></item_desc>";
					xmlValues = xmlValues + "<quantity><![CDATA[" + quantity + "]]></quantity>";
					xmlValues = xmlValues + "<quantity__stduom><![CDATA[" + quantityStdUom + "]]></quantity__stduom>";
					xmlValues = xmlValues + "<unit__ind><![CDATA[" + unitInd + "]]></unit__ind>";
					xmlValues = xmlValues + "<unit__std><![CDATA[" + unitStd + "]]></unit__std>";
					xmlValues = xmlValues + "<site_code><![CDATA[" + siteCode + "]]></site_code>";
					xmlValues = xmlValues + "<site_code__dlv><![CDATA[" + siteCodeDlv + "]]></site_code__dlv>";
					xmlValues = xmlValues + "<site_code__acct><![CDATA[" + siteCodeAcct + "]]></site_code__acct>";
					xmlValues = xmlValues + "<apr_code><![CDATA[" + aprCode + "]]></apr_code>";
					xmlValues = xmlValues + "<priority><![CDATA[" + priority + "]]></priority>";
					xmlValues = xmlValues + "<acct_code><![CDATA[" + acctCode + "]]></acct_code>";
					xmlValues = xmlValues + "<cctr_code><![CDATA[" + cctrCode + "]]></cctr_code>";
					xmlValues = xmlValues + "<emp_code__pur><![CDATA[" + empCodePur + "]]></emp_code__pur>";
					xmlValues = xmlValues + "<emp_code__req><![CDATA[" + empCodeReq + "]]></emp_code__req>";
					xmlValues = xmlValues + "<supp_code__pref><![CDATA[" + suppCodePref + "]]></supp_code__pref>";
					xmlValues = xmlValues + "<purc_rate><![CDATA[" + purcRate + "]]></purc_rate>";
					xmlValues = xmlValues + "<pack_code><![CDATA[" + packCode + "]]></pack_code>";
					xmlValues = xmlValues + "<status><![CDATA[U]]></status>";
					xmlValues = xmlValues + "<chg_date><![CDATA[" + chgDateStr + "]]></chg_date>";
					xmlValues = xmlValues + "<chg_user><![CDATA[" + chgUser + "]]></chg_user>";
					xmlValues = xmlValues + "<chg_term><![CDATA[" + chgTerm + "]]></chg_term>";
					xmlValues = xmlValues + "<pur_lead_time><![CDATA[" + purLeadTime + "]]></pur_lead_time>";
					xmlValues = xmlValues + "<conv__qty_stdoum><![CDATA[" + convQtyStdUom + "]]></conv__qty_stdoum>";
					xmlValues = xmlValues + "<site_code__des><![CDATA[" + siteCode + "]]></site_code__des>";
					xmlValues = xmlValues + "<site_code__bill><![CDATA[" + siteCode + "]]></site_code__bill>";

					xmlValues = xmlValues + "</Detail1></Root>";

					tranIdIndent = getUniqueKey(xmlValues, indKeyStr, "ind_no", "IND");

					// System.out.println("Inserting indent # " + count + " " +
					// tranIdIndent);

					pstmtIndent.setString(1, tranIdIndent);
					pstmtIndent.setTimestamp(2, indDate);
					pstmtIndent.setString(3, indType);
					pstmtIndent.setString(4, deptCodeMfg);
					pstmtIndent.setTimestamp(5, planDueDate);
					pstmtIndent.setTimestamp(6, reqDate);
					pstmtIndent.setString(7, itemCode);
					pstmtIndent.setString(8, itemDescr);
					pstmtIndent.setDouble(9, quantity);
					pstmtIndent.setDouble(10, quantity);
					pstmtIndent.setDouble(11, 0);
					pstmtIndent.setString(12, unitInd);
					pstmtIndent.setString(13, unitStd);
					pstmtIndent.setString(14, siteCode);
					pstmtIndent.setString(15, siteCodeDlv);
					pstmtIndent.setString(16, siteCodeAcct);
					pstmtIndent.setString(17, aprCode);
					pstmtIndent.setString(18, priority);
					pstmtIndent.setString(19, acctCode);
					pstmtIndent.setString(20, cctrCode);
					pstmtIndent.setString(21, empCodePur);
					pstmtIndent.setString(22, empCodeReq);
					pstmtIndent.setString(23, suppCodePref);
					pstmtIndent.setDouble(24, purcRate);
					pstmtIndent.setString(25, packCode);
					pstmtIndent.setString(26, "U");
					pstmtIndent.setTimestamp(27, chgDate);
					pstmtIndent.setString(28, chgUser);
					pstmtIndent.setString(29, chgTerm);
					pstmtIndent.setDouble(30, purLeadTime);
					pstmtIndent.setDouble(31, convQtyStdUom);
					pstmtIndent.setString(32, siteCode);
					pstmtIndent.setString(33, siteCode);
					pstmtIndent.addBatch();

					HashMap valueMap = new HashMap();
					valueMap.put("item_code", itemCode);
					valueMap.put("site_code", siteCode);
					valueMap.put("ord_type", "");
					valueMap.put("quantity", quantity);
					valueMap.put("tran_ser", "Indent");
					valueMap.put("tran_id", tranIdIndent);
					valueMap.put("unit",unitStd);

					valueMap.put("due_date1",planDueDateStr);

					IPD_INDENT.add(valueMap);
					//cpatil-25/08/14-System.out.println("IPD_INDENT valueMap["+valueMap+"]");
				}
				//cpatil-25/08/14-System.out.println("@@@@@cpatil:IPD_INDENT["+IPD_INDENT+"]");
			} else if (winName.equalsIgnoreCase("W_DIST_DEMAND"))
			{
				for (int count = 0; count < list.size(); count++)
				{
					distDemand = (DistDemand) list.get(count);

					tranDate = distDemand.tranDate;
					tranDateStr = sdf.format(distDemand.tranDate);
					siteCode = distDemand.siteCode;
					itemCode = distDemand.itemCode;
					planDueDateStr = sdf.format(distDemand.planDueDate);
					planDueDate = distDemand.planDueDate;
					dueDateStr = sdf.format(distDemand.dueDate);
					dueDate = distDemand.dueDate;
					qtyRequired = distDemand.qtyRequired;
					unit = distDemand.unit;
					siteCodeSrc = distDemand.siteCodeSrc;
					dueDateOrd = distDemand.dueDateOrd;
					dueDateOrdStr = sdf.format(distDemand.dueDateOrd);
					chgDate = distDemand.chgDate;
					chgDateStr = sdf.format(distDemand.chgDate);

					// 20/01/09 manoharan
					// xmlValues
					// ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
					xmlValues = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><Root>";
					xmlValues = xmlValues + "<Header></Header>";
					xmlValues = xmlValues + "<Detail1>";
					xmlValues = xmlValues + "<tran_id><![CDATA[]]></tran_id>";
					xmlValues = xmlValues + "<tran_date><![CDATA[" + tranDateStr + "]]></tran_date>";
					xmlValues = xmlValues + "<site_code><![CDATA[" + siteCode + "]]></site_code>";
					xmlValues = xmlValues + "<item_code><![CDATA[" + itemCode + "]]></item_code>";
					xmlValues = xmlValues + "<plan_due_date><![CDATA[" + planDueDateStr + "]]></plan_due_date>";
					xmlValues = xmlValues + "<due_date><![CDATA[" + dueDateStr + "]]></due_date>";
					//System.out.println("@@@@@@cpatilround(qtyRequired,3)["+round(qtyRequired,3)+"]");
					xmlValues = xmlValues + "<qty_required><![CDATA[" + round(qtyRequired,3) + "]]></qty_required>";
					xmlValues = xmlValues + "<unit><![CDATA[" + unit + "]]></unit>";
					xmlValues = xmlValues + "<site_code__source><![CDATA[" + siteCodeSrc + "]]></site_code__source>";
					xmlValues = xmlValues + "<status><![CDATA[" + status + "]]></status>";
					xmlValues = xmlValues + "<due_date__ord><![CDATA[" + dueDateOrd + "]]></due_date__ord>";
					xmlValues = xmlValues + "<chg_date><![CDATA[" + chgDateStr + "]]></chg_date>";
					xmlValues = xmlValues + "<chg_user><![CDATA[" + chgUser + "]]></chg_user>";
					xmlValues = xmlValues + "<chg_term><![CDATA[" + chgTerm + "]]></chg_term>";
					xmlValues = xmlValues + "</Detail1></Root>";

					tranIdDistDemand = getUniqueKey(xmlValues, disDemKeyStr, "tran_id", "D-DEM");

					// System.out.println("Inserting dist demand # " + count +
					// " " + tranIdDistDemand);

					pstmtDistDemand.setString(1, tranIdDistDemand);
					pstmtDistDemand.setTimestamp(2, tranDate);
					pstmtDistDemand.setString(3, siteCode);
					pstmtDistDemand.setString(4, itemCode);
					pstmtDistDemand.setTimestamp(5, planDueDate);
					pstmtDistDemand.setTimestamp(6, dueDate);
					pstmtDistDemand.setDouble(7, qtyRequired);
					pstmtDistDemand.setString(8, unit);
					pstmtDistDemand.setString(9, siteCodeSrc);
					pstmtDistDemand.setString(10, status);
					pstmtDistDemand.setTimestamp(11, dueDateOrd);
					pstmtDistDemand.setTimestamp(12, chgDate);
					pstmtDistDemand.setString(13, chgUser);
					pstmtDistDemand.setString(14, chgTerm);

					pstmtDistDemand.addBatch();

					//Commented by manoj dtd 15/03/2014 pstmtIndent.addBatch();
					HashMap valueMap = new HashMap();
					valueMap.put("item_code", itemCode);
					valueMap.put("site_code", siteCode);
					valueMap.put("ord_type", "");
					valueMap.put("quantity", qtyRequired);
					valueMap.put("tran_ser", "Distribution Demand");
					valueMap.put("tran_id", tranIdDistDemand);
					valueMap.put("unit",unit);

					valueMap.put("due_date1",dueDateStr);

					IPD_DIST.add(valueMap);
					//cpatil-25/08/14-System.out.println("IPD_DIST valueMap["+valueMap+"]");
				}
				//cpatil-25/08/14-System.out.println("@@@@@cpatil:IPD_DIST["+IPD_DIST+"]");
			} else if (winName.equalsIgnoreCase("W_INDEPENDENT_DEMAND"))
			{
				for (int count = 0; count < list.size(); count++)
				{
					independentDemand = (IndependentDemand) list.get(count);

					siteCode = independentDemand.siteCode;
					siteCodeCust = independentDemand.siteCodeCust;
					itemCode = independentDemand.itemCode;
					unit = independentDemand.unit;
					unitStd = independentDemand.unitStd;
					quantity = independentDemand.quantity;
					quantityStdUom = independentDemand.quantityStdUom;
					convQtyStdUom = independentDemand.convQtyStdUom;
					tranDateStr = sdf.format(independentDemand.tranDate);
					tranDate = independentDemand.tranDate;
					planDueDate = independentDemand.planDueDate;
					planDueDateStr = sdf.format(independentDemand.planDueDate);
					dueDate = independentDemand.dueDate;
					dueDateStr = sdf.format(independentDemand.dueDate);

					// 20/01/09 manoharan
					// xmlValues
					// ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
					xmlValues = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><Root>";
					xmlValues = xmlValues + "<Header></Header>";
					xmlValues = xmlValues + "<Detail1>";
					xmlValues = xmlValues + "<tran_id><![CDATA[]]></tran_id>";
					xmlValues = xmlValues + "<site_code><![CDATA[" + siteCode + "]]></site_code>";
					xmlValues = xmlValues + "<site_code__cust><![CDATA[" + siteCodeCust + "]]></site_code__cust>";
					xmlValues = xmlValues + "<item_code><![CDATA[" + itemCode + "]]></item_code>";
					xmlValues = xmlValues + "<unit><![CDATA[" + unit + "]]></unit>";
					xmlValues = xmlValues + "<unit__std><![CDATA[" + unitStd + "]]></unit__std>";
					xmlValues = xmlValues + "<status><![CDATA[" + status + "]]></status>";
					xmlValues = xmlValues + "<quantity><![CDATA[" + quantity + "]]></quantity>";
					xmlValues = xmlValues + "<quantity__std_uom><![CDATA[" + quantityStdUom + "]]></quantity__std_uom>";
					xmlValues = xmlValues + "<conv__qty_std_oum><![CDATA[" + convQtyStdUom + "]]></conv__qty_std_oum>";
					xmlValues = xmlValues + "<tran_date><![CDATA[" + tranDateStr + "]]></tran_date>";
					xmlValues = xmlValues + "<plan_due_date><![CDATA[" + planDueDateStr + "]]></plan_due_date>";
					xmlValues = xmlValues + "<due_date><![CDATA[" + dueDateStr + "]]></due_date>";
					xmlValues = xmlValues + "</Detail1></Root>";

					tranIdIndDemand = getUniqueKey(xmlValues, indDemKeyStr, "tran_id", "I-DEM");
					// System.out.println(" ");
					// System.out.println(xmlValues);
					// System.out.println(" ");

					// System.out.println("Inserting independent demand # " +
					// count + " " + tranIdIndDemand);
					pstmtIndDemand.setString(1, tranIdIndDemand);
					pstmtIndDemand.setTimestamp(2, tranDate);
					pstmtIndDemand.setString(3, siteCode);
					pstmtIndDemand.setString(4, itemCode);
					pstmtIndDemand.setDouble(5, quantity);
					pstmtIndDemand.setString(6, unit);
					pstmtIndDemand.setDouble(7, convQtyStdUom);
					pstmtIndDemand.setDouble(8, quantityStdUom);
					pstmtIndDemand.setString(9, unitStd);
					pstmtIndDemand.setTimestamp(10, dueDate);
					pstmtIndDemand.setString(11, status);
					pstmtIndDemand.setString(12, siteCodeCust);
					pstmtIndDemand.setTimestamp(13, chgDate);
					pstmtIndDemand.setString(14, chgUser);
					pstmtIndDemand.setString(15, chgTerm);
					pstmtIndDemand.setTimestamp(16, planDueDate);

					pstmtIndDemand.addBatch();

					//Commented by manoj dtd 15/03/2014 pstmtIndent.addBatch();
					HashMap valueMap = new HashMap();
					valueMap.put("item_code", itemCode);
					valueMap.put("site_code", siteCode);
					valueMap.put("ord_type", "");
					valueMap.put("quantity", quantity);
					valueMap.put("tran_ser", "Independent Demand");
					valueMap.put("tran_id", tranIdIndDemand);
					valueMap.put("unit",unit);

					valueMap.put("due_date1",dueDateStr);

					IPD_INDEPENDENT.add(valueMap);
					//cpatil-25/08/14-System.out.println("IPD_INDEPENDENT valueMap["+valueMap+"]");
				}
				//cpatil-25/08/14-System.out.println("@@@@@cpatil:IPD_INDEPENDENT["+IPD_INDEPENDENT+"]");
			}

			//int rowsInsertedWorkOrder[] = pstmtWorkOrder.executeBatch();
			// Commented by Jiten 31/10/06 - error -null pointer Exception
			// pstmtMpsOrder.clearParameters();
			//pstmtWorkOrder.close();
			// int [] insertToIndependentDemandCounts =
			// pstmtMpsOrder.executeBatch() ;
			int rowsInsertedMpsOrder[] = pstmtMpsOrder.executeBatch();
			// Commented by Jiten 31/10/06 - error -null pointer Exception
			// pstmtMpsOrder.clearParameters();
			pstmtMpsOrder.close();
			// End
			// conn.commit();

			// int [] insertTopstmtIndentCounts = pstmtIndent.executeBatch();
			int rowsInsertedIndent[] = pstmtIndent.executeBatch();
			// pstmtIndent.clearParameters();//Commented by Jiten 14/11/06 as
			// giving null pointer exception
			pstmtIndent.close();
			// conn.commit();

			// int [] insertToDistDemandCounts = pstmtDistDemand.executeBatch();
			int rowsInsertedDistDemand[] = pstmtDistDemand.executeBatch();
			// pstmtDistDemand.clearParameters();//Commented by Jiten 14/11/06
			// as giving null pointer exception
			pstmtDistDemand.close();
			// conn.commit();

			int rowsInsertedIndDemand[] = pstmtIndDemand.executeBatch();
			// pstmtIndDemand.clearParameters();//Commented by Jiten 14/11/06 as
			// giving null pointer exception
			pstmtIndDemand.close();
			conn.commit();
		//	System.out.println("Rows Inserted in Work Order   : [" + rowsInsertedWorkOrder.length + "]");
			System.out.println("Rows Inserted in Mps Order   : [" + rowsInsertedMpsOrder.length + "]");
			System.out.println("Rows Inserted in Indent      : [" + rowsInsertedIndent.length + "]");
			System.out.println("Rows Inserted in Dist Demand : [" + rowsInsertedDistDemand.length + "]");
			System.out.println("Rows Inserted in Ind Demand  : [" + rowsInsertedIndDemand.length + "]");

		} // End of try
		catch (BatchUpdateException be)
		{
			be.printStackTrace();
			errString = be.getMessage();
			System.out.println("BatchUpdateException :RunMRPPrcEJB: CreatePlanDemand(ADPElement)" + errString);
			System.out.println("Detail Exception : " + be.getNextException());
		} catch (SQLException e)
		{
			System.out.println("SQLException :RunMRPPrcEJB : CreatePlanDemand(ADPElement adpElement).." + e.getMessage());
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB : CreatePlanDemand(ADPElement adpElement) : " + e.getMessage());
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			if (pstmtWorkOrder != null)
			{
				pstmtWorkOrder = null;
			}
			if (pstmtMpsOrder != null)
			{
				pstmtMpsOrder = null;
			}
			if (pstmtIndent != null)
			{
				pstmtIndent = null;
			}
			if (pstmtDistDemand != null)
			{
				pstmtDistDemand = null;
			}
			// return errString;
		}
		return errString;// Moved by Jiten as finally block does not complete
		// normally
	}

	private double round(double round,int scale) throws ITMException
	{
		return Math.round(round*Math.pow(10, scale))/Math.pow(10, scale);
	}

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

	// //////////////////////
	public String InsertPlanTable() throws Exception
	{
		PreparedStatement pstmtPlanHdr = null;
		PreparedStatement pstmtPlanDet = null;
		String resultString = "";

		String siteCode = "";
		String siteCodeSupp = "";
		String itemCode = "";
		String itemSer = "";
		String itemStru = "";
		String masterSch = "";
		String bomCode = "";
		String suppSour = "";
		String suppCodePref = "";
		String orderOpt = "";
		String dueDateStr = "";
		String batchQtyType = "";
		String empCodePur = "";
		String packCode = "";
		String unit = "";
		String acctCodePh = "";
		String acctCodeWp = "";
		String cctrCodePh = "";
		String aprCode = "";
		String cctrCodeWp = "";

		double demand = 0;
		double supply = 0;
		double planDemand = 0;
		double planSupply = 0;
		double runningDemand = 0;
		double runningSupply = 0;
		double runningPlanSupply = 0;
		double independentDemand = 0;
		double minOrderQty = 0;
		double maxOrderQty = 0;
		double integralQty = 0;
		double maxQty = 0;
		double maxStkQty = 0;
		double minQty = 0;
		double reorderQty = 0;
		double yieldPerc = 100;
		double minPlanPerc = 0;
		double batchQty = 0;
		double purcRate = 0;
		// 12/04/10 manoharan MF90BHU001
		double stockQty = 0;
		double othSupply = 0;
		// end 12/04/10 Manoharan MF90BHU001

		// Variables declared by gulzar on 4/18/2012
		double pendPOQty = 0;
		double pendDOQty = 0;
		double pendIndQty = 0;
		double pendDRQty = 0;
		// End changes by gulzar on 4/18/2012

		int purLeadTime = 0;
		int qcLeadTime = 0;
		int mfgLeadTime = 0;
		int minStkDay = 0;
		int maxStkDay = 0;
		int hdrSeq = 0, seqNo = 0;
		String saleOrder, lineNo;
		boolean flag = true;

		java.sql.Timestamp dueDate = null;

		ADPElement adpElement = null;
		try
		{
			// modified query. added SALE_ORDER & LINE_NO by sabyasachi on
			// 29-03-2011
			// 01/04/11 manoharan sale_order,line_no and seq_no added
			String sqlPlanHdr = "INSERT INTO PLAN_HDR(SITE_CODE, ITEM_CODE, ITEM_SER, SITE_CODE__SUPP, " + "SUPP_SOUR, BOM_CODE, MIN_QTY, MIN_ORDER_QTY, MIN_STK_DAY, MAX_QTY, " + "MAX_STK_DAY, ITEM_STRU, REO_QTY, PUR_LEAD_TIME, QC_LEAD_TIME, " + "MFG_LEAD_TIME, INTEGRAL_QTY, BATCH_QTY, BATCH_QTY_TYPE, MASTER_SCH, ORDER_OPT, " + "YIELD_PERC, MIN_PLAN_PERC, UNIT, APR_CODE, PACK_CODE, EMP_CODE__PUR, " + "SUPP_CODE__PREF, PURC_RATE, ACCT_CODE__PH, CCTR_CODE__PH, ACCT_CODE__WP," + " CCTR_CODE__WP,SALE_ORDER,LINE_NO,seq_no) " + "VALUES( ? , ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? , ? ," + " ? , ? , ? , ? , ? , ? ," + " ? , ? , ? , ?, ?, ?) ";
			pstmtPlanHdr = conn.prepareStatement(sqlPlanHdr);
			// 12/04/10 manoharan MF90BHU001 stock_qty and oth_supply added
			String sqlPlanDet = "INSERT INTO PLAN_DET(SITE_CODE, ITEM_CODE, DEMAND, SUPPLY, PLAN_SUPP, " + "RUNNING_DEMAND, RUNNING_SUPP, RUNNING_PLAN_SUPP, IND_DEMAND, DUE_DATE, " + " STOCK_QTY, OTH_SUPPLY,SALE_ORDER,LINE_NO,SEQ_NO, PENDING_PO, PENDING_DO, PENDING_INDENT, PENDING_DR) " + " VALUES( ? , ? , ? , ? , ? , ? ," + " ? , ? , ? , ?, ?, ?, ?, ? ,?, ?, ?, ?, ?) ";
			// end 12/04/10 manoharan MF90BHU001 stock_qty and oth_supply added
			pstmtPlanDet = conn.prepareStatement(sqlPlanDet);
			hdrSeq = 0;
			System.out.println("adpeList.size()----"+adpeList.size());
			for (int adpeCount = 0; adpeCount < adpeList.size(); adpeCount++)
			{
				flag = true;
				adpElement = (ADPElement) adpeList.get(adpeCount);

				siteCode = adpElement.getSiteCode();
				itemCode = adpElement.getItemCode();
				System.out.println("itemCode----"+itemCode+"---siteCode---"+siteCode);
				itemSer = adpElement.getItemSer();
				siteCodeSupp = adpElement.getSiteCodeSupp();
				suppSour = adpElement.getSuppSour();
				bomCode = adpElement.getBomCode();
				minQty = adpElement.getMinQty();
				minOrderQty = adpElement.getMinOrderQty();
				minStkDay = adpElement.getMinStkDay();
				maxQty = adpElement.getMaxQty();
				maxStkDay = adpElement.getMaxStkDay();
				itemStru = adpElement.getItemStru();
				reorderQty = adpElement.getReoQty();
				purLeadTime = adpElement.getPurLeadTime();
				qcLeadTime = adpElement.getQcLeadTime();
				mfgLeadTime = adpElement.getMfgLeadTime();
				integralQty = adpElement.getIntegralQty();
				batchQty = adpElement.getBatchQty();
				batchQtyType = adpElement.getBatchQtyType();
				masterSch = adpElement.getMasterSch();
				orderOpt = adpElement.getOrderOpt();
				yieldPerc = adpElement.getYieldPerc();
				minPlanPerc = adpElement.getMinPlanPerc();
				unit = adpElement.getUnit();
				aprCode = adpElement.getAprCode();
				packCode = adpElement.getPackCode();
				empCodePur = adpElement.getEmpCodePur();
				suppCodePref = adpElement.getSuppCodePref();
				purcRate = adpElement.getPurcRate();
				acctCodePh = adpElement.getAcctCodePh();
				cctrCodePh = adpElement.getCctrCodePh();
				acctCodeWp = adpElement.getAcctCodeWp();
				cctrCodeWp = adpElement.getCctrCodeWp();
				// added by sabyasachi on 29-03-2011
				saleOrder = adpElement.getSaleOrder();
				lineNo = adpElement.getLineNo();
				// seqNo = 0;
				// added by sabyasachi on 29-03-2011 ends
				// 02-03-2007 manoharan not to insert if the plan is not
				// selected
				if (!disPlan.equalsIgnoreCase("Y") && (suppSour.trim().equalsIgnoreCase("D")))
				{
					continue;
				}
				if (!matPlan.equalsIgnoreCase("Y") && (suppSour.trim().equalsIgnoreCase("P")))
				{
					continue;
				}
				if (!mfgPlan.equalsIgnoreCase("Y") && (suppSour.trim().equalsIgnoreCase("M") || suppSour.trim().equalsIgnoreCase("C")))
				{
					continue;
				}
				// end 02-03-2007 manoharan not to insert if the plan is not
				// selected
				ArrayList timeMRParr = adpElement.getTimeMrpList();
				if (bomCode != null && bomCode.trim().length() == 0)
					bomCode = null;
				for (int timeCtr = 0; timeCtr < timeMRParr.size(); timeCtr++)
				{
					TimeMRP timeMrp = (TimeMRP) timeMRParr.get(timeCtr);

					demand = timeMrp.getDemand();
					supply = timeMrp.getSupply();
					planSupply = timeMrp.getPlanSupply();
					runningDemand = timeMrp.getRunningDemand();
					runningSupply = timeMrp.getRunningSupply();
					runningPlanSupply = timeMrp.getRunningPlanSupply();
					// 01/04/11
					if (runningPlanSupply <= 0 && demand <= 0 && supply <= 0 && planSupply <= 0 && runningDemand <= 0 && runningSupply <= 0)
					{
						continue;
					}
					independentDemand = timeMrp.getIndependentDemand();
					dueDate = timeMrp.getDueDate();
					// 12/04/10 Manoharan MF90BHU001
					stockQty = timeMrp.getStockQty();
					othSupply = timeMrp.getOthSupply();
					// end 12/04/10 Manoharan MF90BHU001

					// Changes made by Gulzar on 4/18/2012
					pendPOQty = timeMrp.getPendingPO();
					pendDOQty = timeMrp.getPendingDO();
					pendIndQty = timeMrp.getPendingIndent();
					pendDRQty = timeMrp.getPendingDR();
					// End changes by Gulzar on 4/18/2012

					pstmtPlanDet.setString(1, siteCode);
					pstmtPlanDet.setString(2, itemCode);
					pstmtPlanDet.setDouble(3, demand);
					pstmtPlanDet.setDouble(4, supply);
					pstmtPlanDet.setDouble(5, planSupply);
					pstmtPlanDet.setDouble(6, runningDemand);
					pstmtPlanDet.setDouble(7, runningSupply);
					pstmtPlanDet.setDouble(8, runningPlanSupply);
					pstmtPlanDet.setDouble(9, independentDemand);
					pstmtPlanDet.setTimestamp(10, dueDate);
					// 12/04/10 Manoharan MF90BHU001
					pstmtPlanDet.setDouble(11, stockQty);
					pstmtPlanDet.setDouble(12, othSupply);
					// end 12/04/10 Manoharan MF90BHU001

					// 01/04/11 manoharan
					if (saleOrder != null && saleOrder.trim().length() > 0)
					{
						pstmtPlanDet.setString(13, saleOrder);
					} else
					{
						pstmtPlanDet.setNull(13, java.sql.Types.CHAR);
					}
					if (lineNo != null && lineNo.trim().length() > 0)
					{
						pstmtPlanDet.setString(14, lineNo);
					} else
					{
						pstmtPlanDet.setNull(14, java.sql.Types.CHAR);
					}
					seqNo++;
					pstmtPlanDet.setInt(15, seqNo);
					// end 01/04/11 manoharan

					// Changes made by Gulzar on 4/18/2012
					pstmtPlanDet.setDouble(16, pendPOQty);
					pstmtPlanDet.setDouble(17, pendDOQty);
					pstmtPlanDet.setDouble(18, pendIndQty);
					pstmtPlanDet.setDouble(19, pendDRQty);
					// Changes made by Gulzar on 4/18/2012

					pstmtPlanDet.addBatch();
				}
				if (seqNo > 0)
				{
					pstmtPlanHdr.setString(1, siteCode);
					pstmtPlanHdr.setString(2, itemCode);
					pstmtPlanHdr.setString(3, itemSer);
					pstmtPlanHdr.setString(4, siteCodeSupp);
					pstmtPlanHdr.setString(5, suppSour);
					if (bomCode != null && bomCode.trim().length() > 0)
					{// If Else condition added by Jiten 14/11/06
						pstmtPlanHdr.setString(6, bomCode);
					} else
					{
						pstmtPlanHdr.setNull(6, java.sql.Types.VARCHAR);
					}
					pstmtPlanHdr.setDouble(7, minQty);
					pstmtPlanHdr.setDouble(8, minOrderQty);
					pstmtPlanHdr.setInt(9, minStkDay);
					pstmtPlanHdr.setDouble(10, maxQty);
					pstmtPlanHdr.setInt(11, maxStkDay);
					pstmtPlanHdr.setString(12, itemStru);
					pstmtPlanHdr.setDouble(13, reorderQty);
					pstmtPlanHdr.setInt(14, purLeadTime);
					pstmtPlanHdr.setInt(15, qcLeadTime);
					pstmtPlanHdr.setInt(16, mfgLeadTime);
					pstmtPlanHdr.setDouble(17, integralQty);
					pstmtPlanHdr.setDouble(18, batchQty);
					pstmtPlanHdr.setString(19, batchQtyType);
					pstmtPlanHdr.setString(20, masterSch);
					pstmtPlanHdr.setString(21, orderOpt);
					pstmtPlanHdr.setDouble(22, yieldPerc);
					pstmtPlanHdr.setDouble(23, minPlanPerc);
					pstmtPlanHdr.setString(24, unit);
					pstmtPlanHdr.setString(25, aprCode);
					pstmtPlanHdr.setString(26, packCode);
					pstmtPlanHdr.setString(27, empCodePur);
					pstmtPlanHdr.setString(28, suppCodePref);
					pstmtPlanHdr.setDouble(29, purcRate);
					pstmtPlanHdr.setString(30, acctCodePh);
					pstmtPlanHdr.setString(31, cctrCodePh);
					pstmtPlanHdr.setString(32, acctCodeWp);
					pstmtPlanHdr.setString(33, cctrCodeWp);
					pstmtPlanHdr.setString(34, saleOrder);
					pstmtPlanHdr.setString(35, lineNo);
					hdrSeq++;

					pstmtPlanHdr.setInt(36, hdrSeq);
					pstmtPlanHdr.addBatch();
				}
				// System.out.println("Site Code : [" + siteCode +
				// "] Item Code : [" + itemCode + "] Bom Code : [" + bomCode +
				// "] Item Ser : [" + itemSer + "]");
			}
			int rowsInsertedPlanHdr[] = pstmtPlanHdr.executeBatch();
			// commented by ted by JIten -31/10/06
			// pstmtPlanHdr.clearParameters();
			// pstmtPlanHdr.close();
			// End
			int rowsInsertedPlanDet[] = pstmtPlanDet.executeBatch();
			// Below Two lines commented by Jiten 31/10/06
			// pstmtPlanDet.clearParameters();
			// pstmtPlanDet.close();
			// End

			conn.commit();
			System.out.println("Rows Inserted in Plan Header : " + rowsInsertedPlanHdr.length);
			System.out.println("Rows Inserted in Plan Deatil : " + rowsInsertedPlanDet.length);
		} catch (BatchUpdateException be)
		{
			System.out.println("BatchUpdateException :RunMRPPrcEJB :InsertPlanTable():" + be.getMessage());
			System.out.println("Detail Exception : " + be.getNextException());
			be.printStackTrace();
			int[] ptr = be.getUpdateCounts();// added by jiten 15/11/06
			for (int i = 0; i < ptr.length; i++)
			{// loop added by jiten 15/11/06
				if (ptr[i] == Statement.EXECUTE_FAILED)
				{
					System.out.println("Index [" + i + "] Error...");
					break;
				}
			}
			resultString = be.getMessage();
			throw new ITMException(be);
		} catch (SQLException se)
		{
			System.out.println("SQLException :RunMRPPrcEJB :InsertPlanTable():" + se.getMessage());
			se.printStackTrace();
			resultString = se.getMessage();
			throw new ITMException(se);
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :InsertPlanTable():" + e.getMessage());
			e.printStackTrace();
			resultString = e.getMessage();
			throw new ITMException(e);
		}
		return resultString;
	}

	// //////////////////////

	private String setValuesInBrow() throws ITMException
	{
		String errCode = "";
		String errString = "";
		String resultString = "";
		StringBuffer retTabSepStrBuff = new StringBuffer();
		StringBuffer valueXmlString = new StringBuffer();
		StringBuffer reqValueXmlString = new StringBuffer();
		String siteCode = "0";
		String itemCode = "0";
		String bomCode = "0";
		String suppSour = "0";
		String orderOpt = "0";
		String dueDateStr = "0";
		String batchQtyType = "0";
		String unit = "0";
		String desc = null;

		double demand = 0;
		double supply = 0;
		double planDemand = 0;
		double planSupply = 0;
		double runningDemand = 0;
		double runningSupply = 0;
		double runningPlanSupply = 0;
		double independentDemand = 0;
		double minOrderQty = 0;
		double integralQty = 0;
		double maxQty = 0;
		double minQty = 0;
		double reorderQty = 0;
		double yieldPerc = 100;
		double minPlanPerc = 0;
		double batchQty = 0;
		double purcRate = 0;
		int purLeadTime = 0;
		int qcLeadTime = 0;
		int mfgLeadTime = 0;
		boolean flag = true;
		// 12/04/10 Manoharan MF90BHU001
		double stockQty = 0;
		double othSupply = 0;
		// end 12/04/10 manoharan MF90BHU001

		// Variables declared by gulzar on 4/18/2012
		double pendPOQty = 0;
		double pendDOQty = 0;
		double pendIndQty = 0;
		double pendDRQty = 0;
		double qtStk = 0;
		// End changes by gulzar on 4/18/2012
		int count1=0,count2=0;
		ADPElement adpElement = null;
		//HashMap<String, ADPElement> detailMap = null;//Added by Manoj dtd 02/11/2013 to set Detail data in xml
		ArrayList<HashMap<String, ADPElement>> detList=null;

		String saleOrder="",itemCodeDescr="",sourceSupplyFlag="";
		PreparedStatement pstmt1 = null;
		ResultSet rs1 = null;
		HashMap sourceSupplyMap = new HashMap();
		String tranSer2="";

		HashMap itemCDDetailMap = new HashMap();

		String itemCodeParent="" , originalOrAltitem="";  // added by cpatil on 03/05/14
		String lineNo="";

		double grossWeight=0;
		String prevItemValue="";

		try
		{
			Set<String>  key=itemCodeDetailMap.keySet();
			Iterator<String> itr2=key.iterator();
			while(itr2.hasNext())
			{
				String keyVal=itr2.next();
				System.out.println("keyVal["+keyVal+"]");
				System.out.println("itemCodeDetailMap.get(keyVal)--["+itemCodeDetailMap.get(keyVal)+"]");
			}
			valueXmlString = new StringBuffer("<?xml version = \"1.0\"?><Root>\r\n");
			int count = 0,reqCount = 0;

			reqValueXmlString = new StringBuffer("<?xml version = \"1.0\"?><Root>\r\n");//added by chandrashekar 0n 12-08-14

			Set sorderItemSet=new TreeSet();

			//test
			//cpatil-25/08/14-System.out.println("@@@@@@@@@@@ cpatil start 15/01/14");
			//valueXmlString.append("<Detail" + context + ">");
			count++;
			valueXmlString.append("<Detail" + context + " domID='" + count + "' >\r\n");

			//cpatil-25/08/14-System.out.println("cpatil--------IPD_MPS_ORDER["+IPD_MPS_ORDER+"]");

			ArrayList IPD_MPS_ORDER_List = new ArrayList();
			ArrayList IPD_INDENT_List = new ArrayList();
			ArrayList IPD_DIST_List = new ArrayList();
			ArrayList IPD_INDEPENDENT_List = new ArrayList();

			for (int ctr3=0; ctr3 < IPD_MPS_ORDER.size();ctr3++)
			{
				count1++;
				HashMap tempMap = new HashMap();
				tempMap =  (HashMap) IPD_MPS_ORDER.get(ctr3);

				String siteCodeMap =  tempMap.get("site_code")==null?" ":tempMap.get("site_code").toString();
				String itemCodeMap =  tempMap.get("item_code")==null?" ":tempMap.get("item_code").toString();
				String tranIdCodeMap = tempMap.get("tran_id")==null?" ":tempMap.get("tran_id").toString();
				String tranSerMap =  tempMap.get("tran_ser")==null?" ":tempMap.get("tran_ser").toString();
				String quantityMap =  tempMap.get("quantity")==null?" ":tempMap.get("quantity").toString();
				String unitMap =  tempMap.get("unit")==null?" ":tempMap.get("unit").toString();
				String dueDate =  tempMap.get("due_date1")==null?" ":tempMap.get("due_date1").toString();

				valueXmlString.append("<Detail4 domID='" + count1 + "' >\r\n");
				valueXmlString.append("<site_code protect = '1'>").append("<![CDATA[" + siteCodeMap  + "]]>").append("</site_code>\r\n");
				valueXmlString.append("<item_code protect = '1'>").append("<![CDATA[" + itemCodeMap + "]]>").append("</item_code>\r\n");
				valueXmlString.append("<item_code_descr protect = '1'>").append("<![CDATA[" + setDescription("descr","item","item_code",itemCodeMap,conn) + "]]>").append("</item_code_descr>\r\n");
				valueXmlString.append("<tran_id protect = '1'>").append("<![CDATA[" + tranIdCodeMap + "]]>").append("</tran_id>\r\n");
				valueXmlString.append("<tran_ser protect = '1'>").append("<![CDATA[" + tranSerMap + "]]>").append("</tran_ser>\r\n");
				valueXmlString.append("<planned_quantity protect = '1'>").append("<![CDATA[" + quantityMap + "]]>").append("</planned_quantity>\r\n");
				valueXmlString.append("<unit protect = '1'>").append("<![CDATA[" + unitMap + "]]>").append("</unit>\r\n");
				valueXmlString.append("<source_supply protect = '1'>").append("M").append("</source_supply>\r\n");

				//valueXmlString.append("<previous_item protect = '1'>").append(itemWorderMap.get(itemCodeMap)==null?"":itemWorderMap.get(itemCodeMap).toString()).append("</previous_item>\r\n");
				valueXmlString.append("<new_planned_supply protect = '1'>").append("Y").append("</new_planned_supply>\r\n");    // added by cpatil on 27/08/14 for displaying diffenrent color for new planned
				valueXmlString.append("<due_date1 protect = '1'>").append(dueDate).append("</due_date1>\r\n");    // added by cpatil for due_date
				valueXmlString.append("</Detail4>");


				itemWorkOrderMap.put(itemCodeMap, tranIdCodeMap);   // 18/06/14
				//cpatil-25/08/14-System.out.println("7249:::itemCodeMap["+itemCodeMap+"]tranIdCodeMap["+tranIdCodeMap+"]-itemWorkOrderMap["+itemWorkOrderMap+"]");

				IPD_MPS_ORDER_List.add(siteCodeMap+itemCodeMap);
			}
			//cpatil-25/08/14-System.out.println("cpatil--------IPD_INDENT["+IPD_INDENT+"]");
			for (int ctr3=0; ctr3 < IPD_INDENT.size();ctr3++)
			{
				count1++;
				HashMap tempMap = new HashMap();
				tempMap =  (HashMap) IPD_INDENT.get(ctr3);

				String siteCodeMap =  tempMap.get("site_code")==null?" ":tempMap.get("site_code").toString();
				String itemCodeMap =  tempMap.get("item_code")==null?" ":tempMap.get("item_code").toString();
				String tranIdCodeMap = tempMap.get("tran_id")==null?" ":tempMap.get("tran_id").toString();
				String tranSerMap =  tempMap.get("tran_ser")==null?" ":tempMap.get("tran_ser").toString();
				String quantityMap =  tempMap.get("quantity")==null?" ":tempMap.get("quantity").toString();
				String unitMap =  tempMap.get("unit")==null?" ":tempMap.get("unit").toString();
				String dueDate =  tempMap.get("due_date1")==null?" ":tempMap.get("due_date1").toString();

				valueXmlString.append("<Detail4 domID='" + count1 + "' >\r\n");
				valueXmlString.append("<site_code protect = '1'>").append("<![CDATA[" + siteCodeMap  + "]]>").append("</site_code>\r\n");
				valueXmlString.append("<item_code protect = '1'>").append("<![CDATA[" + itemCodeMap + "]]>").append("</item_code>\r\n");
				valueXmlString.append("<item_code_descr protect = '1'>").append("<![CDATA[" + setDescription("descr","item","item_code",itemCodeMap,conn) + "]]>").append("</item_code_descr>\r\n");
				valueXmlString.append("<tran_id protect = '1'>").append("<![CDATA[" + tranIdCodeMap + "]]>").append("</tran_id>\r\n");
				valueXmlString.append("<tran_ser protect = '1'>").append("<![CDATA[" + tranSerMap + "]]>").append("</tran_ser>\r\n");
				valueXmlString.append("<planned_quantity protect = '1'>").append("<![CDATA[" + quantityMap + "]]>").append("</planned_quantity>\r\n");
				valueXmlString.append("<unit protect = '1'>").append("<![CDATA[" + unitMap + "]]>").append("</unit>\r\n");
				valueXmlString.append("<source_supply protect = '1'>").append("P").append("</source_supply>\r\n");
				valueXmlString.append("<new_planned_supply protect = '1'>").append("Y").append("</new_planned_supply>\r\n");     // added by cpatil on 27/08/14 for displaying diffenrent color for new planned
				valueXmlString.append("<due_date1 protect = '1'>").append(dueDate).append("</due_date1>\r\n");    // added by cpatil for due_date
				valueXmlString.append("</Detail4>");

				//itemWorderMap.put(itemCode, tranIdCodeMap);   // 18/06/14

				IPD_INDENT_List.add(siteCodeMap+itemCodeMap);
			}
			//cpatil-25/08/14-System.out.println("cpatil--------IPD_DIST["+IPD_DIST+"]");
			for (int ctr3=0; ctr3 < IPD_DIST.size();ctr3++)
			{
				count1++;
				HashMap tempMap = new HashMap();
				tempMap =  (HashMap) IPD_DIST.get(ctr3);

				String siteCodeMap =  tempMap.get("site_code")==null?" ":tempMap.get("site_code").toString();
				String itemCodeMap =  tempMap.get("item_code")==null?" ":tempMap.get("item_code").toString();
				String tranIdCodeMap = tempMap.get("tran_id")==null?" ":tempMap.get("tran_id").toString();
				String tranSerMap =  tempMap.get("tran_ser")==null?" ":tempMap.get("tran_ser").toString();
				String quantityMap =  tempMap.get("quantity")==null?" ":tempMap.get("quantity").toString();
				String unitMap =  tempMap.get("unit")==null?" ":tempMap.get("unit").toString();
				String dueDate =  tempMap.get("due_date1")==null?" ":tempMap.get("due_date1").toString();

				valueXmlString.append("<Detail4 domID='" + count1 + "' >\r\n");
				valueXmlString.append("<site_code protect = '1'>").append("<![CDATA[" + siteCodeMap  + "]]>").append("</site_code>\r\n");
				valueXmlString.append("<item_code protect = '1'>").append("<![CDATA[" + itemCodeMap + "]]>").append("</item_code>\r\n");
				valueXmlString.append("<item_code_descr protect = '1'>").append("<![CDATA[" + setDescription("descr","item","item_code",itemCodeMap,conn) + "]]>").append("</item_code_descr>\r\n");
				valueXmlString.append("<tran_id protect = '1'>").append("<![CDATA[" + tranIdCodeMap + "]]>").append("</tran_id>\r\n");
				valueXmlString.append("<tran_ser protect = '1'>").append("<![CDATA[" + tranSerMap + "]]>").append("</tran_ser>\r\n");
				valueXmlString.append("<planned_quantity protect = '1'>").append("<![CDATA[" + quantityMap + "]]>").append("</planned_quantity>\r\n");
				valueXmlString.append("<unit protect = '1'>").append("<![CDATA[" + unitMap + "]]>").append("</unit>\r\n");
				valueXmlString.append("<source_supply protect = '1'>").append("D").append("</source_supply>\r\n");
				valueXmlString.append("<new_planned_supply protect = '1'>").append("Y").append("</new_planned_supply>\r\n");    // added by cpatil on 27/08/14 for displaying diffenrent color for new planned
				valueXmlString.append("<due_date1 protect = '1'>").append(dueDate).append("</due_date1>\r\n");    // added by cpatil for due_date
				valueXmlString.append("</Detail4>");

				//	itemWorderMap.put(itemCode, tranIdCodeMap);   // 18/06/14

				IPD_DIST_List.add(siteCodeMap+itemCodeMap);
			}
			//cpatil-25/08/14-System.out.println("cpatil--------IPD_INDEPENDENT["+IPD_INDEPENDENT+"]");
			for (int ctr3=0; ctr3 < IPD_INDEPENDENT.size();ctr3++)
			{
				count1++;
				HashMap tempMap = new HashMap();
				tempMap =  (HashMap) IPD_INDEPENDENT.get(ctr3);

				String siteCodeMap =  tempMap.get("site_code")==null?" ":tempMap.get("site_code").toString();
				String itemCodeMap =  tempMap.get("item_code")==null?" ":tempMap.get("item_code").toString();
				String tranIdCodeMap = tempMap.get("tran_id")==null?" ":tempMap.get("tran_id").toString();
				String tranSerMap =  tempMap.get("tran_ser")==null?" ":tempMap.get("tran_ser").toString();
				String quantityMap =  tempMap.get("quantity")==null?" ":tempMap.get("quantity").toString();
				String unitMap =  tempMap.get("unit")==null?" ":tempMap.get("unit").toString();
				String dueDate =  tempMap.get("due_date1")==null?" ":tempMap.get("due_date1").toString();

				valueXmlString.append("<Detail4 domID='" + count1 + "' >\r\n");
				valueXmlString.append("<site_code protect = '1'>").append("<![CDATA[" + siteCodeMap  + "]]>").append("</site_code>\r\n");
				valueXmlString.append("<item_code protect = '1'>").append("<![CDATA[" + itemCodeMap + "]]>").append("</item_code>\r\n");
				valueXmlString.append("<item_code_descr protect = '1'>").append("<![CDATA[" + setDescription("descr","item","item_code",itemCodeMap,conn) + "]]>").append("</item_code_descr>\r\n");
				valueXmlString.append("<tran_id protect = '1'>").append("<![CDATA[" + tranIdCodeMap + "]]>").append("</tran_id>\r\n");
				valueXmlString.append("<tran_ser protect = '1'>").append("<![CDATA[" + tranSerMap + "]]>").append("</tran_ser>\r\n");
				valueXmlString.append("<planned_quantity protect = '1'>").append("<![CDATA[" + quantityMap + "]]>").append("</planned_quantity>\r\n");
				valueXmlString.append("<unit protect = '1'>").append("<![CDATA[" + unitMap + "]]>").append("</unit>\r\n");
				valueXmlString.append("<source_supply protect = '1'>").append("P").append("</source_supply>\r\n");
				valueXmlString.append("<new_planned_supply protect = '1'>").append("Y").append("</new_planned_supply>\r\n");      // added by cpatil on 27/08/14 for displaying diffenrent color for new planned
				valueXmlString.append("<due_date1 protect = '1'>").append(dueDate).append("</due_date1>\r\n");    // added by cpatil for due_date
				valueXmlString.append("</Detail4>");

				//	itemWorderMap.put(itemCode, tranIdCodeMap);   // 18/06/14

				IPD_INDEPENDENT_List.add(siteCodeMap+itemCodeMap);
			}

			valueXmlString.append("</Detail" + context + ">");
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
			//cpatil-25/08/14-System.out.println("@@@@@@@@@@@ cpatil end 15/01/14");


			//test end


			for(int c=0;c<adpeList.size();c++)
			{
				System.out.println("******((ADPElement) adpeList.get(c)).getSaleOrder()["+((ADPElement) adpeList.get(c)).getSaleOrder()+"]");
			}
			//SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
			System.out.println("Printing adpeList.size()---" + adpeList.size());
			System.out.println("parentItemMap["+parentItemMap+"]");
			System.out.println("itemCodeDetailMap["+itemCodeDetailMap+"]");
			System.out.println("itemBomMap["+itemBomMap+"]");
			System.out.println("itemBomMap1["+itemBomMap1+"]");
			System.out.println("itemBomMap2["+itemBomMap2+"]");
			ArrayList<ADPElement> al=new ArrayList<ADPElement>();
			/*if(isBomReplace)
			{
				for (int adpeCount = 0; adpeCount < adpeList.size(); adpeCount++)
				{

				}
			}*/
			/*if(isBomReplace)
			{
				for (int adpeCount = 0; adpeCount < adpeList.size(); adpeCount++)
				{
					ADPElement adpElement1 = (ADPElement) adpeList.get(adpeCount);
					if(itemCodeTo.equalsIgnoreCase( adpElement1.getItemCode()))
					{
						adpElement1.setSaleOrder(saleOrderReplaceBom);
					}
				}

			}*/
			for (int adpeCount = 0; adpeCount < adpeList.size(); adpeCount++)
			{
				ADPElement adpElement1 = (ADPElement) adpeList.get(adpeCount);

				System.out.println("9284--"+adpElement1.getSaleOrder());

			}
			/*
			for (int adpeCount = 0; adpeCount < adpeList.size(); adpeCount++)
			{

				flag = true;
				ADPElement adpElement1 = (ADPElement) adpeList.get(adpeCount);
				String sorder=adpElement1.getSaleOrder();
				System.out.println("sorder["+sorder+"]");
				String item=adpElement1.getItemCode();
				if(checkNull(sorder).trim().length()>0)
				{
					al.add(adpElement1);
				}
			}
			Set <String>itemSet=new HashSet<String>();
			for(int ctr=0;ctr<al.size();ctr++)
			{
				al1=new ArrayList<ADPElement>();
				ADPElement adpEle=al.get(ctr);
				al1.add(adpEle);
				String bCode=adpEle.getBomCode();
				adpEle.getItemCode();
				System.out.println("bCode["+bCode+"]");
				System.out.println("adpEle.getSaleOrder()+adpEle.getItemCode()["+adpEle.getSaleOrder()+adpEle.getItemCode()+"]");
				//if(!itemSet.contains(adpEle.getItemCode()))
				if(!itemSet.contains(adpEle.getItemCode()) && (checkNull(adpEle.getSaleOrder())).trim().length()>0)
					childItems(bCode,adpEle.getSaleOrder(),adpEle.getItemCode());
				itemSet.add(adpEle.getItemCode());
				System.out.println("al1.size()["+al1.size()+"]");
				finalMap.put(adpEle.getSaleOrder()+adpEle.getItemCode(), al1);
				System.out.println("finalMap["+finalMap.size()+"]");
			}*/

			/*Set keyset=finalMap.keySet();
			Iterator<String> itr1=keyset.iterator();
			while(itr1.hasNext())
			{
				String key1=itr1.next();
				System.out.println("8837 key1["+key1+"]");
				adpeList.clear();
				adpeList=finalMap.get(key1);
				System.out.println("finalMap.get(key1).size()["+(finalMap.get(key1)).size()+"]");
			}*/
			//Set keyset=finalMap.keySet();
			//Iterator<String> itr1=keyset.iterator();

			/*	Set keyset1=finalMap.keySet();
			Iterator<String>  itr3=keyset1.iterator();
			while(itr3.hasNext())
			{
				System.out.println("9314["+count+"]");
				String key2=itr3.next();
				System.out.println("8850 key2["+key2+"]");
				//ArrayList<ADPElement> adpeList1=finalMap.get(key2);
				System.out.println("finalMap.get(key2).size()["+finalMap.get(key2).size()+"]");*/   
			for (int adpeCount = 0; adpeCount < adpeList.size(); adpeCount++)
			{
				System.out.println("9321");

				flag = true;
				System.out.println("adpeCount["+adpeCount+"]");
				//adpElement = (ADPElement) adpeList1.get(adpeCount);
				adpElement = (ADPElement) (adpeList).get(adpeCount);	
				//cpatil-25/08/14-System.out.println("Printing adpeCount---" + adpeCount);
				//prevItemValue=adpElement.getItemCodeParent();
				siteCode = adpElement.getSiteCode();
				itemCode = adpElement.getItemCode();
				if(parentItemMap.size()>0)
				{
					if(parentItemMap.containsKey(itemCode))
					{
						prevItemValue=(String) parentItemMap.get(itemCode);
					}	
				}
				maxQty = adpElement.getMaxQty();
				minQty = adpElement.getMinQty();
				suppSour = adpElement.getSuppSour();
				orderOpt = adpElement.getOrderOpt();
				bomCode = adpElement.getBomCode();
				unit = adpElement.getUnit();
				batchQtyType = adpElement.getBatchQtyType();
				minOrderQty = adpElement.getMinOrderQty();
				integralQty = adpElement.getIntegralQty();
				reorderQty = adpElement.getReoQty();
				yieldPerc = adpElement.getYieldPerc();
				minPlanPerc = adpElement.getMinPlanPerc();
				batchQty = adpElement.getBatchQty();
				purcRate = adpElement.getPurcRate();
				qcLeadTime = adpElement.getQcLeadTime();
				purLeadTime = adpElement.getPurLeadTime();
				mfgLeadTime = adpElement.getMfgLeadTime();
				desc = adpElement.getItemDescr();
				saleOrder = adpElement.getSaleOrder(); 
				lineNo=adpElement.getLineNo(); 
				itemCodeParent = adpElement.getItemCodeParent();		//added by cpatil on 03/05/14
				originalOrAltitem = adpElement.getOriginalOrAltitem();		//added by cpatil on 03/05/14
				qtStk = adpElement.getQtStk();	//added by chandrashekar 0n 12-08-14
				System.out.println("itemCode["+itemCode+"]");
				itemCDDetailMap = adpElement.getbomSet();

				System.out.println("adpElement.getDemand()["+adpElement.getDemand()+"]");

				System.out.println("@@@@8864:itemCode["+itemCode+"]-->adpElement.getGrossWeight()["+adpElement.getGrossWeight()+"]");
				grossWeight = adpElement.getGrossWeight();


				bomMap.put(itemCode, bomCode);
				//cpatil-25/08/14-System.out.println("@@@@@@@@itemCDDetailMap["+itemCDDetailMap+"]");
				//cpatil-25/08/14-System.out.println("@@@@@@@@itemCodeParent["+itemCodeParent+"]originalOrAltitem["+originalOrAltitem+"]adpElement.getBomCodeParent()["+adpElement.getBomCodeParent()+"]");
				ArrayList timeMRParr = adpElement.getTimeMrpList();
				System.out.println("Printing timeMRParr.size()---" + timeMRParr.size());
				//detailMap=adpElement.getDetMap();//Added by Manoj dtd 02/11/2013

				//HashMap<String,ADPElement> detailMap=adpElement.getDetMap();
				/*Set keyset=detailMap.keySet();
					Iterator<String> itr1=keyset.iterator();
					while(itr1.hasNext())
					{
						String key=itr1.next();
						System.out.println("key----"+key);
						if(key!=null && (checkNull(key).trim()).length()>0)
						{
							System.out.println("detMap.get(key).getPendingPO()---"+detailMap.get(key).getPendingPO()+"----detailMap.get(key).getStockQty()---"+detailMap.get(key).getStockQty());
						}
					}*/
				detList=adpElement.getDetList();
				System.out.println("@@@@@@@@020115 detList["+detList+"]");

				if( isBomReplace )  
				{
					//cpatil-25/08/14-System.out.println("14/06/14 supreme Detail4List for itemCode [" + itemCode + "] detList.size() [" + detList.size() + "] detList [" + detList.toString() + "]");
				}
				double demandSum = 0,pendPOQtySum = 0;
				double supplySum = 0,pendIndQtySum = 0;
				double planSupplySum = 0,independentDemandSum = 0;
				double runningDemandSum = 0,runningPlanSupplySum = 0;
				double runningSupplySum = 0,planSupplySumSum = 0;

				//for (int timeCtr = 0; timeCtr < timeMRParr.size(); timeCtr++)

				for (int timeCtr = 0; timeCtr < 1 ; timeCtr++)
				{
					if( timeMRParr.size() > 0) 
					{	
						//cpatil-25/08/14-System.out.println("Printing timeCtr---" + timeCtr);
						TimeMRP timeMrp = (TimeMRP) timeMRParr.get(timeCtr);
						//cpatil-25/08/14-System.out.println("Printing timeMrp---" + timeMrp);

						demand = timeMrp.getDemand();
						demandSum = demandSum+demand;
						System.out.println("demand["+demand+"]");
						System.out.println("demandSum["+demandSum+"]");
						supply = timeMrp.getSupply();
						supplySum = supplySum+supply;
						planSupply = timeMrp.getPlanSupply();
						planSupplySum = planSupplySum+planSupply;
						runningDemand = timeMrp.getRunningDemand();
						runningDemandSum = runningDemandSum+runningDemand;
						runningSupply = timeMrp.getRunningSupply();
						runningSupplySum = runningSupplySum+runningSupply;
						runningPlanSupply = timeMrp.getRunningPlanSupply();
						runningPlanSupplySum = runningPlanSupplySum+runningPlanSupply;
						independentDemand = timeMrp.getIndependentDemand();
						independentDemandSum = independentDemandSum+independentDemand;
						dueDateStr = simpleDateFormat.format(timeMrp.getDueDate());
						// 12/04/10 manoharan MF90BHU001
						stockQty = timeMrp.getStockQty();
						othSupply = timeMrp.getOthSupply();
						// end 12/04/10 manoharan MF90BHU001

						// Changes made by Gulzar on 4/18/2012
						pendPOQty = timeMrp.getPendingPO();
						pendPOQtySum = pendPOQtySum+pendPOQty;
						pendDOQty = timeMrp.getPendingDO();
						pendIndQty = timeMrp.getPendingIndent();
						pendIndQtySum = pendIndQtySum+pendIndQty;
						pendDRQty = timeMrp.getPendingDR();
						//Added  by manoj dtd 05/01/15
						/*if(isDetailReq)
						{
							if(demand==0)
							{
								continue;
							}
						}*/
						// End changes by Gulzar on 4/18/2012

						// added by akhilesh on
						//count++; commented by chandrashekar
						//cpatil-25/08/14-System.out.println("@@@@@@@@@@@isDetailReq["+isDetailReq+"]");
						/*if(isDetailReq)  // cpatil
						{
							//count++;
							//cpatil-25/08/14-System.out.println("@@@@@@@@@["+siteCode+"]["+itemCode+ "]@@@@@@@@@sorderItemSet["+sorderItemSet+"]saleOrder["+saleOrder+"]isDetailReq["+isDetailReq+"]");
							if( sorderItemSet != null && sorderItemSet.contains(siteCode+itemCode+saleOrder+lineNo))   // +saleOrder
							{
								//cpatil-25/08/14-System.out.println("@@@@@@@@@@@@@@@@@@@ continue");
								continue;
							}
							else
							{
								//cpatil-25/08/14-System.out.println("@@@@@@@@@ added ["+siteCode+"]["+itemCode+"]["+saleOrder+"]@@@@@");
								sorderItemSet.add(  siteCode+itemCode+saleOrder+lineNo );  //+saleOrder
							}
						}*/
						/*if(isRequirement)  // Chandrashekar
						{

							System.out.println("@@@@@@@@@["+siteCode+"]["+itemCode+ "]@@@@@@@@@sorderItemSet["+sorderItemSet+"]saleOrder["+saleOrder+"]isRequirement["+isRequirement+"]");
							if( sorderItemSet != null && sorderItemSet.contains(siteCode+itemCode))   // +saleOrder
							{
								System.out.println("@@@@@@@@@@@@@@@@@@@ continue");
								continue;
							}
							else
							{
								System.out.println("@@@@@@@@@ added ["+siteCode+"]["+itemCode+"]["+saleOrder+"]@@@@@");
								sorderItemSet.add(  siteCode+itemCode );  //+saleOrder
							}
						}

						System.out.println("@@@@@@@@ test continue not found--["+siteCode+"]-["+itemCode+"]--@@sorderItemSet["+sorderItemSet+"]");*/

						//valueXmlString.append("<Detail" + context + " domID='" + count + "' >\r\n");
						if(!(isDetailReq))
						{	count++;
						valueXmlString.append("<Detail" + context + " domID='" + count + "' >\r\n");
						}
						else if(isDetailReq)
						{	
							count++;
							valueXmlString.append("<Detail" + context + " domID='" + count + "' >\r\n");
						}
						else
						{
							valueXmlString.append("<Detail" + context + ">\r\n ");
						}
						if(isDetailReq)
						{
							//valueXmlString.append("<sale_order protect = '1'>").append("<![CDATA[" + adpElement.getSaleOrder() + "]]>").append("</sale_order>\r\n");
							//valueXmlString.append("<line_no protect = '1'>").append("<![CDATA[" + adpElement.getLineNo() + "]]>").append("</line_no>\r\n");
							String refId=adpElement.getRefId();
							if (isBomReplace)
							{
								//cpatil-25/08/14-System.out.println("13/06/14 manoharan isBomReplace ["+ isBomReplace +"] refId["+refId+"]");
							}
							else
							{
								System.out.println("@@@@@@@@@@@@refId["+refId+"]");
							}



							//valueXmlString.append("<reference protect = '1'>").append("<![CDATA[" + adpElement.getRefId() + "]]>").append("</reference>\r\n");
						}
						if (flag || isDetailReq)
						{
							valueXmlString.append("<refDetails protect = '1'>").append("<![CDATA[" + adpElement.getRefId() + "]]>").append("</refDetails>\r\n");
							valueXmlString.append("<current_sorder protect = '1'>").append("<![CDATA[" + adpElement.getSaleOrder() + "]]>").append("</current_sorder>\r\n");
							valueXmlString.append("<site_code protect = '1'>").append("<![CDATA[" + siteCode + "]]>").append("</site_code>\r\n");
							valueXmlString.append("<item_code protect = '1'>").append("<![CDATA[" + itemCode + "]]>").append("</item_code>\r\n");
							valueXmlString.append("<item_code_descr protect = '1'>").append("<![CDATA[" + setDescription("descr","item","item_code",itemCode,conn) + "]]>").append("</item_code_descr>\r\n");
							valueXmlString.append("<supp_sour protect = '1'>").append("<![CDATA[" + suppSour + "]]>").append("</supp_sour>\r\n");




						} else
						{
							valueXmlString.append("<site_code protect = '1'>").append("<![CDATA[" + "" + "]]>").append("</site_code>\r\n");
							valueXmlString.append("<item_code protect = '1'>").append("<![CDATA[" + "" + "]]>").append("</item_code>\r\n");
							valueXmlString.append("<supp_sour protect = '1'>").append("<![CDATA[" + "" + "]]>").append("</supp_sour>\r\n");
						}
						if(isDetailReq)
						{
							System.out.println("getRequiredDecimal(demand, 3)["+getRequiredDecimal(demand, 3)+"]");
							System.out.println("getRequiredDecimal(adpElement.getReordPlanQty(), 3)["+getRequiredDecimal(adpElement.getReordPlanQty(), 3)+"]");
							//valueXmlString.append("<demand protect = '1'>").append("<![CDATA[" + getRequiredDecimal(demand, 3) + "]]>").append("</demand>\r\n");//Added  by manoj dtd 05/01/15	
							valueXmlString.append("<demand protect = '1'>").append("<![CDATA[" + getRequiredDecimal(adpElement.getDemand()-adpElement.getReordPlanQty(), 3) + "]]>").append("</demand>\r\n");//Added  by manoj dtd 05/01/15
							if( adpElement.getSoDemand() == 0)
							{
								valueXmlString.append("<sodemand protect = '1'>").append("<![CDATA[" + getRequiredDecimal(adpElement.getDemand()-adpElement.getReordPlanQty(), 3) + "]]>").append("</sodemand>\r\n");//Added  by manoj dt
							}
							else
							{
								valueXmlString.append("<sodemand protect = '1'>").append("<![CDATA[" + getRequiredDecimal(adpElement.getSoDemand()-adpElement.getReordPlanQty(), 3) + "]]>").append("</sodemand>\r\n");//Added  by manoj dtd 05/01/15
							}
							valueXmlString.append("<sale_order protect = '1'>").append("<![CDATA[" + adpElement.getSaleOrder() + "]]>").append("</sale_order>\r\n");
							valueXmlString.append("<line_no protect = '1'>").append("<![CDATA[" + checkNull(adpElement.getLineNo()) + "]]>").append("</line_no>\r\n");

							System.out.println("@@@@@@@@@ saleOrder["+checkNull(saleOrder).trim()+"]adpElement.getSaleOrder()["+checkNull(adpElement.getSaleOrder()).trim()+"]locGroupMap["+locGroupMap+"]");
							/*
							if( locGroupMap.containsKey(checkNull(saleOrder).trim()) )
							{
								System.out.println("@@@@@@@@ locGroupMap found for itemCode ["+itemCode+"]adpElement.getSaleOrder()["+adpElement.getSaleOrder()+"]saleOrder["+saleOrder+"]");

								//valueXmlString.append("<loc_group protect = '1'>").append("<![CDATA[" + locGroupMap.get(checkNull(adpElement.getSaleOrder()).trim())==null?"":locGroupMap.get(checkNull(adpElement.getSaleOrder()).trim()).toString() + "]]>").append("</loc_group>\r\n");
								valueXmlString.append("<loc_group protect = '1'>").append("<![CDATA[" + locGroupMap.get(checkNull(saleOrder).trim())==null?"":locGroupMap.get(checkNull(saleOrder).trim()).toString() + "]]>").append("</loc_group>\r\n");
							}
							else
							{
								System.out.println("@@@@@@@@ locGroupMap not found for itemCode ["+itemCode+"]adpElement.getSaleOrder()["+adpElement.getSaleOrder()+"]saleOrder["+saleOrder+"]");
								valueXmlString.append("<loc_group protect = '1'>").append("").append("</loc_group>\r\n");
							}
							 */

							String tempLocGroup="";

							Set s1=locGroupMap.entrySet(); 
							Iterator itr=s1.iterator();
							System.out.println("@@@@@final---locGroupMap["+locGroupMap+"]]");
							while(itr.hasNext())
							{ 
								Map.Entry m=(Map.Entry)itr.next(); 
								{ 
									//System.out.println("@@@@@@@@@@@m["+m+"]@@@@@@@@@");
									//tempList = new ArrayList();	
									String keyListStr =  m.getKey().toString(); 
									//System.out.println("@@@@@keyListStr["+keyListStr+"]@@@@["+keyMap.get("076ORE0009@  1")+"]");
									System.out.println("@@@@@@@@@@@@ inside map iterator keyListStr["+keyListStr+"]saleOrder["+saleOrder+"]");
									if( checkNull(keyListStr).trim().equalsIgnoreCase(checkNull(saleOrder).trim()) )
									{
										tempLocGroup = locGroupMap.get(keyListStr);
										System.out.println("@@@@@@@@ tempLocGroup found------>["+tempLocGroup+"]");
									}
								}
							}
							System.out.println("@@@@@@@@ tempLocGroup["+tempLocGroup+"]");

							if(  tempLocGroup == null || tempLocGroup.trim().length() == 0  )
							{
								if( locGroupList != null )
								{
									System.out.println("@@@@@ locGroupList["+locGroupList+"]");
									String locGroupLst[]=locGroupList.split(",");
									System.out.println("@@@@@ locGroupLst.length["+locGroupLst.length+"]");
									for(int i=0;i<locGroupLst.length;i++)
									{
										String SOrder="";
										String tempLocGroup1=locGroupLst[i];
										System.out.println("@@@@@ tempLocGroup1["+tempLocGroup1+"]");
										String tempLocGroupArr[]=tempLocGroup1.split("@");
										if( tempLocGroupArr.length > 0 )
										{
											SOrder=tempLocGroupArr[0];
										}
										System.out.println("@@@@@9826 SOrder["+SOrder+"]");
										if( SOrder != null )
										{
											tempLocGroup = locGroupMap.get(SOrder);
											System.out.println("@@@@@@@@9830 tempLocGroup found------>["+tempLocGroup+"]"); 
											break;
										}
									}
								}
								System.out.println("@@@@@9833 tempLocGroup["+tempLocGroup+"]");
							}

							valueXmlString.append("<loc_group protect = '1'>").append("<![CDATA[" + tempLocGroup + "]]>").append("</loc_group>\r\n");

						}
						else
						{
							valueXmlString.append("<demand protect = '1'>").append("<![CDATA[" + getRequiredDecimal(demand, 3) + "]]>").append("</demand>\r\n");	
						}

						if(isDetailReq)
							//valueXmlString.append("<supply protect = '1'>").append("<![CDATA[" + round(supplySum, 3) + "]]>").append("</supply>\r\n");
							valueXmlString.append("<supply protect = '1'>").append("<![CDATA[" + getRequiredDecimal(adpElement.getSupply(), 3) + "]]>").append("</supply>\r\n");
						else
						{
							valueXmlString.append("<supply protect = '1'>").append("<![CDATA[" + round(supply, 3) + "]]>").append("</supply>\r\n");
						}
						valueXmlString.append("<due_date protect = '1'>").append("<![CDATA[" + dueDateStr + "]]>").append("</due_date>\r\n");
						valueXmlString.append("<plan_supply protect = '1'>").append("<![CDATA[" + getRequiredDecimal(planSupply, 3) + "]]>").append("</plan_supply>\r\n");
						valueXmlString.append("<running_demand protect = '1'>").append("<![CDATA[" + getRequiredDecimal(runningDemand, 3) + "]]>").append("</running_demand>\r\n");
						valueXmlString.append("<running_supply protect = '1'>").append("<![CDATA[" + getRequiredDecimal(runningSupply, 3) + "]]>").append("</running_supply>\r\n");
						valueXmlString.append("<running_plan_supply protect = '1'>").append("<![CDATA[" + getRequiredDecimal(runningPlanSupply, 3) + "]]>").append("</running_plan_supply>\r\n");
						valueXmlString.append("<independent_demand protect = '1'>").append("<![CDATA[" + getRequiredDecimal(independentDemand, 3) + "]]>").append("</independent_demand>\r\n");
						if (flag)
						{
							if (bomCode != null)
							{
								valueXmlString.append("<bom_code protect = '1'>").append("<![CDATA[" + bomCode + "]]>").append("</bom_code>\r\n");
							} else
							{
								valueXmlString.append("<bom_code protect = '1'>").append("<![CDATA[" + "" + "]]>").append("</bom_code>\r\n");
							}
							valueXmlString.append("<order_opt protect = '1'>").append("<![CDATA[" + orderOpt + "]]>").append("</order_opt>\r\n");
							valueXmlString.append("<batch_qty_type protect = '1'>").append("<![CDATA[" + batchQtyType + "]]>").append("</batch_qty_type>\r\n");
							valueXmlString.append("<unit protect = '1'>").append("<![CDATA[" + unit + "]]>").append("</unit>\r\n");
							valueXmlString.append("<min_order_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(minOrderQty, 3) + "]]>").append("</min_order_qty>\r\n");
							valueXmlString.append("<integral_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(integralQty, 3) + "]]>").append("</integral_qty>\r\n");
							valueXmlString.append("<max_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(maxQty, 3) + "]]>").append("</max_qty>\r\n");
							valueXmlString.append("<min_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(minQty, 3) + "]]>").append("</min_qty>\r\n");
							valueXmlString.append("<reorder_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(reorderQty, 3) + "]]>").append("</reorder_qty>\r\n");
							valueXmlString.append("<yield_perc protect = '1'>").append("<![CDATA[" + getRequiredDecimal(yieldPerc, 2) + "]]>").append("</yield_perc>\r\n");
							valueXmlString.append("<min_plan_perc protect = '1'>").append("<![CDATA[" + getRequiredDecimal(minPlanPerc, 2) + "]]>").append("</min_plan_perc>\r\n");
							valueXmlString.append("<batch_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(batchQty, 3) + "]]>").append("</batch_qty>\r\n");
							valueXmlString.append("<purc_rate protect = '1'>").append("<![CDATA[" + getRequiredDecimal(purcRate, 3) + "]]>").append("</purc_rate>\r\n");
							valueXmlString.append("<pur_lead_time protect = '1'>").append("<![CDATA[" + getRequiredDecimal(purLeadTime, 2) + "]]>").append("</pur_lead_time>\r\n");
							valueXmlString.append("<qc_lead_time protect = '1'>").append("<![CDATA[" + getRequiredDecimal(qcLeadTime, 2) + "]]>").append("</qc_lead_time>\r\n");
							valueXmlString.append("<mfg_lead_time protect = '1'>").append("<![CDATA[" + getRequiredDecimal(mfgLeadTime, 2) + "]]>").append("</mfg_lead_time>\r\n");
							valueXmlString.append("<description protect = '1'>").append("<![CDATA[" + desc + "]]>").append("</description>\r\n");
							valueXmlString.append("<stock_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(stockQty, 3) + "]]>").append("</stock_qty>\r\n");
							valueXmlString.append("<oth_supply protect = '1'>").append("<![CDATA[" + getRequiredDecimal(othSupply, 3) + "]]>").append("</oth_supply>\r\n");
							valueXmlString.append("<pending_po protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendPOQty, 3) + "]]>").append("</pending_po>\r\n");
							valueXmlString.append("<pending_do protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendDOQty, 3) + "]]>").append("</pending_do>\r\n");
							valueXmlString.append("<pending_indent protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendIndQty, 3) + "]]>").append("</pending_indent>\r\n");
							valueXmlString.append("<pending_dr protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendDRQty, 3) + "]]>").append("</pending_dr>\r\n");
						} else
						{
							valueXmlString.append("<bom_code protect = '1'>").append("<![CDATA[" + "" + "]]>").append("</bom_code>\r\n");
							valueXmlString.append("<order_opt protect = '1'>").append("<![CDATA[" + "" + "]]>").append("</order_opt>\r\n");
							valueXmlString.append("<batch_qty_type protect = '1'>").append("<![CDATA[" + "" + "]]>").append("</batch_qty_type>\r\n");
							valueXmlString.append("<unit protect = '1'>").append("<![CDATA[" + "" + "]]>").append("</unit>\r\n");
							valueXmlString.append("<min_order_qty protect = '1'>").append("<![CDATA[" + 0.000 + "]]>").append("</min_order_qty>\r\n");
							valueXmlString.append("<integral_qty protect = '1'>").append("<![CDATA[" + 0.000 + "]]>").append("</integral_qty>\r\n");
							valueXmlString.append("<max_qty protect = '1'>").append("<![CDATA[" + 0.000 + "]]>").append("</max_qty>\r\n");
							valueXmlString.append("<min_qty protect = '1'>").append("<![CDATA[" + 0.000 + "]]>").append("</min_qty>\r\n");
							valueXmlString.append("<reorder_qty protect = '1'>").append("<![CDATA[" + 0.000 + "]]>").append("</reorder_qty>\r\n");
							valueXmlString.append("<yield_perc protect = '1'>").append("<![CDATA[" + 0.00 + "]]>").append("</yield_perc>\r\n");
							valueXmlString.append("<min_plan_perc protect = '1'>").append("<![CDATA[" + 0.00 + "]]>").append("</min_plan_perc>\r\n");
							valueXmlString.append("<batch_qty protect = '1'>").append("<![CDATA[" + 0.000 + "]]>").append("</batch_qty>\r\n");
							valueXmlString.append("<purc_rate protect = '1'>").append("<![CDATA[" + 0.000 + "]]>").append("</purc_rate>\r\n");
							valueXmlString.append("<pur_lead_time protect = '1'>").append("<![CDATA[" + 0.00 + "]]>").append("</pur_lead_time>\r\n");
							valueXmlString.append("<qc_lead_time protect = '1'>").append("<![CDATA[" + 0.00 + "]]>").append("</qc_lead_time>\r\n");
							valueXmlString.append("<mfg_lead_time protect = '1'>").append("<![CDATA[" + 0.00 + "]]>").append("</mfg_lead_time>\r\n");
							valueXmlString.append("<description protect = '1'>").append("<![CDATA[" + "" + "]]>").append("</description>\r\n");
							valueXmlString.append("<stock_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(stockQty, 3) + "]]>").append("</stock_qty>\r\n");
							valueXmlString.append("<oth_supply protect = '1'>").append("<![CDATA[" + getRequiredDecimal(othSupply, 3) + "]]>").append("</oth_supply>\r\n");
							valueXmlString.append("<pending_po protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendPOQty, 3) + "]]>").append("</pending_po>\r\n");
							valueXmlString.append("<pending_do protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendDOQty, 3) + "]]>").append("</pending_do>\r\n");
							valueXmlString.append("<pending_indent protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendIndQty, 3) + "]]>").append("</pending_indent>\r\n");
							valueXmlString.append("<pending_dr protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendDRQty, 3) + "]]>").append("</pending_dr>\r\n");

						}

						if( isDetailReq )	
						{
							finalString = "";

							String tempCode2 = itemBomMap.get(itemCode);//adpElement.getBomCodeParent()==null ?"":adpElement.getBomCodeParent();
							valueXmlString.append("<bom_code_parent protect = '1'>").append("<![CDATA[" + checkNull(tempCode2) + "]]>").append("</bom_code_parent>\r\n");
							String tempCode = adpElement.getBomCode()==null ?"":adpElement.getBomCode();
							valueXmlString.append("<bom_code_org protect = '1'>").append("<![CDATA[" + tempCode + "]]>").append("</bom_code_org>\r\n");
							valueXmlString.append("<bom_code_ref protect = '1'>").append("<![CDATA[" + tempCode + "]]>").append("</bom_code_ref>\r\n");

							if(grossWeight>0)
							{
								valueXmlString.append("<gross_weight protect = '1'>").append("<![CDATA["+ getRequiredDecimal(grossWeight,3) +"]]>").append("</gross_weight>\r\n");	
							}
							else
							{
								valueXmlString.append("<gross_weight protect = '1'>").append("<![CDATA["+ getRequiredDecimal(adpElement.getDemand(),3) +"]]>").append("</gross_weight>\r\n");
							}
							//String mfgType = getMfgType( itemCode, conn);
							String mfgType = getMfgType( itemCode,siteCode, conn); 
							valueXmlString.append("<mfg_type protect = '1'>").append("<![CDATA["+mfgType +"]]>").append("</mfg_type>\r\n");

							valueXmlString.append("<itemType protect = '1'>").append("<![CDATA[" + getItemType(suppSour) + "]]>").append("</itemType>\r\n");

							/*
							int tempCnt = Integer.parseInt(getItemType(suppSour)==null?"0":getItemType(suppSour));
							System.out.println("@@@@@@@@@@@itemCode["+itemCode+"]suppSour["+suppSour+"] tempCnt["+tempCnt+"]tempCode2["+tempCode2+"]");
							for( int ctrCnt=1; ctrCnt <= tempCnt; ctrCnt++)
							{
								finalString = finalString + "-";
							}
							if( tempCnt > 0)
							{
								finalString = finalString + ">";
							}
							if( tempCode2 == null || tempCode2.trim().length() == 0 )
							{
								//System.out.println("@@@@@@@@@@@ main item.....");
								finalString = "";
							}
							if( bomCode == null || bomCode.trim().length() == 0 )
							{
								finalString = finalString + itemCode ;
							}
							else
							{
								finalString = finalString + itemCode + "("+bomCode.trim()+")" ;
							}
							 */

							if( bomCode == null || bomCode.trim().length() == 0 )
							{
								finalString = itemCode ;
							}
							else
							{
								finalString = itemCode + "("+bomCode.trim()+")" ;
							}


							// getParentItemList(itemCode, parentItemMap , itemBomMap ,bomMap );
							// System.out.println("2@@@@@@getParentList["+finalString+"]stkKey[1]["+stkKey[1]+"]parentItemMap["+parentItemMap+"]");
							valueXmlString.append("<itemDetailsInfo protect = '1'>").append("<![CDATA["+finalString +"]]>").append("</itemDetailsInfo>\r\n");

							/*
							Boolean tranSerflag = tranSerFlag(siteCode+itemCode,IPD_DIST_List,IPD_INDENT_List,IPD_INDEPENDENT_List,IPD_MPS_ORDER_List);
							sourceSupplyFlag="";
							System.out.println("@@@@@@@@@["+itemCode+"]tranSerflag["+tranSerflag+"]tranSer2["+tranSer2+"]");
							if( tranSerflag == true )
							{
								sourceSupplyFlag = "P";
							}
							if( "Stock".equalsIgnoreCase(tranSer2) )
							{
								sourceSupplyFlag = sourceSupplyFlag + "S";
							}
							if("Work Order".equalsIgnoreCase(tranSer2) || "Dist Order".equalsIgnoreCase(tranSer2) || "Dist Order".equalsIgnoreCase(tranSer2) || "Purchase Order".equalsIgnoreCase(tranSer2) || "Indent".equalsIgnoreCase(tranSer2))
							{
								sourceSupplyFlag = sourceSupplyFlag + "W";
							}
							if( sourceSupplyFlag != null && sourceSupplyFlag.trim().length() > 0)
							{
								valueXmlString.append("<source_supply protect = '1'>").append("<![CDATA[" + sourceSupplyFlag + "]]>").append("</source_supply>\r\n");
							}
							//cpatil-25/08/14-System.out.println("@@@@@@@@@@@@@@@["+itemCode+"] sourceSupplyFlag["+sourceSupplyFlag+"] ");
							tranSer2="";
							 */

							System.out.println("@@@@@@itemCode["+itemCode+"]itemCDDetailMap["+itemCDDetailMap+"]");
							if ( itemCDDetailMap != null && itemCDDetailMap.containsKey(itemCode))
							{
								String tempBomItem = itemCDDetailMap.get(itemCode)==null?"":itemCDDetailMap.get(itemCode).toString();
								valueXmlString.append("<itemCodeDetailMap  protect = '1'>").append("<![CDATA[" + tempBomItem + "]]>").append("</itemCodeDetailMap>\r\n");  // added by cpatil on 03/05/14	
							}
							else
							{
								valueXmlString.append("<itemCodeDetailMap  protect = '1'>").append(" ").append("</itemCodeDetailMap>\r\n");  // added by cpatil on 03/05/14
							}

						}


						//cpatil-25/08/14-System.out.println("Printing valueXmlString----" + valueXmlString);
						// ended by akhilesh

						if (flag)
						{
							retTabSepStrBuff.append(siteCode).append("\t");
							retTabSepStrBuff.append(itemCode).append("\t");
							retTabSepStrBuff.append(desc).append("\t");// Gulzar on
							// 4/30/2012
							retTabSepStrBuff.append(suppSour).append("\t");
						} else
						{
							retTabSepStrBuff.append(" ").append("\t");
							retTabSepStrBuff.append(" ").append("\t");
							retTabSepStrBuff.append(" ").append("\t");// Gulzar on
							// 4/30/2012
							// for item
							// description
							retTabSepStrBuff.append(" ").append("\t");
						}
						retTabSepStrBuff.append(decFormat(demand)).append("\t");
						retTabSepStrBuff.append(decFormat(supply)).append("\t");

						// 12/04/10 manoharan MF90BHU001
						retTabSepStrBuff.append(decFormat(stockQty)).append("\t");
						retTabSepStrBuff.append(decFormat(othSupply)).append("\t");
						// end end 12/04/10 manoharan MF90BHU001

						// Changes made by Gulzar on 4/18/2012
						retTabSepStrBuff.append(decFormat(pendPOQty)).append("\t");
						retTabSepStrBuff.append(decFormat(pendDOQty)).append("\t");
						retTabSepStrBuff.append(decFormat(pendIndQty)).append("\t");
						retTabSepStrBuff.append(decFormat(pendDRQty)).append("\t");
						// End changes by Gulzar on 4/18/2012

						retTabSepStrBuff.append(dueDateStr).append("\t");
						retTabSepStrBuff.append(decFormat(planSupply)).append("\t");
						retTabSepStrBuff.append(decFormat(runningDemand)).append("\t");
						retTabSepStrBuff.append(decFormat(runningSupply)).append("\t");
						retTabSepStrBuff.append(decFormat(runningPlanSupply)).append("\t");
						retTabSepStrBuff.append(decFormat(independentDemand)).append("\t");
						if (flag)
						{
							if (bomCode != null)
							{
								retTabSepStrBuff.append(bomCode).append("\t");
							} else
							{
								retTabSepStrBuff.append(" ").append("\t");
							}
							retTabSepStrBuff.append(orderOpt).append("\t");
							retTabSepStrBuff.append(batchQtyType).append("\t");
							retTabSepStrBuff.append(unit).append("\t");
							retTabSepStrBuff.append(minOrderQty).append("\t");
							retTabSepStrBuff.append(integralQty).append("\t");
							retTabSepStrBuff.append(maxQty).append("\t");
							retTabSepStrBuff.append(minQty).append("\t");
							retTabSepStrBuff.append(reorderQty).append("\t");
							retTabSepStrBuff.append(yieldPerc).append("\t");
							retTabSepStrBuff.append(minPlanPerc).append("\t");
							retTabSepStrBuff.append(batchQty).append("\t");
							retTabSepStrBuff.append(purcRate).append("\t");
							retTabSepStrBuff.append(purLeadTime).append("\t");
							retTabSepStrBuff.append(qcLeadTime).append("\t");
							retTabSepStrBuff.append(mfgLeadTime).append("\n");
							// retTabSepStrBuff.append(desc).append("\t");//Gulzar
							// on 4/30/2012

							/*
							 * // 12/04/10 manoharan MF90BHU001
							 * retTabSepStrBuff.append
							 * (decFormat(stockQty)).append("\t");
							 * retTabSepStrBuff.append
							 * (decFormat(othSupply)).append("\n"); // end end
							 * 12/04/10 manoharan MF90BHU001
							 * 
							 * //Changes made by Gulzar on 4/18/2012
							 * retTabSepStrBuff
							 * .append(decFormat(pendPOQty)).append("\t");
							 * retTabSepStrBuff
							 * .append(decFormat(pendDOQty)).append("\t");
							 * retTabSepStrBuff
							 * .append(decFormat(pendIndQty)).append("\t");
							 * retTabSepStrBuff
							 * .append(decFormat(pendDRQty)).append("\t"); //End
							 * changes by Gulzar on 4/18/2012
							 */
						} else
						{
							retTabSepStrBuff.append(" ").append("\t");
							retTabSepStrBuff.append(" ").append("\t");
							retTabSepStrBuff.append(" ").append("\t");
							retTabSepStrBuff.append(" ").append("\t");
							retTabSepStrBuff.append("0").append("\t");
							retTabSepStrBuff.append("0").append("\t");
							retTabSepStrBuff.append("0").append("\t");
							retTabSepStrBuff.append("0").append("\t");
							retTabSepStrBuff.append("0").append("\t");
							retTabSepStrBuff.append("0").append("\t");
							retTabSepStrBuff.append("0").append("\t");
							retTabSepStrBuff.append("0").append("\t");
							retTabSepStrBuff.append("0").append("\t");
							retTabSepStrBuff.append("0").append("\t");
							retTabSepStrBuff.append("0").append("\t");
							retTabSepStrBuff.append("0").append("\n");
							// retTabSepStrBuff.append(desc).append("\t");//Gulzar
							// on 4/30/2012
							/*
							 * // 12/04/10 manoharan MF90BHU001
							 * retTabSepStrBuff.append
							 * (decFormat(stockQty)).append("\t");
							 * retTabSepStrBuff.append
							 * (decFormat(othSupply)).append("\n"); // end end
							 * 12/04/10 manoharan MF90BHU001
							 * 
							 * //Changes made by Gulzar on 4/18/2012
							 * retTabSepStrBuff
							 * .append(decFormat(pendPOQty)).append("\t");
							 * retTabSepStrBuff
							 * .append(decFormat(pendDOQty)).append("\t");
							 * retTabSepStrBuff
							 * .append(decFormat(pendIndQty)).append("\t");
							 * retTabSepStrBuff
							 * .append(decFormat(pendDRQty)).append("\t"); //End
							 * changes by Gulzar on 4/18/2012
							 */
						}
						flag = false;
						//int count1=0;

						System.out.println("@@@@@@@@@050115 9654 detList.size()["+detList.size()+"]");

						for(int k=0;k<detList.size();k++)
						{

							Set keySet=detList.get(k).keySet();
							Iterator<String> itr=keySet.iterator();
							while(itr.hasNext())
							{
								System.out.println("@@@@@@@@ inside while--k["+k+"]");
								String mapKey=itr.next();
								System.out.println("mapKey---"+mapKey);
								boolean populateDet=false;
								if(mapKey!=null && checkNull(mapKey).trim().length()>0)
								{
									populateDet=true;
								}
								System.out.println("@@@@@@@@050115 populateDet["+populateDet+"]");
								if(populateDet)
								{	
									System.out.println("@@@@@@@@@ inside populateDet....");
									ADPElement detadpElement=detList.get(k).get(mapKey);

									//siteCode = detadpElement.getSiteCode();
									//itemCode = detadpElement.getItemCode();
									//maxQty = detadpElement.getMaxQty();
									//minQty = detadpElement.getMinQty();
									//suppSour = detadpElement.getSuppSour();
									//orderOpt = detadpElement.getOrderOpt();
									//bomCode = detadpElement.getBomCode();
									//unit = detadpElement.getUnit();
									//batchQtyType = detadpElement.getBatchQtyType();
									//minOrderQty = detadpElement.getMinOrderQty();
									//integralQty = detadpElement.getIntegralQty();
									//reorderQty = detadpElement.getReoQty();
									//yieldPerc = detadpElement.getYieldPerc();
									//minPlanPerc = detadpElement.getMinPlanPerc();
									//batchQty = detadpElement.getBatchQty();
									//purcRate = detadpElement.getPurcRate();
									//qcLeadTime = detadpElement.getQcLeadTime();
									//purLeadTime = detadpElement.getPurLeadTime();
									//mfgLeadTime = detadpElement.getMfgLeadTime();
									//desc = detadpElement.getItemDescr();


									ArrayList dettimeMRParr = detadpElement.getTimeMrpList();
									System.out.println("@@@@@@@@@050115 9696 dettimeMRParr.size()["+dettimeMRParr.size()+"]");
									for (int dettimeCtr = 0; dettimeCtr < dettimeMRParr.size(); dettimeCtr++)
									{
										System.out.println("@@@@@@@@@@@ inside dettimeCtr["+dettimeCtr+"]");
										count1++;
										valueXmlString.append("<Detail4 domID='" + count1 + "' >\r\n");

										String altItemPerc = detadpElement.getAltitemPerc();

										System.out.println("@@@@@@@@1 altItemPerc["+altItemPerc+"]");
										if( altItemPerc == null || "null".equalsIgnoreCase(altItemPerc) || altItemPerc.trim().length() == 0 )
										{
											altItemPerc = "100";
										}
										System.out.println("@@@@@@@@ altItemPerc["+altItemPerc+"]");
										valueXmlString.append("<alt_item_perc protect = '1'>").append("<![CDATA[" + altItemPerc + "]]>").append("</alt_item_perc>\r\n");
										TimeMRP timeMrp1 = (TimeMRP) dettimeMRParr.get(dettimeCtr);
										System.out.println("Printing timeMrp---" + timeMrp1);

										demand = timeMrp1.getDemand();
										supply = timeMrp1.getSupply();
										planSupply = timeMrp1.getPlanSupply();
										runningDemand = timeMrp1.getRunningDemand();
										runningSupply = timeMrp1.getRunningSupply();
										runningPlanSupply = timeMrp1.getRunningPlanSupply();
										independentDemand = timeMrp1.getIndependentDemand();
										//dueDateStr = simpleDateFormat.format(timeMrp1.getDueDate());
										stockQty = timeMrp1.getStockQty();
										othSupply = timeMrp1.getOthSupply();
										pendPOQty = timeMrp1.getPendingPO();
										pendDOQty = timeMrp1.getPendingDO();
										pendIndQty = timeMrp1.getPendingIndent();
										pendDRQty = timeMrp1.getPendingDR();
										String tranId=mapKey.split("#")[0];
										String tranSer=mapKey.split("#")[1];
										String stkKey[]=tranId.split("@");
										//	valueXmlString.append("<supp_detail protect = '1'>");

										//Boolean tranSerflag = tranSerFlag(siteCode+itemCode,IPD_DIST_List,IPD_INDENT_List,IPD_INDEPENDENT_List,IPD_MPS_ORDER_List);
										System.out.println("@@@@@@@@@tranSer2["+tranSer2+"]itemCode["+itemCode+"]tranSer["+tranSer+"]");  // cpatil on 20/03/14

										sourceSupplyFlag="";

										//System.out.println("@@@@@@@@@["+itemCode+"]tranSerflag["+tranSerflag+"]tranSer2["+tranSer2+"]");
										//if( tranSerflag == true )
										//{
										//	sourceSupplyFlag = "P";
										//sourceSupplyMap.put("planned", "P");
										//}

										Boolean tranSerflag = tranSerFlag(siteCode+itemCode,IPD_DIST_List,IPD_INDENT_List,IPD_INDEPENDENT_List,IPD_MPS_ORDER_List);
										sourceSupplyFlag="";
										System.out.println("@@@@@@@@@["+itemCode+"]tranSerflag["+tranSerflag+"]tranSer2["+tranSer2+"]");
										if( tranSerflag == true )
										{
											sourceSupplyFlag = "P";
										}
										if( "Stock".equalsIgnoreCase(tranSer2) ||  "Stock".equalsIgnoreCase(tranSer)  )
										{
											sourceSupplyFlag = sourceSupplyFlag + "S";
										}
										if("Work Order".equalsIgnoreCase(tranSer2) || "Dist Order".equalsIgnoreCase(tranSer2) || "Dist Order".equalsIgnoreCase(tranSer2) || "Purchase Order".equalsIgnoreCase(tranSer2) || "Indent".equalsIgnoreCase(tranSer2)
												|| "Work Order".equalsIgnoreCase(tranSer) || "Dist Order".equalsIgnoreCase(tranSer) || "Dist Order".equalsIgnoreCase(tranSer) || "Purchase Order".equalsIgnoreCase(tranSer) || "Indent".equalsIgnoreCase(tranSer))
										{
											sourceSupplyFlag = sourceSupplyFlag + "W";
										}

										/*
										if( "Stock".equalsIgnoreCase(tranSer2) ||  "Stock".equalsIgnoreCase(tranSer)  )
										{
											sourceSupplyFlag = "S";
											//sourceSupplyMap.put("stock", "S");
										}
										//if("Work Order".equalsIgnoreCase(tranSer2) || "Dist Issue".equalsIgnoreCase(tranSer2) || "Dist Receipt".equalsIgnoreCase(tranSer2) || "Purchase Order".equalsIgnoreCase(tranSer2) || "Indent".equalsIgnoreCase(tranSer2))
										else
										{
											sourceSupplyFlag = "W";
											//sourceSupplyMap.put("wip", "W");
										}
										 */

										/*
										if( isBomReplace )
										{
											System.out.println("@@@@@@@@ tran ser isBomReplace["+tranSer2+"]tranSer["+tranSer+"]");
											if("Work Order".equalsIgnoreCase(tranSer2) || "Dist Issue".equalsIgnoreCase(tranSer2) || "Dist Receipt".equalsIgnoreCase(tranSer2) || "Purchase Order".equalsIgnoreCase(tranSer2) || "Indent".equalsIgnoreCase(tranSer2))
											{
												sourceSupplyFlag = sourceSupplyFlag + "P";
											}
											else
											{
												sourceSupplyFlag = sourceSupplyFlag + "S";
											}	
										}
										 */
										System.out.println("@@@@@@@@@@@@@@050115 9785 itemCode["+itemCode+"]:::sourceSupplyFlag["+sourceSupplyFlag+"]");

										valueXmlString.append("<source_supply protect = '1'>").append("<![CDATA[" + sourceSupplyFlag + "]]>").append("</source_supply>\r\n");
										if(isDetailReq)  // added by cpatil on 27/08/14 for displaying diffenrent color for new planned
										{
											valueXmlString.append("<new_planned_supply protect = '1'>").append("N").append("</new_planned_supply>\r\n");     // added by cpatil on 27/08/14 for displaying diffenrent color for new planned
										}
										//cpatil-25/08/14-System.out.println("@@@@@@@@@@@@@@@["+itemCode+"] sourceSupplyFlag["+sourceSupplyFlag+"] ");
										tranSer2="";



										if("Stock".equalsIgnoreCase(tranSer))
										{
											System.out.println("@@@@@@@@@050115 inside Stock---stkKey.length["+stkKey.length+"]stkKey["+stkKey+"]");
											if(stkKey.length>0)
											{
												System.out.println("@@@@@@@@050115 9780 site_code["+stkKey[0]+"]item_code["+stkKey[1]+"]lot_no["+stkKey[2]+"]lot_sl["+stkKey[3]+"]loc_code["+stkKey[4]+"]");
												valueXmlString.append("<site_code protect = '1'>").append("<![CDATA[" + stkKey[0] + "]]>").append("</site_code>\r\n");
												valueXmlString.append("<item_code protect = '1'>").append("<![CDATA[" + stkKey[1] + "]]>").append("</item_code>\r\n");
												valueXmlString.append("<item_code_descr protect = '1'>").append("<![CDATA[" + setDescription("descr","item","item_code",stkKey[1],conn) + "]]>").append("</item_code_descr>\r\n");
												valueXmlString.append("<lot_no protect = '1'>").append("<![CDATA[" + stkKey[2] + "]]>").append("</lot_no>\r\n");
												valueXmlString.append("<lot_sl protect = '1'>").append("<![CDATA[" + stkKey[3] + "]]>").append("</lot_sl>\r\n");
												valueXmlString.append("<loc_code protect = '1'>").append("<![CDATA[" + stkKey[4] + "]]>").append("</loc_code>\r\n");
												valueXmlString.append("<alloc_pref protect = '1'>").append("<![CDATA[" + checkNull(stkKey[5]) + "]]>").append("</alloc_pref>\r\n");
												valueXmlString.append("<unit protect = '1'>").append("<![CDATA[" + setDescription("unit", "item", "item_code", stkKey[1], conn) + "]]>").append("</unit>\r\n");
												valueXmlString.append("<parent_item protect = '1'>").append("<![CDATA[" + itemCode + "]]>").append("</parent_item>\r\n");

												System.out.println("@@@@8035:originalOrAltitem["+originalOrAltitem+"]itemCode["+itemCode+"]stkKey[1]["+stkKey[1]+"]itemCodeParent["+itemCodeParent+"]parentItemMap["+parentItemMap+"]itemWorkOrderMap["+itemWorkOrderMap+"]");
												//System.out.println("@@@@@@@@9874:::parentItemMap["+parentItemMap+"]itemWorkOrderMap["+itemWorkOrderMap+"]");
												if("A".equalsIgnoreCase(originalOrAltitem))
												{
													//String prevItemValue = parentItemMap.get(itemCodeParent)==null?"":parentItemMap.get(itemCodeParent).toString(); 
													valueXmlString.append("<previous_item protect = '1'>").append("<![CDATA[" + prevItemValue + "]]>").append("</previous_item>\r\n");

													//String prevItemValue = parentItemMap.get(itemCode)==null?"":parentItemMap.get(itemCode).toString(); 
													//valueXmlString.append("<previous_item protect = '1'>").append("<![CDATA[" + itemCodeParent + "]]>").append("</previous_item>\r\n");

													String itemCodeParentBom = parentItemMap.get(itemCodeParent)==null?"":parentItemMap.get(itemCodeParent).toString();	

													String prevItemWorder = itemWorkOrderMap.get(itemCodeParentBom)==null?"":itemWorkOrderMap.get(itemCodeParentBom).toString();	
													//valueXmlString.append("<prev_item_worder protect = '1'>").append("<![CDATA[" + prevItemWorder + "]]>").append("</prev_item_worder>\r\n");
													valueXmlString.append("<prev_item_worder protect = '1'>").append("<![CDATA[]]>").append("</prev_item_worder>\r\n");
													//cpatil-25/08/14-System.out.println("@@@@8047:prevItemValue["+prevItemValue+"]itemCodeParentBom["+itemCodeParentBom+"]prevItemWorder["+prevItemWorder+"]parentItemMap["+parentItemMap+"]itemWorkOrderMap["+itemWorkOrderMap+"]");	
												}
												else
												{	
													System.out.println("@@@@@@@@9874:::parentItemMap["+parentItemMap+"]itemWorkOrderMap["+itemWorkOrderMap+"]");
													//String prevItemValue = parentItemMap.get(stkKey[1])==null?"":parentItemMap.get(stkKey[1]).toString(); 
													valueXmlString.append("<previous_item protect = '1'>").append("<![CDATA[" + prevItemValue + "]]>").append("</previous_item>\r\n");
													//valueXmlString.append("<prev_item_worder protect = '1'>").append("<![CDATA[" + (itemWorkOrderMap.get(prevItemValue)==null?"":itemWorkOrderMap.get(prevItemValue).toString()) + "]]>").append("</prev_item_worder>\r\n");
													valueXmlString.append("<prev_item_worder protect = '1'>").append("<![CDATA[]]>").append("</prev_item_worder>\r\n");
													//cpatil-25/08/14-System.out.println("@@@@8054:prevItemValue["+prevItemValue+"]parentItemMap["+parentItemMap+"]itemWorkOrderMap["+itemWorkOrderMap+"]");
												}

												valueXmlString.append("<supply protect = '1'>").append("<![CDATA[" + round(supply, 3) + "]]>").append("</supply>\r\n");
												valueXmlString.append("<plan_supply protect = '1'>").append("0").append("</plan_supply>\r\n");

											}
										}
										else
										{               //setDescription("descr","item","item_code",stkKey[1])
											valueXmlString.append("<site_code protect = '1'>").append("<![CDATA[" + siteCode + "]]>").append("</site_code>\r\n");
											valueXmlString.append("<item_code protect = '1'>").append("<![CDATA[" + itemCode + "]]>").append("</item_code>\r\n");
											valueXmlString.append("<item_code_descr protect = '1'>").append("<![CDATA[" + setDescription("descr","item","item_code",itemCode,conn) + "]]>").append("</item_code_descr>\r\n");
											valueXmlString.append("<tran_id protect = '1'>").append("<![CDATA[" + stkKey[0] + "]]>").append("</tran_id>\r\n");
											valueXmlString.append("<line_no protect = '1'>").append("<![CDATA[" + stkKey[1] + "]]>").append("</line_no>\r\n");
											valueXmlString.append("<unit protect = '1'>").append("<![CDATA[" + setDescription("unit", "item", "item_code", itemCode, conn) + "]]>").append("</unit>\r\n");

											valueXmlString.append("<previous_item protect = '1'>").append("  ").append("</previous_item>\r\n");
											valueXmlString.append("<prev_item_worder protect = '1'>").append(" ").append("</prev_item_worder>\r\n");
											//planned_quantity //added for test
											valueXmlString.append("<planned_quantity protect = '1'>").append("<![CDATA[" + getRequiredDecimal(othSupply, 3) + "]]>").append("</planned_quantity>\r\n");
											valueXmlString.append("<plan_supply protect = '1'>").append("<![CDATA[" + getRequiredDecimal(othSupply, 3) + "]]>").append("</plan_supply>\r\n");
											valueXmlString.append("<supply protect = '1'>").append("0").append("</supply>\r\n");	
										}
										valueXmlString.append("<tran_ser protect = '1'>").append("<![CDATA[" + tranSer + "]]>").append("</tran_ser>\r\n");

										//	valueXmlString.append("</supp_detail>");

										valueXmlString.append("<demand protect = '1'>").append("<![CDATA[" + getRequiredDecimal(demand, 3) + "]]>").append("</demand>\r\n");
										if(!isDetailReq)
										{
											valueXmlString.append("<supply protect = '1'>").append("<![CDATA[" + round(supply, 3) + "]]>").append("</supply>\r\n");
											valueXmlString.append("<plan_supply protect = '1'>").append("<![CDATA[" + getRequiredDecimal(planSupply, 3) + "]]>").append("</plan_supply>\r\n");
										}
										valueXmlString.append("<running_demand protect = '1'>").append("<![CDATA[" + getRequiredDecimal(runningDemand, 3) + "]]>").append("</running_demand>\r\n");
										valueXmlString.append("<running_supply protect = '1'>").append("<![CDATA[" + getRequiredDecimal(runningSupply, 3) + "]]>").append("</running_supply>\r\n");
										valueXmlString.append("<running_plan_supply protect = '1'>").append("<![CDATA[" + getRequiredDecimal(runningPlanSupply, 3) + "]]>").append("</running_plan_supply>\r\n");
										valueXmlString.append("<independent_demand protect = '1'>").append("<![CDATA[" + getRequiredDecimal(independentDemand, 3) + "]]>").append("</independent_demand>\r\n");
										valueXmlString.append("<stock_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(stockQty, 3) + "]]>").append("</stock_qty>\r\n");
										valueXmlString.append("<oth_supply protect = '1'>").append("<![CDATA[" + getRequiredDecimal(othSupply, 3) + "]]>").append("</oth_supply>\r\n");
										valueXmlString.append("<pending_po protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendPOQty, 3) + "]]>").append("</pending_po>\r\n");
										valueXmlString.append("<pending_do protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendDOQty, 3) + "]]>").append("</pending_do>\r\n");
										valueXmlString.append("<pending_indent protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendIndQty, 3) + "]]>").append("</pending_indent>\r\n");
										valueXmlString.append("<pending_dr protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendDRQty, 3) + "]]>").append("</pending_dr>\r\n");

										valueXmlString.append("<item_code_parent  protect = '1'>").append("<![CDATA["+itemCodeParent+"]]>").append("</item_code_parent>\r\n");  // added by cpatil on 03/05/14 // remove trim()

										if( detadpElement.getAltitemPerc() == null || "null".equalsIgnoreCase(detadpElement.getAltitemPerc())  ||  detadpElement.getAltitemPerc().trim().length() == 0 )
										{											
											valueXmlString.append("<originalOrAltitem  protect = '1'>").append("<![CDATA[" + originalOrAltitem + "]]>").append("</originalOrAltitem>\r\n");  // added by cpatil on 03/05/14
										}
										else
										{
											valueXmlString.append("<originalOrAltitem  protect = '1'>").append("<![CDATA[" + "A" + "]]>").append("</originalOrAltitem>\r\n");  // added by cpatil on 03/05/14
										}
										valueXmlString.append("<due_date1  protect = '1'>").append("").append("</due_date1>\r\n");  // added by cpatil on 03/05/14

										valueXmlString.append("</Detail4>");	
									}

								}				 
							}
						}


						valueXmlString.append("</Detail" + context + ">");
					} //on230115
				}
				if(isRequirement)//Added by Chandrashekar on 11-08-14
				{	

					valueXmlString = new StringBuffer();
					//cpatil-25/08/14-System.out.println("context["+context+"]");
					//reqValueXmlString = new StringBuffer("<?xml version = \"1.0\"?><Root>\r\n");
					reqCount++;
					reqValueXmlString.append("<Detail" + context + " domID='" + reqCount + "' >\r\n");
					reqValueXmlString.append("<site_code protect = '1'>").append("<![CDATA[" + siteCode + "]]>").append("</site_code>\r\n");
					reqValueXmlString.append("<item_code protect = '1'>").append("<![CDATA[" + itemCode + "]]>").append("</item_code>\r\n");
					reqValueXmlString.append("<supp_sour protect = '1'>").append("<![CDATA[" + suppSour + "]]>").append("</supp_sour>\r\n");
					reqValueXmlString.append("<demand protect = '1'>").append("<![CDATA[" + getRequiredDecimal(demandSum, 3) + "]]>").append("</demand>\r\n");
					reqValueXmlString.append("<supply protect = '1'>").append("<![CDATA[" + round(supplySum, 3) + "]]>").append("</supply>\r\n");
					reqValueXmlString.append("<due_date protect = '1'>").append("<![CDATA[" + dueDateStr + "]]>").append("</due_date>\r\n");
					reqValueXmlString.append("<plan_supply protect = '1'>").append("<![CDATA[" + getRequiredDecimal(planSupplySum, 3) + "]]>").append("</plan_supply>\r\n");
					reqValueXmlString.append("<running_demand protect = '1'>").append("<![CDATA[" + getRequiredDecimal(runningDemandSum, 3) + "]]>").append("</running_demand>\r\n");
					reqValueXmlString.append("<running_supply protect = '1'>").append("<![CDATA[" + getRequiredDecimal(runningSupplySum, 3) + "]]>").append("</running_supply>\r\n");
					reqValueXmlString.append("<running_plan_supply protect = '1'>").append("<![CDATA[" + getRequiredDecimal(runningPlanSupplySum, 3) + "]]>").append("</running_plan_supply>\r\n");
					reqValueXmlString.append("<independent_demand protect = '1'>").append("<![CDATA[" + getRequiredDecimal(independentDemand, 3) + "]]>").append("</independent_demand>\r\n");
					if (bomCode != null)
					{
						reqValueXmlString.append("<bom_code protect = '1'>").append("<![CDATA[" + bomCode + "]]>").append("</bom_code>\r\n");
					} else
					{
						reqValueXmlString.append("<bom_code protect = '1'>").append("<![CDATA[" + "" + "]]>").append("</bom_code>\r\n");
					}
					reqValueXmlString.append("<order_opt protect = '1'>").append("<![CDATA[" + orderOpt + "]]>").append("</order_opt>\r\n");
					reqValueXmlString.append("<batch_qty_type protect = '1'>").append("<![CDATA[" + batchQtyType + "]]>").append("</batch_qty_type>\r\n");
					reqValueXmlString.append("<unit protect = '1'>").append("<![CDATA[" + unit + "]]>").append("</unit>\r\n");
					reqValueXmlString.append("<min_order_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(minOrderQty, 3) + "]]>").append("</min_order_qty>\r\n");
					reqValueXmlString.append("<integral_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(integralQty, 3) + "]]>").append("</integral_qty>\r\n");
					reqValueXmlString.append("<max_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(maxQty, 3) + "]]>").append("</max_qty>\r\n");
					reqValueXmlString.append("<min_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(minQty, 3) + "]]>").append("</min_qty>\r\n");
					reqValueXmlString.append("<reorder_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(reorderQty, 3) + "]]>").append("</reorder_qty>\r\n");
					reqValueXmlString.append("<yield_perc protect = '1'>").append("<![CDATA[" + getRequiredDecimal(yieldPerc, 2) + "]]>").append("</yield_perc>\r\n");
					reqValueXmlString.append("<min_plan_perc protect = '1'>").append("<![CDATA[" + getRequiredDecimal(minPlanPerc, 2) + "]]>").append("</min_plan_perc>\r\n");
					reqValueXmlString.append("<batch_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(batchQty, 3) + "]]>").append("</batch_qty>\r\n");
					reqValueXmlString.append("<purc_rate protect = '1'>").append("<![CDATA[" + getRequiredDecimal(purcRate, 3) + "]]>").append("</purc_rate>\r\n");
					reqValueXmlString.append("<pur_lead_time protect = '1'>").append("<![CDATA[" +  getRequiredDecimal(purLeadTime, 3) + "]]>").append("</pur_lead_time>\r\n");
					reqValueXmlString.append("<qc_lead_time protect = '1'>").append("<![CDATA[" + getRequiredDecimal(qcLeadTime, 3) + "]]>").append("</qc_lead_time>\r\n");
					reqValueXmlString.append("<mfg_lead_time protect = '1'>").append("<![CDATA[" + getRequiredDecimal(mfgLeadTime, 3) + "]]>").append("</mfg_lead_time>\r\n");
					reqValueXmlString.append("<description protect = '1'>").append("<![CDATA[" + desc + "]]>").append("</description>\r\n");	
					reqValueXmlString.append("<stock_qty protect = '1'>").append("<![CDATA[" + getRequiredDecimal(stockQty, 3) + "]]>").append("</stock_qty>\r\n");
					reqValueXmlString.append("<oth_supply protect = '1'>").append("<![CDATA[" + getRequiredDecimal(othSupply, 3) + "]]>").append("</oth_supply>\r\n");
					reqValueXmlString.append("<pending_po protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendPOQtySum, 3) + "]]>").append("</pending_po>\r\n");
					reqValueXmlString.append("<pending_do protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendDOQty, 3) + "]]>").append("</pending_do>\r\n");
					reqValueXmlString.append("<pending_indent protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendIndQtySum, 3) + "]]>").append("</pending_indent>\r\n");
					reqValueXmlString.append("<pending_dr protect = '1'>").append("<![CDATA[" + getRequiredDecimal(pendDRQty, 3) + "]]>").append("</pending_dr>\r\n");
					reqValueXmlString.append("<quarntine_stk protect = '1'>").append("<![CDATA[" + getRequiredDecimal(qtStk, 3) + "]]>").append("</quarntine_stk>\r\n");
					reqValueXmlString.append("</Detail" + context + ">");
				}



			}


			//}


			valueXmlString.append("</Root>");
			reqValueXmlString.append("</Root>");
			System.out.println("Printing reqValueXmlString----" + reqValueXmlString);
			System.out.println("Printing valueXmlString----2---" + valueXmlString);
			System.out.println("Printing context-------" + context);
			// context=2;
			//if (context != null && context.trim().length() > 0 && (context.equals("2") ||context.equals("3")))   //Commented by Manoj dtd 06/06/2014 to check on boolean value

			//cpatil-25/08/14-System.out.println("isWizard-------"+isWizard);
			if(isWizard)
			{
				resultString = valueXmlString.toString();
			} else
			{
				resultString = retTabSepStrBuff.toString();
			}
			if(isRequirement)//Added by Chandrashekar on 11-08-14
			{
				resultString = reqValueXmlString.toString();
			}
			System.out.println("resultString---" + resultString);
			// resultString = valueXmlString.toString();
			// System.out.println("End of collected datas......");
			// resultString = retTabSepStrBuff.toString();
		} catch (SQLException se)
		{
			System.out.println("SQLException :RunMRPPrcEJB :setValuesInBrow():" + se.getMessage() + ":");
			se.printStackTrace();
			throw new ITMException(se);
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :setValuesInBrow():" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		} finally
		{
			try
			{
				conn.close();
				conn = null;
				retTabSepStrBuff = null;
				valueXmlString = null;
				reqValueXmlString = null;
			} catch (Exception e)
			{
			}
		}
		return resultString;
	}



	private String getItemType(String suppSour) throws SQLException 
	{

		String value="";

		suppSour = checkNull(suppSour);
		//System.out.println("@@@@@@@@@ inside getItemType suppSour["+suppSour+"]");
		//		if( flag == true )
		//		{
		//			value="0";
		//		}
		//		else 
		if("M".equalsIgnoreCase(suppSour.trim()) )  // M
		{
			value="2";
			//System.out.println("@@@@@@@@@ inside M suppSour["+suppSour+"]value["+value+"]");
		}
		else if("P".equalsIgnoreCase(suppSour) )
		{
			value="3";
			//System.out.println("@@@@@@@@@ inside P suppSour["+suppSour+"]value["+value+"]");
		}
		else
		{
			value="1";
			//System.out.println("@@@@@@@@@ inside else suppSour["+suppSour+"]value["+value+"]");
		}
		//System.out.println("return --- > suppSour["+suppSour+"]value["+value+"]");
		return value;
	}




	private void getParentItemList(String itemCode, HashMap map, HashMap bomMap, HashMap tempBomMap)  //parentItemMap , itemBomMap ,bomMap
	{
		String temp = "";
		String tempBomCode = "";
		System.out.println("inside calculate..["+itemCode+"].parentItemMap["+map+"]itemBomMap["+bomMap+"]bomMap["+tempBomMap+"]");
		if( bomMap.containsKey(itemCode))
		{
			tempBomCode = bomMap.get(itemCode).toString()== null?"":bomMap.get(itemCode).toString();
		}
		if( map.containsKey(itemCode))
		{
			temp = map.get(itemCode).toString()==null?"":map.get(itemCode).toString();
			finalString =  temp.trim() + "("+tempBomCode+")      -->" + finalString.trim() ;
		}
		else
		{
			temp="";
		}
		//System.out.println("@@@@ itemCode["+itemCode+"]temp["+temp+"]");
		if( temp != null &&  ( ! "".equalsIgnoreCase(temp)) )
		{
			getParentItemList(temp,map,bomMap,tempBomMap);
		}
		else
		{
			//return "";
		}
		//return temp;
	}


	private Boolean tranSerFlag(String value, ArrayList iPD_DIST_List,ArrayList iPD_INDENT_List, ArrayList iPD_INDEPENDENT_List,	ArrayList iPD_MPS_ORDER_List) 
	{
		//String sourceSupplyFlag="";
		Boolean flag = false;
		//cpatil-25/08/14-System.out.println("@@@@@@@@@cpatil--value["+value+"]--iPD_DIST_List["+iPD_DIST_List+"]@@@@iPD_INDENT_List["+iPD_INDENT_List+"]@@@@iPD_INDEPENDENT_List["+iPD_INDEPENDENT_List+"]@@@@iPD_MPS_ORDER_List["+iPD_MPS_ORDER_List+"]@@@@");
		if(iPD_DIST_List.contains(value) || iPD_INDENT_List.contains(value) || iPD_INDEPENDENT_List.contains(value) || iPD_MPS_ORDER_List.contains(value))
		{
			flag = true;
		}

		//cpatil-25/08/14-System.out.println("@@@@@cpatiltranSerFlag["+flag+"]");
		return flag;
	}

	private String setDescription(String field, String table,
			String field2, String value,Connection conn) throws SQLException 
			{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String descr="",sql="";

		sql = "select "+ field +" from "+ table +" where "+ field2 +" = ? ";
		pstmt = conn.prepareStatement(sql);
		pstmt.setString( 1, value );
		rs = pstmt.executeQuery();
		if (rs.next())
		{
			descr = checkNull(rs.getString(1));
		}
		rs.close();rs = null;
		pstmt.close();pstmt = null;  

		//cpatil-25/08/14-System.out.println("@@@@@@@@cpatil-Descr["+descr+"]");

		return descr;
			}

	/*public double getRequiredDecimal(double actVal, int prec)
	{
		NumberFormat numberFormat = NumberFormat.getIntegerInstance();
		Double DoubleValue = new Double(actVal);
		numberFormat.setMaximumFractionDigits(3);
		String strValue = numberFormat.format(DoubleValue);
		strValue = strValue.replaceAll(",", "");
		double reqVal = Double.parseDouble(strValue);
		return reqVal;
	}*/

	public String getRequiredDecimal(double actVal, int prec)//Added by chandrashekar on 11-08-14
	{
		String fmtStr = "############0";
		String strValue = null;
		if (prec > 0)
		{
			fmtStr = fmtStr + "." + "000000000".substring(0, prec);
		}
		DecimalFormat decFormat = new DecimalFormat(fmtStr);
		return decFormat.format(actVal);
	}




	private void Write2XSL() throws ITMException
	{
		String errCode = "", date;
		String errString = "";
		String resultString = "";
		StringBuffer retTabSepStrBuff = new StringBuffer();

		String siteCode = "0";
		String itemCode = "0";
		String bomCode = "0";
		String suppSour = "0";
		String orderOpt = "0";
		String dueDateStr = "0";
		String batchQtyType = "0";
		String unit = "0";
		String desc = null;

		double demand = 0;
		double supply = 0;
		double planDemand = 0;
		double planSupply = 0;
		double runningDemand = 0;
		double runningSupply = 0;
		double runningPlanSupply = 0;
		double independentDemand = 0;
		double minOrderQty = 0;
		double integralQty = 0;
		double maxQty = 0;
		double minQty = 0;
		double reorderQty = 0;
		double yieldPerc = 100;
		double minPlanPerc = 0;
		double batchQty = 0;
		double purcRate = 0;
		int purLeadTime = 0;
		int qcLeadTime = 0;
		int mfgLeadTime = 0;
		boolean flag = true;
		// 12/04/10 Manoharan MF90BHU001
		double stockQty = 0;
		double othSupply = 0;
		// end 12/04/10 manoharan MF90BHU001

		// Variables declared by gulzar on 4/18/2012
		double pendPOQty = 0;
		double pendDOQty = 0;
		double pendIndQty = 0;
		double pendDRQty = 0;
		// End changes by gulzar on 4/18/2012

		ADPElement adpElement = null;
		java.sql.Timestamp dueDate;
		HSSFCell cell = null;
		HSSFRow row = null;
		HSSFCellStyle cellStyle = null;
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

		final String[] titles =
		{ "Site Code", "Item Code", "Item Description", "Supply Source", "Demand", "Supply", "Stock Qty", "Other Supply", "Pending PO", "Pending DO", "Pending Indent", "Pending DR", "Due Date", "Plan Supply", "Running Demand", "Running Supply", "Running Plan Supply", "Independent Demand", "Bom Code", "Order Opt", "Batch Qty Type", "Unit", "Min Order Qty", "Integral Qty", "Max Qty", "Min Qty", "Reorder Qty", "Yield Perc", "Min Plan %", "Batch Qty", "Purc Rate", "Pur Lead Time", "QC Lead Time", "MFG Lead Time" };
		// 30
		try
		{

			HSSFWorkbook wb;
			wb = new HSSFWorkbook();
			HSSFSheet sheet = wb.createSheet("MRPRun");
			HSSFRow titleRow = sheet.createRow(0);
			titleRow.setHeightInPoints(45);
			cellStyle = wb.createCellStyle();

			HSSFCellStyle style = wb.createCellStyle();
			style.setBorderTop((short) 6); // double lines border
			style.setBorderBottom((short) 1); // single line border
			style.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
			HSSFFont font = wb.createFont();
			font.setFontName(HSSFFont.FONT_ARIAL);
			font.setFontHeightInPoints((short) 20);
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			font.setColor(HSSFColor.BLUE.index);
			style.setFont(font);

			HSSFCell titleCell = titleRow.createCell((short) 0);
			titleCell.setCellValue(new HSSFRichTextString("MRP - Material Requirements"));
			titleCell.setCellStyle(style);
			sheet.autoSizeColumn((short) 1);

			// titleCell.setCellStyle(styles.get("title"));

			HSSFRow headerRow = sheet.createRow(1);
			headerRow.setHeightInPoints(40);
			HSSFCell headerCell;

			for (int cellCtr = 0; cellCtr < titles.length; cellCtr++)
			{
				headerCell = headerRow.createCell((short) cellCtr);
				headerCell.setCellValue(titles[cellCtr]);
			}

			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
			int insertRow = 2;
			for (int adpeCount = 0; adpeCount < adpeList.size(); adpeCount++)
			{

				flag = true;
				adpElement = (ADPElement) adpeList.get(adpeCount);

				siteCode = adpElement.getSiteCode();
				itemCode = adpElement.getItemCode();
				maxQty = adpElement.getMaxQty();
				minQty = adpElement.getMinQty();
				suppSour = adpElement.getSuppSour();
				orderOpt = adpElement.getOrderOpt();
				bomCode = adpElement.getBomCode();
				unit = adpElement.getUnit();
				batchQtyType = adpElement.getBatchQtyType();
				minOrderQty = adpElement.getMinOrderQty();
				integralQty = adpElement.getIntegralQty();
				reorderQty = adpElement.getReoQty();
				yieldPerc = adpElement.getYieldPerc();
				minPlanPerc = adpElement.getMinPlanPerc();
				batchQty = adpElement.getBatchQty();
				purcRate = adpElement.getPurcRate();
				qcLeadTime = adpElement.getQcLeadTime();
				purLeadTime = adpElement.getPurLeadTime();
				mfgLeadTime = adpElement.getMfgLeadTime();
				desc = adpElement.getItemDescr();

				ArrayList timeMRParr = adpElement.getTimeMrpList();
				for (int timeCtr = 0; timeCtr < timeMRParr.size(); timeCtr++)
				{
					TimeMRP timeMrp = (TimeMRP) timeMRParr.get(timeCtr);
					dueDate = timeMrp.getDueDate();
					demand = timeMrp.getDemand();
					supply = timeMrp.getSupply();
					planSupply = timeMrp.getPlanSupply();
					runningDemand = timeMrp.getRunningDemand();
					runningSupply = timeMrp.getRunningSupply();
					runningPlanSupply = timeMrp.getRunningPlanSupply();
					independentDemand = timeMrp.getIndependentDemand();
					dueDateStr = simpleDateFormat.format(timeMrp.getDueDate());
					// 12/04/10 manoharan MF90BHU001
					stockQty = timeMrp.getStockQty();
					othSupply = timeMrp.getOthSupply();
					// end 12/04/10 manoharan MF90BHU001

					// Changes made by Gulzar on 4/18/2012
					pendPOQty = timeMrp.getPendingPO();
					pendDOQty = timeMrp.getPendingDO();
					pendIndQty = timeMrp.getPendingIndent();
					pendDRQty = timeMrp.getPendingDR();
					// End changes by Gulzar on 4/18/2012

					insertRow++;
					row = sheet.createRow(insertRow);
					for (int j = 0; j < titles.length; j++)
					{
						cell = row.createCell((short) j);
					}

					// if(flag)
					// {
					row.getCell(0).setCellValue(siteCode);
					row.getCell(1).setCellValue(itemCode);
					row.getCell(2).setCellValue(desc);
					row.getCell(3).setCellValue(suppSour);
					// }

					row.getCell(4).setCellValue(demand);
					row.getCell(5).setCellValue(supply);
					row.getCell(6).setCellValue(stockQty);
					row.getCell(7).setCellValue(othSupply);

					// Changed by Gulzar on 4/27/2012
					row.getCell(8).setCellValue(pendPOQty);
					row.getCell(9).setCellValue(pendDOQty);
					row.getCell(10).setCellValue(pendIndQty);
					row.getCell(11).setCellValue(pendDRQty);
					// End Changes by Gulzar on 4/27/2012

					cell = row.getCell(12);
					cell.setCellValue(HSSFDateUtil.getExcelDate(dueDate));
					cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
					cell.setCellStyle(cellStyle);

					row.getCell(13).setCellValue(planSupply);
					row.getCell(14).setCellValue(runningDemand);
					row.getCell(15).setCellValue(runningSupply);
					row.getCell(16).setCellValue(runningPlanSupply);
					row.getCell(17).setCellValue(independentDemand);

					// if(flag)
					// {
					row.getCell(18).setCellValue(bomCode);
					row.getCell(19).setCellValue(orderOpt);
					row.getCell(20).setCellValue(batchQtyType);
					row.getCell(21).setCellValue(unit);
					row.getCell(22).setCellValue(minOrderQty);
					row.getCell(23).setCellValue(integralQty);
					row.getCell(24).setCellValue(maxQty);
					row.getCell(25).setCellValue(minQty);
					row.getCell(26).setCellValue(reorderQty);
					row.getCell(27).setCellValue(yieldPerc);
					row.getCell(28).setCellValue(minPlanPerc);
					row.getCell(29).setCellValue(batchQty);
					row.getCell(30).setCellValue(purcRate);
					row.getCell(31).setCellValue(purLeadTime);
					row.getCell(32).setCellValue(qcLeadTime);
					row.getCell(33).setCellValue(mfgLeadTime);
					// }

					// flag = false; // 25/02/11 manoharan commented as BTPL
					// want the same to be repeated in the excel file
				}
			}

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document dom = db.parse("/IBASEHOME/ibase.xml");
			String mrpOutputLocation = "";
			try
			{
				mrpOutputLocation = dom.getElementsByTagName("mrp_output_location").item(0).getFirstChild().getNodeValue();
			} 
			catch (Exception e)
			{
				System.out.println("Exception :RunMRPPrcEJB :setValuesInBrow():" + e.getMessage() + ":");
				e.printStackTrace();
				throw new ITMException(e);
			}
			Calendar cal = Calendar.getInstance();
			String curTime = (new java.text.DecimalFormat("0000")).format(cal.get(Calendar.YEAR)) + (new java.text.DecimalFormat("00")).format(cal.get(Calendar.MONTH) + 1) + (new java.text.DecimalFormat("00")).format(cal.get(Calendar.DAY_OF_MONTH)) + (new java.text.DecimalFormat("00")).format(cal.get(Calendar.HOUR_OF_DAY)) + (new java.text.DecimalFormat("00")).format(cal.get(Calendar.MINUTE));

			String fileName = mrpOutputLocation + File.separator + "MRPRun_" + curTime + ".xls";
			dom = null;
			db = null;
			dbf = null;
			File outputDir = new File(fileName);
			File subDirFile = null;

			if (!outputDir.exists())
			{
				String subDirName = "";

				if (mrpOutputLocation.indexOf("\\") > 0)
				{
					String subDirs[] = mrpOutputLocation.split("\\\\");
					subDirName = subDirs[0];
					//cpatil-25/08/14-System.out.println("windows stype path");
					for (int idx = 1; idx < subDirs.length; idx++)
					{
						subDirName = subDirName + File.separator + subDirs[idx];
						System.out.println("subDirs[ idx ] [" + subDirs[idx] + "]");
					}
				} else
				{
					String subDirs[] = mrpOutputLocation.split("/");
					subDirName = subDirs[0];
					//cpatil-25/08/14-System.out.println("Unix style path");
					for (int idx = 1; idx < subDirs.length; idx++)
					{
						subDirName = subDirName + File.separator + subDirs[idx];
						System.out.println("subDirs[ idx ] [" + subDirs[idx] + "]");
					}

				}
				subDirFile = new File(subDirName);
				System.out.println("File path [" + subDirName + "]");
				if (!subDirFile.exists())
				{
					System.out.println("creating folders [" + subDirName + "]");
					subDirFile.mkdirs();
				}
			}

			// Write the output to a file
			// if(wb instanceof XSSFWorkbook) file += "x";
			FileOutputStream out = new FileOutputStream(fileName);
			wb.write(out);
			out.close();

			// System.out.println("End of collected datas......");
			resultString = retTabSepStrBuff.toString();
		} catch (SQLException se)
		{
			System.out.println("SQLException :RunMRPPrcEJB :setValuesInBrow():" + se.getMessage() + ":");
			se.printStackTrace();
			throw new ITMException(se);
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB :setValuesInBrow():" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		} finally
		{
			try
			{
				conn.close();
				conn = null;
				retTabSepStrBuff = null;
			} catch (Exception e)
			{
			}
		}

	}

	// */
	/*
	 * private void Write2XSL() throws ITMException { String errCode = "", date;
	 * String errString = ""; String resultString = ""; StringBuffer
	 * retTabSepStrBuff = new StringBuffer();
	 * 
	 * String siteCode = "0"; String itemCode = "0"; String bomCode = "0";
	 * String suppSour = "0"; String orderOpt = "0"; String dueDateStr = "0";
	 * String batchQtyType = "0"; String unit = "0"; String desc = null;
	 * 
	 * double demand = 0; double supply = 0; double planDemand = 0; double
	 * planSupply = 0; double runningDemand = 0; double runningSupply = 0;
	 * double runningPlanSupply = 0; double independentDemand = 0; double
	 * minOrderQty = 0; double integralQty = 0; double maxQty = 0; double minQty
	 * = 0; double reorderQty = 0; double yieldPerc = 100; double minPlanPerc =
	 * 0; double batchQty = 0; double purcRate = 0; int purLeadTime = 0; int
	 * qcLeadTime = 0; int mfgLeadTime = 0; boolean flag = true; // 12/04/10
	 * Manoharan MF90BHU001 double stockQty = 0; double othSupply = 0; // end
	 * 12/04/10 manoharan MF90BHU001 ADPElement adpElement = null;
	 * java.sql.Timestamp dueDate; HSSFCell cell = null; HSSFRow row = null;
	 * HSSFCellStyle cellStyle = null; SimpleDateFormat sdf = new
	 * SimpleDateFormat("MM/dd/yyyy");
	 * 
	 * final String[] titles = { "Site Code", "Item Code", "Item Description",
	 * "Supply Source", "Demand", "Supply", "Stock Qty", "Other Supply",
	 * "Due Date", "Plan Supply", "Running Demand", "Running Supply",
	 * "Running Plan Supply", "Independent Demand",
	 * "Bom Code","Order Opt","Batch Qty Type"
	 * ,"Unit","Min Order Qty","Integral Qty",
	 * "Max Qty","Min Qty","Reorder Qty","Yield Perc", "Min Plan %","Batch Qty",
	 * "Purc Rate", "Pur Lead Time","QC Lead Time", "MFG Lead Time" }; // 30 try
	 * {
	 * 
	 * HSSFWorkbook wb; wb = new HSSFWorkbook(); HSSFSheet sheet =
	 * wb.createSheet("MRPRun"); HSSFRow titleRow = sheet.createRow(0);
	 * titleRow.setHeightInPoints(45); cellStyle = wb.createCellStyle();
	 * 
	 * HSSFCellStyle style = wb.createCellStyle(); style.setBorderTop((short)
	 * 6); // double lines border style.setBorderBottom((short) 1); // single
	 * line border
	 * style.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index); HSSFFont
	 * font = wb.createFont(); font.setFontName(HSSFFont.FONT_ARIAL);
	 * font.setFontHeightInPoints((short) 20);
	 * font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
	 * font.setColor(HSSFColor.BLUE.index); style.setFont(font);
	 * 
	 * 
	 * 
	 * HSSFCell titleCell = titleRow.createCell((short) 0);
	 * titleCell.setCellValue(new
	 * HSSFRichTextString("MRP - Material Requirements"));
	 * titleCell.setCellStyle(style); sheet.autoSizeColumn((short) 1);
	 * 
	 * 
	 * //titleCell.setCellStyle(styles.get("title"));
	 * 
	 * HSSFRow headerRow = sheet.createRow(1); headerRow.setHeightInPoints(40);
	 * HSSFCell headerCell;
	 * 
	 * for (int cellCtr = 0; cellCtr < titles.length; cellCtr++) { headerCell =
	 * headerRow.createCell((short)cellCtr);
	 * headerCell.setCellValue(titles[cellCtr]); }
	 * 
	 * SimpleDateFormat simpleDateFormat = new
	 * SimpleDateFormat(genericUtility.getApplDateFormat()); int insertRow = 2;
	 * for(int adpeCount=0; adpeCount<adpeList.size(); adpeCount++) {
	 * 
	 * 
	 * flag = true; adpElement = (ADPElement)adpeList.get(adpeCount);
	 * 
	 * siteCode = adpElement.getSiteCode(); itemCode = adpElement.getItemCode();
	 * maxQty = adpElement.getMaxQty(); minQty = adpElement.getMinQty();
	 * suppSour = adpElement.getSuppSour(); orderOpt = adpElement.getOrderOpt();
	 * bomCode = adpElement.getBomCode(); unit = adpElement.getUnit();
	 * batchQtyType = adpElement.getBatchQtyType(); minOrderQty =
	 * adpElement.getMinOrderQty(); integralQty = adpElement.getIntegralQty();
	 * reorderQty = adpElement.getReoQty(); yieldPerc =
	 * adpElement.getYieldPerc(); minPlanPerc = adpElement.getMinPlanPerc();
	 * batchQty = adpElement.getBatchQty(); purcRate = adpElement.getPurcRate();
	 * qcLeadTime = adpElement.getQcLeadTime(); purLeadTime =
	 * adpElement.getPurLeadTime(); mfgLeadTime = adpElement.getMfgLeadTime();
	 * desc = adpElement.getItemDescr();
	 * 
	 * ArrayList timeMRParr = adpElement.getTimeMrpList(); for (int timeCtr = 0;
	 * timeCtr < timeMRParr.size() ; timeCtr++) { TimeMRP timeMrp =
	 * (TimeMRP)timeMRParr.get(timeCtr); dueDate = timeMrp.getDueDate(); demand
	 * = timeMrp.getDemand(); supply = timeMrp.getSupply(); planSupply =
	 * timeMrp.getPlanSupply(); runningDemand = timeMrp.getRunningDemand();
	 * runningSupply = timeMrp.getRunningSupply(); runningPlanSupply =
	 * timeMrp.getRunningPlanSupply(); independentDemand =
	 * timeMrp.getIndependentDemand(); dueDateStr =
	 * simpleDateFormat.format(timeMrp.getDueDate()); // 12/04/10 manoharan
	 * MF90BHU001 stockQty = timeMrp.getStockQty(); othSupply =
	 * timeMrp.getOthSupply(); // end 12/04/10 manoharan MF90BHU001 insertRow++;
	 * row = sheet.createRow(insertRow); for (int j = 0; j < titles.length; j++)
	 * { cell = row.createCell((short)j); }
	 * 
	 * if(flag) { row.getCell(0).setCellValue(siteCode);
	 * row.getCell(1).setCellValue(itemCode); row.getCell(2).setCellValue(desc);
	 * row.getCell(3).setCellValue(suppSour); }
	 * 
	 * row.getCell(4).setCellValue(demand); row.getCell(5).setCellValue(supply);
	 * row.getCell(6).setCellValue(stockQty);
	 * row.getCell(7).setCellValue(othSupply);
	 * 
	 * cell = row.getCell(8);
	 * cell.setCellValue(HSSFDateUtil.getExcelDate(dueDate));
	 * cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
	 * cell.setCellStyle(cellStyle);
	 * 
	 * row.getCell(9).setCellValue(planSupply);
	 * row.getCell(10).setCellValue(runningDemand);
	 * row.getCell(11).setCellValue(runningSupply);
	 * row.getCell(12).setCellValue(runningPlanSupply);
	 * row.getCell(13).setCellValue(independentDemand);
	 * 
	 * if(flag) { row.getCell(14).setCellValue(bomCode);
	 * row.getCell(15).setCellValue(orderOpt);
	 * row.getCell(16).setCellValue(batchQtyType);
	 * row.getCell(17).setCellValue(unit);
	 * row.getCell(18).setCellValue(minOrderQty);
	 * row.getCell(19).setCellValue(integralQty);
	 * row.getCell(20).setCellValue(maxQty);
	 * row.getCell(21).setCellValue(minQty);
	 * row.getCell(22).setCellValue(reorderQty);
	 * row.getCell(23).setCellValue(yieldPerc);
	 * row.getCell(24).setCellValue(minPlanPerc);
	 * row.getCell(25).setCellValue(batchQty);
	 * row.getCell(26).setCellValue(purcRate);
	 * row.getCell(27).setCellValue(purLeadTime);
	 * row.getCell(28).setCellValue(qcLeadTime);
	 * row.getCell(29).setCellValue(mfgLeadTime); }
	 * 
	 * //flag = false; // 25/02/11 manoharan commented as BTPL want the same to
	 * be repeated in the excel file } }
	 * 
	 * DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	 * DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(
	 * "/IBASEHOME/ibase.xml" ); String mrpOutputLocation = ""; try {
	 * mrpOutputLocation = dom.getElementsByTagName( "mrp_output_location"
	 * ).item(0).getFirstChild().getNodeValue(); } catch (Exception e) {
	 * System.out.println("Exception :RunMRPPrcEJB :setValuesInBrow():" +
	 * e.getMessage() + ":"); e.printStackTrace(); throw new ITMException(e); }
	 * Calendar cal = Calendar.getInstance(); String curTime = ( new
	 * java.text.DecimalFormat( "0000" ) ).format( cal.get(Calendar.YEAR) ) + (
	 * new java.text.DecimalFormat( "00" ) ).format( cal.get(Calendar.MONTH) + 1
	 * ) + ( new java.text.DecimalFormat( "00" ) ).format(
	 * cal.get(Calendar.DAY_OF_MONTH) ) + ( new java.text.DecimalFormat( "00" )
	 * ).format( cal.get(Calendar.HOUR_OF_DAY) ) + ( new
	 * java.text.DecimalFormat( "00" ) ).format( cal.get(Calendar.MINUTE) ) ;
	 * 
	 * 
	 * String fileName = mrpOutputLocation + File.separator+"MRPRun_" + curTime
	 * + ".xls"; dom = null; db = null; dbf = null; File outputDir = new File(
	 * fileName ); File subDirFile = null;
	 * 
	 * if( !outputDir.exists() ) { String subDirName = "";
	 * 
	 * if (mrpOutputLocation.indexOf("\\") > 0) { String subDirs[] =
	 * mrpOutputLocation.split( "\\\\" ); subDirName = subDirs[0];
	 * System.out.println("windows stype path"); for( int idx = 1; idx <
	 * subDirs.length; idx++ ) { subDirName = subDirName + File.separator +
	 * subDirs[ idx ]; System.out.println("subDirs[ idx ] [" + subDirs[ idx ] +
	 * "]"); } } else { String subDirs[] = mrpOutputLocation.split( "/" );
	 * subDirName = subDirs[0]; System.out.println("Unix style path"); for( int
	 * idx = 1; idx < subDirs.length; idx++ ) { subDirName = subDirName +
	 * File.separator + subDirs[ idx ]; System.out.println("subDirs[ idx ] [" +
	 * subDirs[ idx ] + "]"); }
	 * 
	 * } subDirFile = new File( subDirName ); System.out.println("File path [" +
	 * subDirName + "]"); if( !subDirFile.exists() ) {
	 * System.out.println("creating folders [" + subDirName + "]");
	 * subDirFile.mkdirs(); } }
	 * 
	 * 
	 * // Write the output to a file //if(wb instanceof XSSFWorkbook) file +=
	 * "x"; FileOutputStream out = new FileOutputStream(fileName);
	 * wb.write(out); out.close();
	 * 
	 * //System.out.println("End of collected datas......"); resultString =
	 * retTabSepStrBuff.toString(); } catch (SQLException se) {
	 * System.out.println("SQLException :RunMRPPrcEJB :setValuesInBrow():" +
	 * se.getMessage() + ":"); se.printStackTrace(); throw new ITMException(se);
	 * } catch (Exception e) {
	 * System.out.println("Exception :RunMRPPrcEJB :setValuesInBrow():" +
	 * e.getMessage() + ":"); e.printStackTrace(); throw new ITMException(e); }
	 * finally { try { conn.close(); conn = null; retTabSepStrBuff = null; }
	 * catch(Exception e) {} }
	 * 
	 * }
	 */
	private String checkNull(String value)
	{
		if (value == null)
		{
			value = "";
		}
		return value;
	}

	private HashMap<String, ADPElement> getAltItemSupply(String siteCode,String itemCode,String altitemPerc) throws ITMException
	{
		double demand = 0;
		double supply = 0;
		java.sql.Timestamp dueDate = null;
		double stockQty = 0;
		double othSupply = 0;
		double pendPOQty = 0;
		double pendDOQty = 0;
		double pendIndQty = 0;
		double pendDRQty = 0;
		double availStk = 0;
		double quarntineStk = 0;
		Statement stmt = null;
		ResultSet rs = null;
		errString = "";
		String adpQuery = null;
		PreparedStatement pstmt = null;
		String saleOrder = null;
		String lineNo = null;
		String tranId="";
		String tranSer="";
		double prevdemand=0;
		double prevsupply=0;
		double prevstockQty=0;
		double prevothSupply=0;
		double prevpendPOQty=0;
		double prevpendDOQty=0;
		double prevpendIndQty=0;
		double prevpendDRQty=0;
		HashMap<String, ADPElement> detMap=new HashMap<String, ADPElement>();
		ArrayList<HashMap<String, ADPElement>> alist=new ArrayList<HashMap<String,ADPElement>>();
		try
		{
			String sqlFileName = null;
			//sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "demandsupplyDetail";
			sqlFileName = CommonConstants.JBOSSHOME + File.separator + "sql" + File.separator + "altItemStock";

			if ((CommonConstants.DB_NAME).equalsIgnoreCase("db2"))
			{
				String adpQueryOriginal = readFile(sqlFileName + "DB2.sql");
				String strDateFrom = dateFrom.toString();
				strDateFrom = strDateFrom.replaceAll(" ", "-");
				strDateFrom = strDateFrom.replaceAll(":", ".");
				String strDateTo = dateTo.toString();
				strDateTo = strDateTo.replaceAll(" ", "-");
				strDateTo = strDateTo.replaceAll(":", ".");
				adpQuery = adpQueryOriginal;
				adpQuery = adpQuery.replaceAll("@sitecode@", siteCode);
				//adpQuery = adpQuery.replaceAll("@itemcode@", itemCode);
				adpQuery = adpQuery.replaceAll("@itemcode@", siteCode+itemCode);
				adpQuery = adpQuery.replaceAll("@fromdate@", dateFromString);
				adpQuery = adpQuery.replaceAll("@todate@", dateToString);
				adpQuery = adpQuery.replaceAll("@ordtypes@", standingOrdTypes);
				adpQuery = adpQuery.replaceAll("@madetoorder@", madeToOrder);
				adpQuery = adpQuery.replaceAll("@madetostock@", madeToStock);
				// 01-10-2007 manoharan
				adpQuery = adpQuery.replaceAll("@rundate@", runDateString);
				// end 01-10-2007 manoharan
			} else if ((CommonConstants.DB_NAME).equalsIgnoreCase("oracle"))
			{
				// 14-02-2007 manoharan
				// String adpQueryOriginal = readFile(CommonConstants.JBOSSHOME
				// + File.separator +"sql" + File.separator +
				// "demandsupplyOracle.sql");
				String adpQueryOriginal = readFile(sqlFileName + "Oracle.sql");
				// end 14-02-2007 manoharan
				adpQuery = adpQueryOriginal;
				// System.out.println("Replacing Values.in SQL.....");
				adpQuery = adpQuery.replaceAll("@sitecode@", siteCode);
				adpQuery = adpQuery.replaceAll("@itemcode@", siteCode+itemCode);
				adpQuery = adpQuery.replaceAll("@fromdate@", dbDateFrom);
				adpQuery = adpQuery.replaceAll("@todate@", dbDateTo);
				adpQuery = adpQuery.replaceAll("@ordtypes@", standingOrdTypes);
				adpQuery = adpQuery.replaceAll("@madetoorder@", madeToOrder);
				adpQuery = adpQuery.replaceAll("@madetostock@", madeToStock);
				// 01-10-2007 manoharan
				adpQuery = adpQuery.replaceAll("@rundate@", dbRunDate);

			}
			pstmt=conn.prepareStatement(adpQuery);
			rs = pstmt.executeQuery();


			String rsItemCode = "", adpItemcode = "";
			while (rs.next())
			{
				System.out.println("@@@@@@3766 sql executed.....");
				rsItemCode = rs.getString(1);// Added by JIten 02/11/06 as per
				dueDate = rs.getTimestamp(2);
				demand = rs.getDouble(3);
				supply = rs.getDouble(4);
				stockQty = rs.getDouble(5);
				othSupply = rs.getDouble(6);
				pendDOQty = rs.getDouble(8);
				pendDRQty = rs.getDouble(10);
				pendIndQty = rs.getDouble(9);
				pendPOQty = rs.getDouble(7);
				tranId=rs.getString("tran_id");
				tranSer=rs.getString("tran_ser");
				if (dueDate.compareTo(dateFrom) < 0)
				{
					dueDate = dateFrom;
				}



				ADPElement detADPElement=new ADPElement();
				detADPElement.setSupply(dueDate, supply);

				detADPElement.setStockQty(dueDate, stockQty);
				detADPElement.setOthSupply(dueDate, othSupply);
				detADPElement.setPendingPO(dueDate, pendPOQty);
				detADPElement.setPendingDO(dueDate, pendDOQty);
				detADPElement.setPendingIndent(dueDate, pendIndQty);
				detADPElement.setPendingDR(dueDate, pendDRQty);
				detADPElement.setOriginalOrAltitem("A");
				detADPElement.setAltitemPerc(altitemPerc);
				//cpatil-25/08/14-System.out.println("Setting SaleOrder in Detail record---"+adpElement.getSaleOrder());
				//cpatil-25/08/14-System.out.println("Setting Line No in Detail record---"+adpElement.getLineNo());
				//detADPElement.setSaleOrder(adpElement.getSaleOrder());
				//detADPElement.setLineNo(adpElement.getLineNo());
				//cpatil-25/08/14-System.out.println("detADPElement.getPendingPO()----"+detADPElement.getPendingPO());

				System.out.println("tranId#tranSer----"+tranId+"#"+tranSer);
				detMap.put(tranId+"#"+tranSer, detADPElement);



			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;

			//System.out.println("@@@@@@3934:outside itemCodeTo["+itemCodeTo+"]isBomReplace["+isBomReplace+"]adpElement.getItemCode()["+adpElement.getItemCode()+"]");

			/*if(isBomReplace &&  itemCodeTo.equalsIgnoreCase(adpElement.getItemCode()))
			{
				System.out.println("@@@@@@3934:itemCodeTo["+itemCodeTo+"]dueDate["+dueDate+"]bomReplaceDemand["+bomReplaceDemand+"]");
				adpElement.setDemand(dueDate, bomReplaceDemand, "          ", "   ");
			}
			 */
		} catch (SQLException se)
		{
			System.out.println("SQLException :RunMRPPrcEJB : populateDemandSupply(ADPElement).." + se.getMessage());
			System.out.println(adpQuery);
			se.printStackTrace();
			errString = se.getMessage();
			throw new ITMException(se);
		} catch (Exception e)
		{
			System.out.println("Exception :RunMRPPrcEJB : populateDemandSupply(ADPElement):...." + e.getMessage() + ":");
			this.errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		} finally
		{
			if (pstmt != null)
			{
				pstmt = null;
			}
			if (rs != null)
			{
				rs = null;
			}

		}

		return detMap;

	}

	/**
	 * Create a library of cell styles
	 */
	/*
	 * private static Map<String, HSSFCellStyle> createStyles(Workbook wb){
	 * Map<String, HSSFCellStyle> styles = new HashMap<String, HSSFCellStyle>();
	 * HSSFCellStyle style; Font titleFont = wb.createFont();
	 * titleFont.setFontHeightInPoints((short)18);
	 * titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD); style =
	 * wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	 * style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
	 * style.setFont(titleFont); styles.put("title", style);
	 * 
	 * Font monthFont = wb.createFont();
	 * monthFont.setFontHeightInPoints((short)11);
	 * monthFont.setColor(IndexedColors.WHITE.getIndex()); style =
	 * wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	 * style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
	 * style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
	 * style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
	 * style.setFont(monthFont); style.setWrapText(true); styles.put("header",
	 * style);
	 * 
	 * style = wb.createCellStyle();
	 * style.setAlignment(HSSFCellStyle.ALIGN_CENTER); style.setWrapText(true);
	 * style.setBorderRight(HSSFCellStyle.BORDER_THIN);
	 * style.setRightBorderColor(IndexedColors.BLACK.getIndex());
	 * style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
	 * style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
	 * style.setBorderTop(HSSFCellStyle.BORDER_THIN);
	 * style.setTopBorderColor(IndexedColors.BLACK.getIndex());
	 * style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
	 * style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
	 * styles.put("cell", style);
	 * 
	 * style = wb.createCellStyle();
	 * style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	 * style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
	 * style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
	 * style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
	 * style.setDataFormat(wb.createDataFormat().getFormat("0.00"));
	 * styles.put("formula", style);
	 * 
	 * style = wb.createCellStyle();
	 * style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	 * style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
	 * style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
	 * style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
	 * style.setDataFormat(wb.createDataFormat().getFormat("0.00"));
	 * styles.put("formula_2", style);
	 * 
	 * return styles; }
	 * 
	 * public double getRequiredDecimal(double actVal, int prec) { NumberFormat
	 * numberFormat = NumberFormat.getIntegerInstance (); Double DoubleValue =
	 * new Double (actVal); numberFormat.setMaximumFractionDigits(3); String
	 * strValue = numberFormat.format(DoubleValue); strValue =
	 * strValue.replaceAll(",",""); double reqVal =
	 * Double.parseDouble(strValue); return reqVal; }
	 */
	private void childItems(String bCode,String saleOrder,String itemCodeParent)
	{
		String key1="";
		Set<String> value2=new HashSet<String>();
		//ADPElement adpE=new ADPElement();
		System.out.println("11211--saleOrder["+saleOrder+"]");
		String refSo="",refItem="";
		double soQty=0;
		//if (itemBomMap1.containsValue(bCode))
		//{
		for (Entry<String, Set<String>> e : itemBomMap1.entrySet()) 
		{
			key1 = e.getKey();
			value2 = e.getValue();
			//if ((value2.toString()).equalsIgnoreCase(bCode))
			if (value2.contains(bCode))
			{
				for(int ctr=0;ctr<adpeList.size();ctr++)
				{
					ADPElement adpE=(ADPElement) adpeList.get(ctr);
					System.out.println("key1["+key1+"]");
					System.out.println("adpE.getItemCode()["+adpE.getItemCode()+"]");
					System.out.println("adpE.getRefId()["+adpE.getRefId()+"]");
					String refId=adpE.getRefId();
					ADPElement adpE1 = new ADPElement();
					try {
						adpE1=(ADPElement) adpE.clone();
					} catch (CloneNotSupportedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					//System.out.println("@@@@ refId.length()["+refId.length()+"]");
					if(refId!=null && refId.length()>0)
					{
						String refIdArr[]=refId.split("~");
						System.out.println("@@@@@ refIdArr.length["+refIdArr.length+"]");
						for(int i=0;i<refIdArr.length;i++)
						{
							String soLine=refIdArr[i];
							String soLineArr[]=soLine.split("@");
							refSo=soLineArr[0];
							refItem=soLineArr[1];
							soQty=Double.parseDouble(soLineArr[2]);
							//double =Double.parseDouble(soLine.split("@")[2]);
							System.out.println("outside refItem["+refItem+"]adpE.getItemCode()["+adpE.getItemCode()+"]refSo["+refSo+"]saleOrder["+saleOrder+"]soQty["+soQty+"]");
							if(refItem.equalsIgnoreCase(adpE.getItemCode()) && refSo.equalsIgnoreCase(saleOrder) )
							{
								System.out.println("inside refItem["+refItem+"]adpE.getItemCode()["+adpE.getItemCode()+"]refSo["+refSo+"]saleOrder["+saleOrder+"]soQty["+soQty+"]");
								adpE1.setSoDemand(soQty);
								adpE1.setSaleOrder(saleOrder);
								break;
							}

						}
					}



					if(key1.equalsIgnoreCase(checkNull(adpE1.getItemCode())))
					{
						System.out.println("adpE.getBomCode()["+adpE1.getBomCode()+"]");
						adpE1.setItemCodeParent(itemCodeParent);
						al1.add(adpE1);
						//adpE.setDetList(null);
						if((checkNull(adpE1.getBomCode()).trim()).length()>0)
						{
							childItems(adpE1.getBomCode(),saleOrder,adpE1.getItemCode());	
						}


					}
					adpE1 = null;
				}
			}
		}
		//}



	}
}

//Added by Jiten 07/11/06
class CyclicItem
{
	public String siteCode;
	public String bomCode;
	public String itemCode;
	public String cylicItemCode;
}



//End
/*
 * private String InsertPlanDemand(String winName, java.util.ArrayList list) {
 * String xmlValues = ""; String errString = ""; try { InitialContext ctx =
 * null;
 * 
 * AppConnectParm appConnect = new AppConnectParm(); ctx = new
 * InitialContext(appConnect.getProperty()); MasterStatefulHome
 * masterStatefulHome = (MasterStatefulHome)ctx.lookup("MasterStateful");
 * MasterStateful masterStateful = masterStatefulHome.create(); String []
 * authencate = new String[2]; authencate[0] = userId; authencate[1] = userId;
 * 
 * SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
 * if(winName.equalsIgnoreCase("W_MPS_ORDER")) {
 * System.out.println("W_MPS_ORDER"); String tranId = ""; String ordType = "";
 * String itemCode = ""; String siteCode = ""; String mrpRunId = ""; String
 * addnOrder = ""; String status = ""; String routeCode = ""; String bomCode =
 * ""; String projCode = ""; //String chgUser = ""; //String chgTerm = "";
 * String unit = ""; String acctCodeWp = ""; String cctrCodeWp = "";
 * 
 * double quantity = 0; double yieldPerc = 0 ; double curBatchQty = 0;
 * 
 * String ordDate = ""; String planDueDate = ""; String dueDate = ""; String
 * statusDate = ""; String chgDate = "";
 * 
 * // java.sql.Timestamp ordDate = null; // java.sql.Timestamp planDueDate =
 * null; // java.sql.Timestamp dueDate = null; // java.sql.Timestamp statusDate
 * = null; // java.sql.Timestamp chgDate = null;
 * 
 * MPSOrder mpsOrder = null; for(int count = 0; count<list.size(); count++) {
 * 
 * mpsOrder = (MPSOrder)list.get(count);
 * 
 * ordType = mpsOrder.ordType; itemCode = mpsOrder.itemCode; siteCode =
 * mpsOrder.siteCode; quantity = mpsOrder.quantity; ordDate =
 * sdf.format(mpsOrder.ordDate); //mpsOrder.ordDate; planDueDate =
 * sdf.format(mpsOrder.planDueDate); //mpsOrder.planDueDate; mrpRunId =
 * mpsOrder.mrpRunId; addnOrder = mpsOrder.addnOrder; dueDate =
 * sdf.format(mpsOrder.dueDate); //mpsOrder.dueDate; status = mpsOrder.status;
 * statusDate = sdf.format(mpsOrder.statusDate); //mpsOrder.statusDate;
 * yieldPerc = mpsOrder.yieldPerc; routeCode = mpsOrder.routeCode; bomCode =
 * mpsOrder.bomCode; projCode = mpsOrder.projCode; chgDate =
 * sdf.format(mpsOrder.chgDate); //mpsOrder.chgDate; // chgUser =
 * mpsOrder.chgUser; // chgTerm = mpsOrder.chgTerm; unit = mpsOrder.unit;
 * acctCodeWp = mpsOrder.acctCodeWp; cctrCodeWp = mpsOrder.cctrCodeWp;
 * curBatchQty = mpsOrder.curBatchQty; xmlValues =
 * "<?xml version='1.0' encoding='UTF-8'?>\n" + "<Root>\n"; xmlValues =
 * xmlValues + "<DocumentRoot>" + "<description>" + "Datawindow Root" +
 * "</description>"; xmlValues = xmlValues + "<group0>" + "<description>" +
 * "Group0 description" + "</description>"; xmlValues = xmlValues + "<Header0>";
 * xmlValues = xmlValues + "<objName><![CDATA[mps_order]]></objName>"; xmlValues
 * = xmlValues + "<pageContext><![CDATA[1]]></pageContext>"; xmlValues =
 * xmlValues + "<objContext><![CDATA[1]]></objContext>"; xmlValues = xmlValues +
 * "<editFlag><![CDATA[A]]></editFlag>"; xmlValues = xmlValues +
 * "<focusedColumn><![CDATA[]]></focusedColumn>"; xmlValues = xmlValues +
 * "<action><![CDATA[SAVE]]></action>"; xmlValues = xmlValues +
 * "<elementName><![CDATA[]]></elementName>"; xmlValues = xmlValues +
 * "<keyValue><![CDATA[1]]></keyValue>"; xmlValues = xmlValues +
 * "<taxKeyValue><![CDATA[]]></taxKeyValue>"; xmlValues = xmlValues +
 * "<saveLevel><![CDATA[1]]></saveLevel>"; xmlValues = xmlValues +
 * "<forcedSave><![CDATA[true]]></forcedSave>"; xmlValues = xmlValues +
 * "<taxInFocus><![CDATA[false]]></taxInFocus>"; xmlValues = xmlValues +
 * "<description>Header0 members</description>";
 * 
 * 
 * xmlValues = xmlValues +
 * "<Detail1 dbID=\"\" domID=\"1\" objName=\"mps_order\" objContext=\"1\" >";
 * xmlValues = xmlValues +
 * "<attribute pkNames=\"\" status=\"N\" updateFlag=\"A\" selected=\"N\" />";
 * xmlValues = xmlValues + "<tran_id><![CDATA[]]></tran_id>"; xmlValues =
 * xmlValues + "<order_type><![CDATA[" + ordType + "]]></order_type>"; xmlValues
 * = xmlValues + "<item_code><![CDATA[" + itemCode + "]]></item_code>";
 * xmlValues = xmlValues + "<site_code><![CDATA[" + siteCode +
 * "]]></site_code>"; xmlValues = xmlValues + "<quantity><![CDATA[" + quantity +
 * "]]></quantity>"; xmlValues = xmlValues + "<ord_date><![CDATA[" + ordDate +
 * "]]></ord_date>"; xmlValues = xmlValues + "<plan_due_date><![CDATA[" +
 * planDueDate + "]]></plan_due_date>"; xmlValues = xmlValues +
 * "<mrp_run_id><![CDATA[" + mrpRunId + "]]></mrp_run_id>"; xmlValues =
 * xmlValues + "<addn_order><![CDATA[" + addnOrder + "]]></addn_order>";
 * xmlValues = xmlValues + "<due_date><![CDATA[" + dueDate + "]]></due_date>";
 * xmlValues = xmlValues + "<status><![CDATA[" + status + "]]></status>";
 * xmlValues = xmlValues + "<status_date><![CDATA[" + statusDate +
 * "]]></status_date>"; xmlValues = xmlValues + "<yield_perc><![CDATA[" +
 * yieldPerc + "]]></yield_perc>"; xmlValues = xmlValues +
 * "<route_code><![CDATA[" + routeCode + "]]></route_code>"; xmlValues =
 * xmlValues + "<bom_code><![CDATA[" + bomCode + "]]></bom_code>"; xmlValues =
 * xmlValues + "<proj_code><![CDATA[" + projCode + "]]></proj_code>"; xmlValues
 * = xmlValues + "<chg_date><![CDATA[" + chgDate + "]]></chg_date>"; xmlValues =
 * xmlValues + "<chg_user><![CDATA[" + chgUser + "]]></chg_user>"; xmlValues =
 * xmlValues + "<chg_term><![CDATA[" + chgTerm + "]]></chg_term>"; xmlValues =
 * xmlValues + "<unit><![CDATA[" + unit + "]]></unit>"; xmlValues = xmlValues +
 * "<acct_code__wp><![CDATA[" + acctCodeWp + "]]></acct_code__wp>"; xmlValues =
 * xmlValues + "<cctr_code__wp><![CDATA[" + cctrCodeWp + "]]></cctr_code__wp>";
 * xmlValues = xmlValues + "<current_batch_qty><![CDATA[" + curBatchQty +
 * "]]></current_batch_qty>";
 * 
 * xmlValues = xmlValues + "</Detail1>"; xmlValues = xmlValues + "</Header0>";
 * xmlValues = xmlValues + "</group0>"; xmlValues = xmlValues +
 * "</DocumentRoot>"; xmlValues = xmlValues + "</Root>\r\n"; errString =
 * masterStateful.processRequest(authencate, logInSite, true, xmlValues);
 * //errString = saveData(xmlValues);
 * 
 * } } else if(winName.equalsIgnoreCase("W_DIST_DEMAND")) { String tranId = "";
 * String siteCode = ""; String itemCode = ""; String unit = ""; String
 * siteCodeSrc = ""; final String status = "T"; //String chgUser = ""; // String
 * chgTerm = "";
 * 
 * double qtyRequired = 0;
 * 
 * String tranDate = ""; String planDueDate = ""; String dueDateOrd = ""; String
 * dueDate = ""; String chgDate = "";
 * 
 * // java.sql.Timestamp tranDate = null; // java.sql.Timestamp planDueDate =
 * null; // java.sql.Timestamp dueDateOrd = null; // java.sql.Timestamp dueDate
 * = null; // java.sql.Timestamp chgDate = null;
 * 
 * DistDemand distDemand = new DistDemand(); for(int count = 0;
 * count<list.size(); count++) { distDemand = (DistDemand)list.get(count);
 * 
 * tranDate = sdf.format(distDemand.tranDate); siteCode = distDemand.siteCode;
 * itemCode = distDemand.itemCode; planDueDate =
 * sdf.format(distDemand.planDueDate); //distDemand.planDueDate; dueDate =
 * sdf.format(distDemand.dueDate); //distDemand.dueDate; qtyRequired =
 * distDemand.qtyRequired; unit = distDemand.unit; siteCodeSrc =
 * distDemand.siteCodeSrc; dueDateOrd = sdf.format(distDemand.dueDateOrd);
 * chgDate = sdf.format(distDemand.chgDate); //distDemand.chgDate; //chgUser =
 * distDemand.chgUser; //chgTerm = distDemand.chgTerm; xmlValues =
 * "<?xml version='1.0' encoding='UTF-8'?>\n" + "<Root>\n"; xmlValues =
 * xmlValues + "<DocumentRoot>" + "<description>" + "Datawindow Root" +
 * "</description>"; xmlValues = xmlValues + "<group0>" + "<description>" +
 * "Group0 description" + "</description>"; xmlValues = xmlValues + "<Header0>";
 * xmlValues = xmlValues + "<objName><![CDATA[dist_demand]]></objName>";
 * xmlValues = xmlValues + "<pageContext><![CDATA[1]]></pageContext>"; xmlValues
 * = xmlValues + "<objContext><![CDATA[1]]></objContext>"; xmlValues = xmlValues
 * + "<editFlag><![CDATA[A]]></editFlag>"; xmlValues = xmlValues +
 * "<focusedColumn><![CDATA[]]></focusedColumn>"; xmlValues = xmlValues +
 * "<action><![CDATA[SAVE]]></action>"; xmlValues = xmlValues +
 * "<elementName><![CDATA[]]></elementName>"; xmlValues = xmlValues +
 * "<keyValue><![CDATA[1]]></keyValue>"; xmlValues = xmlValues +
 * "<taxKeyValue><![CDATA[]]></taxKeyValue>"; xmlValues = xmlValues +
 * "<saveLevel><![CDATA[1]]></saveLevel>"; xmlValues = xmlValues +
 * "<forcedSave><![CDATA[true]]></forcedSave>"; xmlValues = xmlValues +
 * "<taxInFocus><![CDATA[false]]></taxInFocus>"; xmlValues = xmlValues +
 * "<description>Header0 members</description>";
 * 
 * 
 * xmlValues = xmlValues +
 * "<Detail1 dbID=\"\" domID=\"1\" objName=\"dist_demand\" objContext=\"1\" >";
 * xmlValues = xmlValues +
 * "<attribute pkNames=\"\" status=\"N\" updateFlag=\"A\" selected=\"N\" />";
 * xmlValues = xmlValues + "<tran_id><![CDATA[]]></tran_id>"; xmlValues =
 * xmlValues + "<tran_date><![CDATA[" + tranDate + "]]></tran_date>"; xmlValues
 * = xmlValues + "<site_code><![CDATA[" + siteCode + "]]></site_code>";
 * xmlValues = xmlValues + "<item_code><![CDATA[" + itemCode +
 * "]]></item_code>"; xmlValues = xmlValues + "<plan_due_date><![CDATA[" +
 * planDueDate + "]]></plan_due_date>"; xmlValues = xmlValues +
 * "<due_date><![CDATA[" + dueDate + "]]></due_date>"; xmlValues = xmlValues +
 * "<qty_required><![CDATA[" + qtyRequired + "]]></qty_required>"; xmlValues =
 * xmlValues + "<unit><![CDATA[" + unit + "]]></unit>"; xmlValues = xmlValues +
 * "<site_code__source><![CDATA[" + siteCodeSrc + "]]></site_code__source>";
 * xmlValues = xmlValues + "<status><![CDATA[" + status + "]]></status>";
 * xmlValues = xmlValues + "<due_date__ord><![CDATA[" + dueDateOrd +
 * "]]></due_date__ord>"; xmlValues = xmlValues + "<chg_date><![CDATA[" +
 * chgDate + "]]></chg_date>"; xmlValues = xmlValues + "<chg_user><![CDATA[" +
 * chgUser + "]]></chg_user>"; xmlValues = xmlValues + "<chg_term><![CDATA[" +
 * chgTerm + "]]></chg_term>";
 * 
 * xmlValues = xmlValues + "</Detail1>"; xmlValues = xmlValues + "</Header0>";
 * xmlValues = xmlValues + "</group0>"; xmlValues = xmlValues +
 * "</DocumentRoot>"; xmlValues = xmlValues + "</Root>\r\n";
 * 
 * //errString = saveData(xmlValues); errString =
 * masterStateful.processRequest(authencate, logInSite, true, xmlValues); } }
 * 
 * else if(winName.equalsIgnoreCase("W_INDENT")) { String indNo = ""; final
 * String indType = "M"; String deptCode = ""; String itemCode = ""; String
 * itemDescr= ""; String unitInd = ""; String unitStd = ""; String siteCode =
 * ""; String siteCodeDlv = ""; String siteCodeAcct = ""; String siteCodeCust =
 * ""; String aprCode = ""; final String priority = "R"; String acctCode = "";
 * String cctrCode = ""; String empCodePur = ""; String empCodeReq = ""; String
 * suppCodePref = ""; String packCode = ""; final String status = "T"; //String
 * chgUser = ""; // String chgTerm = "";
 * 
 * double purLeadTime = 0 ; double quantity = 0; double quantityStdUom = 0;
 * double ordQuantity = 0; double purcRate = 0; double convQtyStdUom = 0;
 * 
 * String indDate = ""; String planDueDate = ""; String reqDate = ""; String
 * chgDate = ""; // // java.sql.Timestamp indDate = null; // java.sql.Timestamp
 * planDate = null; // java.sql.Timestamp reqDate = null; // java.sql.Timestamp
 * chgDate = null;
 * 
 * 
 * Indent indent = new Indent(); for(int count = 0; count<list.size(); count++)
 * { indent = (Indent)list.get(count);
 * 
 * //indent.tranDate; indDate = sdf.format(indent.indDate); //indent.indDate;
 * deptCode = indent.indType; planDueDate = sdf.format(indent.planDueDate);
 * //indent.planDueDate; reqDate = sdf.format(indent.reqDate); //indent.reqDate;
 * itemCode = indent.itemCode; itemDescr = indent.itemDescr; quantity =
 * indent.quantity; quantityStdUom = indent.quantityStdUom; unitInd =
 * indent.unitInd; unitStd = indent.unitStd; siteCode = indent.siteCode;
 * siteCodeDlv = indent.siteCodeDlv; siteCodeAcct = indent.siteCodeAcct; aprCode
 * = indent.aprCode; acctCode = indent.acctCode; cctrCode = indent.cctrCode;
 * empCodePur = indent.empCodePur; empCodeReq = indent.empCodeReq; suppCodePref
 * = indent.suppCodePref; purcRate = indent.purcRate; packCode =
 * indent.packCode; chgDate = sdf.format(indent.chgDate); //chgUser =
 * indent.chgUser; //chgTerm = indent.chgTerm; purLeadTime = indent.purLeadTime;
 * convQtyStdUom = indent.convQtyStdUom; planDueDate =
 * sdf.format(indent.planDueDate); xmlValues =
 * "<?xml version='1.0' encoding='UTF-8'?>\n" + "<Root>\n"; xmlValues =
 * xmlValues + "<DocumentRoot>" + "<description>" + "Datawindow Root" +
 * "</description>"; xmlValues = xmlValues + "<group0>" + "<description>" +
 * "Group0 description" + "</description>"; xmlValues = xmlValues + "<Header0>";
 * xmlValues = xmlValues + "<objName><![CDATA[indent]]></objName>"; xmlValues =
 * xmlValues + "<pageContext><![CDATA[1]]></pageContext>"; xmlValues = xmlValues
 * + "<objContext><![CDATA[1]]></objContext>"; xmlValues = xmlValues +
 * "<editFlag><![CDATA[A]]></editFlag>"; xmlValues = xmlValues +
 * "<focusedColumn><![CDATA[]]></focusedColumn>"; xmlValues = xmlValues +
 * "<action><![CDATA[SAVE]]></action>"; xmlValues = xmlValues +
 * "<elementName><![CDATA[]]></elementName>"; xmlValues = xmlValues +
 * "<keyValue><![CDATA[1]]></keyValue>"; xmlValues = xmlValues +
 * "<taxKeyValue><![CDATA[]]></taxKeyValue>"; xmlValues = xmlValues +
 * "<saveLevel><![CDATA[1]]></saveLevel>"; xmlValues = xmlValues +
 * "<forcedSave><![CDATA[true]]></forcedSave>"; xmlValues = xmlValues +
 * "<taxInFocus><![CDATA[false]]></taxInFocus>"; xmlValues = xmlValues +
 * "<description>Header0 members</description>";
 * 
 * xmlValues = xmlValues +
 * "<Detail1 dbID=\"\" domID=\"1\" objName=\"indent\" objContext=\"1\" >";
 * xmlValues = xmlValues +
 * "<attribute pkNames=\"\" status=\"N\" updateFlag=\"A\" selected=\"N\" />";
 * xmlValues = xmlValues + "<ind_no><![CDATA[]]></ind_no>"; xmlValues =
 * xmlValues + "<ind_date><![CDATA[" + indDate + "]]></ind_date>"; xmlValues =
 * xmlValues + "<ind_type><![CDATA[" + indType + "]]></ind_type>"; xmlValues =
 * xmlValues + "<dept_code><![CDATA[" + deptCode + "]]></dept_code>"; xmlValues
 * = xmlValues + "<plan_due_date><![CDATA[" + planDueDate +
 * "]]></plan_due_date>"; xmlValues = xmlValues + "<req_date><![CDATA[" +
 * reqDate + "]]></req_date>"; xmlValues = xmlValues + "<item_code><![CDATA[" +
 * itemCode + "]]></item_code>"; xmlValues = xmlValues + "<item_desc><![CDATA["
 * + itemDescr + "]]></item_desc>"; xmlValues = xmlValues +
 * "<quantity><![CDATA[" + quantity + "]]></quantity>"; xmlValues = xmlValues +
 * "<quantity__stduom><![CDATA[" + quantityStdUom + "]]></quantity__stduom>";
 * xmlValues = xmlValues + "<unit__ind><![CDATA[" + unitInd + "]]></unit__ind>";
 * xmlValues = xmlValues + "<unit__std><![CDATA[" + unitStd + "]]></unit__std>";
 * xmlValues = xmlValues + "<site_code><![CDATA[" + siteCode +
 * "]]></site_code>"; xmlValues = xmlValues + "<site_code__dlv><![CDATA[" +
 * siteCodeDlv + "]]></site_code__dlv>"; xmlValues = xmlValues +
 * "<site_code__acct><![CDATA[" + siteCodeAcct + "]]></site_code__acct>";
 * xmlValues = xmlValues + "<apr_code><![CDATA[" + aprCode + "]]></apr_code>";
 * xmlValues = xmlValues + "<priority><![CDATA[" + priority + "]]></priority>";
 * xmlValues = xmlValues + "<acct_code><![CDATA[" + acctCode +
 * "]]></acct_code>"; xmlValues = xmlValues + "<cctr_code><![CDATA[" + cctrCode
 * + "]]></cctr_code>"; xmlValues = xmlValues + "<emp_code__pur><![CDATA[" +
 * empCodePur + "]]></emp_code__pur>"; xmlValues = xmlValues +
 * "<emp_code__req><![CDATA[" + empCodeReq + "]]></emp_code__req>"; xmlValues =
 * xmlValues + "<supp_code__pref><![CDATA[" + suppCodePref +
 * "]]></supp_code__pref>"; xmlValues = xmlValues + "<purc_rate><![CDATA[" +
 * purcRate + "]]></purc_rate>"; xmlValues = xmlValues + "<pack_code><![CDATA["
 * + packCode + "]]></pack_code>"; xmlValues = xmlValues + "<status><![CDATA[" +
 * status + "]]></status>"; xmlValues = xmlValues + "<chg_date><![CDATA[" +
 * chgDate + "]]></chg_date>"; xmlValues = xmlValues + "<chg_user><![CDATA[" +
 * chgUser + "]]></chg_user>"; xmlValues = xmlValues + "<chg_term><![CDATA[" +
 * chgTerm + "]]></chg_term>"; xmlValues = xmlValues +
 * "<pur_lead_time><![CDATA[" + purLeadTime + "]]></pur_lead_time>"; xmlValues =
 * xmlValues + "<conv__qty_stdoum><![CDATA[" + convQtyStdUom +
 * "]]></conv__qty_stdoum>";
 * 
 * xmlValues = xmlValues + "</Detail1>"; xmlValues = xmlValues + "</Header0>";
 * xmlValues = xmlValues + "</group0>"; xmlValues = xmlValues +
 * "</DocumentRoot>"; xmlValues = xmlValues + "</Root>\r\n"; FileOutputStream
 * fout = null; BufferedWriter bw = null; fout = new
 * FileOutputStream("XML.xml"); bw = new BufferedWriter(new
 * OutputStreamWriter(fout)); bw.write(xmlValues); bw.close(); fout.close();
 * 
 * //errString = saveData(xmlValues); errString =
 * masterStateful.processRequest(authencate, logInSite, true, xmlValues); }
 * 
 * }
 * 
 * else if(winName.equalsIgnoreCase("W_INDEPENDENT_DEMAND")) { String tranId =
 * ""; String siteCode = ""; String siteCodeCust = ""; String itemCode = "";
 * String unit = ""; String unitStd = ""; String status = "T";
 * 
 * double quantity = 0; double quantityStdUom = 0; double convQtyStdUom = 1;
 * 
 * String tranDate = ""; String planDueDate = ""; String dueDate = "";
 * 
 * // java.sql.Timestamp tranDate = null; // java.sql.Timestamp planDueDate =
 * null; // java.sql.Timestamp dueDate = null;
 * 
 * 
 * IndependentDemand independentDemand = new IndependentDemand(); for(int count
 * = 0; count<list.size(); count++) { independentDemand =
 * (IndependentDemand)list.get(count);
 * 
 * siteCode = independentDemand.siteCode; siteCodeCust =
 * independentDemand.siteCodeCust; itemCode = independentDemand.itemCode; unit =
 * independentDemand.unit; unitStd = independentDemand.unitStd; quantity =
 * independentDemand.quantity; quantityStdUom =
 * independentDemand.quantityStdUom; convQtyStdUom =
 * independentDemand.convQtyStdUom; tranDate =
 * sdf.format(independentDemand.tranDate); //independentDemandTranDate;
 * planDueDate = sdf.format(independentDemand.planDueDate);
 * //independentDemandPlanDueDate; dueDate =
 * sdf.format(independentDemand.dueDate); //independentDemandDueDate; xmlValues
 * = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<Root>\n"; xmlValues =
 * xmlValues + "<DocumentRoot>" + "<description>" + "Datawindow Root" +
 * "</description>"; xmlValues = xmlValues + "<group0>" + "<description>" +
 * "Group0 description" + "</description>"; xmlValues = xmlValues + "<Header0>";
 * xmlValues = xmlValues + "<objName><![CDATA[independent_demand]]></objName>";
 * xmlValues = xmlValues + "<pageContext><![CDATA[1]]></pageContext>"; xmlValues
 * = xmlValues + "<objContext><![CDATA[1]]></objContext>"; xmlValues = xmlValues
 * + "<editFlag><![CDATA[A]]></editFlag>"; xmlValues = xmlValues +
 * "<focusedColumn><![CDATA[]]></focusedColumn>"; xmlValues = xmlValues +
 * "<action><![CDATA[SAVE]]></action>"; xmlValues = xmlValues +
 * "<elementName><![CDATA[]]></elementName>"; xmlValues = xmlValues +
 * "<keyValue><![CDATA[1]]></keyValue>"; xmlValues = xmlValues +
 * "<taxKeyValue><![CDATA[]]></taxKeyValue>"; xmlValues = xmlValues +
 * "<saveLevel><![CDATA[1]]></saveLevel>"; xmlValues = xmlValues +
 * "<forcedSave><![CDATA[true]]></forcedSave>"; xmlValues = xmlValues +
 * "<taxInFocus><![CDATA[false]]></taxInFocus>"; xmlValues = xmlValues +
 * "<description>Header0 members</description>";
 * 
 * xmlValues = xmlValues +
 * "<Detail1 dbID=\"\" domID=\"1\" objName=\"independent_demand\" objContext=\"1\" >"
 * ; xmlValues = xmlValues +
 * "<attribute pkNames=\"\" status=\"N\" updateFlag=\"A\" selected=\"N\" />";
 * xmlValues = xmlValues + "<tran_id><![CDATA[]]></tran_id>"; xmlValues =
 * xmlValues + "<site_code><![CDATA[" + siteCode + "]]></site_code>"; xmlValues
 * = xmlValues + "<site_code__cust><![CDATA[" + siteCodeCust +
 * "]]></site_code__cust>"; xmlValues = xmlValues + "<item_code><![CDATA[" +
 * itemCode + "]]></item_code>"; xmlValues = xmlValues + "<unit><![CDATA[" +
 * unit + "]]></unit>"; xmlValues = xmlValues + "<unit__std><![CDATA[" + unitStd
 * + "]]></unit__std>"; xmlValues = xmlValues + "<status><![CDATA[" + status +
 * "]]></status>"; xmlValues = xmlValues + "<quantity><![CDATA[" + quantity +
 * "]]></quantity>"; xmlValues = xmlValues + "<quantity__std_uom><![CDATA[" +
 * quantityStdUom + "]]></quantity__std_uom>"; xmlValues = xmlValues +
 * "<conv__qty_std_oum><![CDATA[" + convQtyStdUom + "]]></conv__qty_std_oum>";
 * xmlValues = xmlValues + "<tran_date><![CDATA[" + tranDate +
 * "]]></tran_date>"; xmlValues = xmlValues + "<plan_due_date><![CDATA[" +
 * planDueDate + "]]></plan_due_date>"; xmlValues = xmlValues +
 * "<due_date><![CDATA[" + dueDate + "]]></due_date>";
 * 
 * xmlValues = xmlValues + "</Detail1>";
 * 
 * xmlValues = xmlValues + "</Header0>"; xmlValues = xmlValues + "</group0>";
 * xmlValues = xmlValues + "</DocumentRoot>"; xmlValues = xmlValues +
 * "</Root>\r\n";
 * 
 * //errString = saveData(xmlValues); errString =
 * masterStateful.processRequest(authencate, logInSite, true, xmlValues); }
 * 
 * } masterStateful = null; // xmlValues = xmlValues + "</Header>"; // xmlValues
 * = xmlValues + "</Root>";
 * 
 * 
 * 
 * 
 * } catch(Exception e) { System.out.println("Exception [InsertPlanDemand] : " +
 * e); e.printStackTrace(); errString = e.getMessage(); } return errString; }
 */