package  ibase.webitm.ejb.mfg.adv;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import org.xml.sax.InputSource;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import java.rmi.RemoteException;
import java.util.*;
import java.util.Date;
import java.sql.*;
import java.io.*;
import org.omg.CORBA.ORB;
import org.w3c.dom.*;
import java.util.Properties;
import javax.xml.parsers.*;
import javax.ejb.*;
import javax.naming.InitialContext;

import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.*;
import ibase.webitm.utility.TransIDGenerator;
import ibase.utility.CommonConstants;
import ibase.ejb.*;
import ibase.system.config.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3
public class WorkorderPrc extends ProcessEJB implements  WorkorderPrcLocal,WorkorderPrcRemote //SessionBean
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();

	CommonConstants commonConstants = new CommonConstants();

	Connection conn = null;

	StringBuffer retBuf = null;
	String itemCode=null;
	String itemDescr=null;
	String mfgType=null;
	String dueDate=null;
	String siteCode=null;
	String errorString=null;
	String loginCode=null;
	String chgTerm=null;

	int quantity=0;
	int demand=0;
	int minQty=0;
	int maxQty=0;
	int batches=0;
	double amount=0.0;
	double demandAmt=0.0;

	/*public void ejbCreate() throws RemoteException, CreateException
	{
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate()
	{
	}
	public void ejbPassivate()
	{
	}*/
	public String process() throws RemoteException,ITMException
	{
		return "";
	}

	//=>getData Method
	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("WorkorderPrcEJB :getData() function called");
		String rtrStr = "";
		Document headerDom = null;
		Document detailDom = null;

		try
		{
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				System.out.println("XML String :"+xmlString);
				headerDom = genericUtility.parseString(xmlString);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				System.out.println("XML String :"+xmlString2);
				detailDom = genericUtility.parseString(xmlString2);
			}

			rtrStr = getData(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println("Exception :WorkorderPrcEJB :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			rtrStr = e.getMessage();
			throw new ITMException(e);
		}
		return rtrStr;

	}//END OF GETDATA(1)


	public String getData(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String errString=null;
		String errCode = "";
		String getDataSql= "" ;
		String sql= "" ;
		String resultString = "";
		ResultSet rs1 = null;
		PreparedStatement pstmt = null;
		Statement st = null;
		StringBuffer retTabSepStrBuff = new StringBuffer();
		String siteCode=null;

		java.util.HashMap refMap = new java.util.HashMap();
		try
		{
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver = null;

		}
		catch (Exception e)
		{
			System.out.println("Exception :WorkorderPrcEJB :ejbCreate :==>"+e);
			e.printStackTrace();
		}

		try
		{
			siteCode = genericUtility.getColumnValue("site_code",headerDom);
			if(siteCode!=null && siteCode.equals(""))
			{
				siteCode = "";
				System.out.println("Site Code From is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}
			if ( siteCode == null || siteCode.trim().length() == 0 )
			{
				siteCode = "";
				System.out.println("Site Code From is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
				return errString;
			}

			if((commonConstants.DB_NAME).equalsIgnoreCase("ORACLE"))
			{
				getDataSql="SELECT A.ITEM_CODE,C.DESCR,(CASE WHEN RTRIM(B.MFG_TYPE) IS NULL THEN RTRIM(C.MFG_TYPE)ELSE RTRIM(B.MFG_TYPE) END) "
				+" AS MFG_TYPE,A.DUE_DATE,(CASE WHEN B.MIN_QTY IS NULL THEN C.MIN_QTY ELSE B.MIN_QTY END )"
				+" AS MIN_QTY,(CASE WHEN B.MAX_QTY IS NULL THEN C.MAX_QTY ELSE B.MAX_QTY END)AS MAX_QTY,"
				+" A.QUANTITY,A.DEMAND_QTY,A.SITE_CODE,A.TRAN_ID,"
				+" CASE WHEN A.QUANTITY IS NULL THEN 0 ELSE A.QUANTITY END * CASE WHEN DDF_PICK_RATE(ddf_get_mrp_plist(),(fn_sysdate()),a.item_code,null,'L') IS NULL THEN 0 ELSE "
				+" DDF_PICK_RATE(ddf_get_mrp_plist(),(fn_sysdate()),a.item_code,null,'L') END AS AMOUNT ,"
				+" CASE WHEN A.DEMAND_QTY IS NULL THEN 0 ELSE A.DEMAND_QTY END * CASE WHEN "
				+" DDF_PICK_RATE(ddf_get_mrp_plist(),(fn_sysdate()),a.item_code,null,'L') IS NULL THEN 0 ELSE "
				+" DDF_PICK_RATE(ddf_get_mrp_plist(),(fn_sysdate()),a.item_code,null,'L') END AS DEMAND_AMT "
				+" FROM MPS_ORDER A,SITEITEM B,ITEM C "
				+" WHERE ( A.ITEM_CODE = B.ITEM_CODE (+)) AND "
				+" ( A.SITE_CODE = B.SITE_CODE (+)) AND  ( A.ITEM_CODE = C.ITEM_CODE ) "
				+" AND ( ( A.STATUS <> 'C' ) AND ( A.SITE_CODE =?) )";

			}
			else if((commonConstants.DB_NAME).equalsIgnoreCase("DB2")||(commonConstants.DB_NAME).equalsIgnoreCase("MSSQL"))
			{
				getDataSql="SELECT  A.ITEM_CODE ,C.DESCR ,(CASE WHEN RTRIM(B.MFG_TYPE) IS NULL THEN RTRIM(C.MFG_TYPE)ELSE RTRIM(B.MFG_TYPE) END) "
				+" AS MFG_TYPE,A.DUE_DATE ,(CASE WHEN B.MIN_QTY IS NULL THEN C.MIN_QTY ELSE B.MIN_QTY END )AS"
				+" MIN_QTY,(CASE WHEN B.MAX_QTY IS NULL THEN C.MAX_QTY ELSE B.MAX_QTY END)AS MAX_QTY,"
				+" A.QUANTITY ,A.DEMAND_QTY ,A.SITE_CODE ,A.TRAN_ID, "
				+" CASE WHEN A.QUANTITY IS NULL THEN 0 ELSE A.QUANTITY END * CASE WHEN DDF_PICK_RATE(ddf_get_mrp_plist(),(fn_sysdate()),a.item_code,' ','L') IS NULL THEN 0 ELSE "
				+" DDF_PICK_RATE(ddf_get_mrp_plist(),(fn_sysdate()),a.item_code,' ','L') END AS AMOUNT ,"
				+" CASE WHEN A.DEMAND_QTY IS NULL THEN 0 ELSE A.DEMAND_QTY END * CASE WHEN "
				+" DDF_PICK_RATE(ddf_get_mrp_plist(),(fn_sysdate()),a.item_code,' ','L') IS NULL THEN 0 ELSE "
				+" DDF_PICK_RATE(ddf_get_mrp_plist(),(fn_sysdate()),a.item_code,' ','L') END AS DEMAND_AMT "
				+" FROM MPS_ORDER A LEFT OUTER JOIN SITEITEM B ON A.ITEM_CODE = B.ITEM_CODE AND "
				+" A.SITE_CODE = B.SITE_CODE , ITEM C "
				+" WHERE ( A.ITEM_CODE = C.ITEM_CODE) AND ( ( A.STATUS <> 'C' ) "
				+" AND ( A.SITE_CODE = ? ) ) ";
			}
			System.out.println("getDataSql..."+ getDataSql);
			pstmt = conn.prepareStatement(getDataSql);
			pstmt.setString(1,siteCode);
			rs1 = pstmt.executeQuery();

			while(rs1.next())
			{
					System.out.println("Inside while...");
					//item code
					retTabSepStrBuff.append(rs1.getString(1)).append("\t");
					//ITEM DESC
					retTabSepStrBuff.append(rs1.getString(2)).append("\t");
					//mfg TYPE
					retTabSepStrBuff.append(rs1.getString(3)).append("\t");
					//DUE_DATE
					dueDate=this.genericUtility.getValidDateString(rs1.getTimestamp(4).toString(),this.genericUtility.getDBDateFormat(),this.genericUtility.getApplDateFormat());
					retTabSepStrBuff.append(dueDate).append("\t");
					//min_qty
					retTabSepStrBuff.append(rs1.getDouble(5)).append("\t");
					//max_qty
					retTabSepStrBuff.append(rs1.getDouble(6)).append("\t");
					//Quantity
					retTabSepStrBuff.append(rs1.getDouble(7)).append("\t");
					//demand qty
					retTabSepStrBuff.append(rs1.getDouble(8)).append("\t");
					//site_code
					retTabSepStrBuff.append(rs1.getString(9)).append("\t");
					//for tranid
					retTabSepStrBuff.append(rs1.getString(10)).append("\t");
					//FOR AMOUNT
					retTabSepStrBuff.append(rs1.getDouble(11)).append("\t");
					//FOR DEMAND AMOUNT
					retTabSepStrBuff.append(rs1.getDouble(12)).append("\t");

					retTabSepStrBuff.append("\n");
			}
			resultString = retTabSepStrBuff.toString();
			System.out.println("ResultString....." + resultString);
			rs1.close();
			pstmt.close();

		}
		catch (SQLException e)
		{
			System.out.println("SQLException :WorkorderPrcEJB :getData(Document headerDom, Document detailDom, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		catch (Exception e)
		{
			System.out.println("Exception :WorkorderPrcEJB :getData(Document headerDom, Document detailDom, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				retTabSepStrBuff = null;
				if(conn != null && !conn.isClosed())
				{
					if(rs1 != null)
					{
						rs1.close();
						rs1=null;
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt=null;
					}
					conn.rollback();
					conn.close();
				}
			}
			catch(Exception e)
			{
				errString = e.getMessage();
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return resultString;
	}//END OF GETDATA(2)

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


		try
		{
				System.out.println("xmlString[process]::::::::::;;;"+xmlString);
				System.out.println("xmlString2[process]::::::::::;;;"+xmlString2);
				System.out.println("windowName[process]::::::::::;;;"+windowName);
				System.out.println("xtraParams[process]:::::::::;;;"+xtraParams);

		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			e.printStackTrace();
		}

		try
		{
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString);
				System.out.println("headerDom" + headerDom);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2);
				System.out.println("detailDom" + detailDom);
			}
			retStr = process(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println("Exception :WorkorderPrcEJB :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			retStr = e.getMessage();
			throw new ITMException(e);
		}
		return retStr;
	}//END OF PROCESS (1)
	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		int updCnt = 0;
		int parentNodeListLength = 0;
		int childNodeListLength = 0;
		String errString=null;
		String childNodeName = "";
		String siteCode = null;//this.siteCode;
		String itemCode=null;//for item code
		String dueDate=null;//for due date

		String tranId1=null;//for tran id
		String siteCode1=null;

		NodeList parentNodeList = null;
		NodeList childNodeList = null;

		Node parentNode = null;
		Node childNode = null;
		ArrayList tranList = new ArrayList();
		try
			{
				ConnDriver connDriver = new ConnDriver();
				conn = connDriver.getConnectDB("DriverITM");
				conn.setAutoCommit(false);
				connDriver = null;

			loginCode=genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			loginCode=blanknull(loginCode).trim();
			chgTerm=genericUtility.getValueFromXTRA_PARAMS(xtraParams,"termId");
			chgTerm=blanknull(chgTerm).trim();
			System.out.println("[WorkorderPrc][loginCode]=>"+loginCode);
			System.out.println("[WorkorderPrc][chgTerm]=>"+chgTerm);
			siteCode1 = genericUtility.getColumnValue("site_code",headerDom);	//from header
			System.out.println("[WorkorderPrc][SiteCode]=>"+siteCode1);
			siteCode1=blanknull(siteCode1).trim();
			parentNodeList = detailDom.getElementsByTagName("Detail2");
			parentNodeListLength = parentNodeList.getLength();
			System.out.println("parentNodeListLength:::::::::"+parentNodeListLength);

			for (int selectedRow = 0; selectedRow < parentNodeListLength; selectedRow++)
			{
				parentNode = parentNodeList.item(selectedRow);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				System.out.println("childNodeListLength::: "+ childNodeListLength+"\n");
				for (int childRow = 0; childRow < childNodeListLength; childRow++)
				{
					childNode = childNodeList.item(childRow);
					childNodeName = childNode.getNodeName();
					if (childNodeName.equals("tran_id"))
					{
						tranId1 = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("item_code"))
					{
						itemCode = childNode.getFirstChild().getNodeValue();
					}

					if (childNodeName.equals("due_date"))
					{
						dueDate = childNode.getFirstChild().getNodeValue();
					}
				}//inner for loop
				tranList.add(tranId1);
				System.out.println("[workorderPrc]tranId=>"+tranId1);
				/*errorString=calWorkorderPrc(tranId1,conn);
				if(errorString!=null)
				{
					try
					{
						conn.rollback();
						System.out.println("Connection is roll back");
						break;
					}
					catch(Exception d)
					{
						System.out.println("Exception : WorkorderPrcEJB =>"+d.toString());
						d.printStackTrace();
						break;
					}
				}//end of if*/
			}// OUT FOR LOOP

			errString=calWorkorderPrc(tranList,conn);
			if(errString !=null && errString.trim().length() > 0 )
			{
				try
				{
					conn.rollback();
					System.out.println("Connection is roll back");
					//break;
				}
				catch(Exception d)
				{
					System.out.println("Exception : WorkorderPrcEJB =>"+d.toString());
					d.printStackTrace();
					//break;
				}
			}//end of if
			else
			{

				try
				{
					System.out.println("Connection Commited");
					conn.commit();
					errString= itmDBAccessEJB.getErrorString("","VTSUCC","","",conn);
					System.out.println("errString from itmDBAccessEJB " + errString) ;
				}
				catch(Exception d)
				{
					System.out.println("Exception : WorkorderPrcEJB =>"+d.toString());
					d.printStackTrace();
					//break;
				}
			}
		}//try end
		catch(Exception e)
		{
			try
			{
				conn.rollback();
			}
			catch(Exception d)
			{
				System.out.println("Exception : WorkorderPrcEJB =>"+d.toString());
				d.printStackTrace();
			System.out.println("Exception :WorkorderPrcEJB :process(String xmlString2, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
			}
		}
		finally
		{
			System.out.println("errorString...." + errString);
			System.out.println("Closing Connection....");
			try
			{
				if(conn != null && !conn.isClosed())
				{
					conn.rollback();
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				errString = e.getMessage();
				e.printStackTrace();
				return errString ;
			}
		}
		System.out.println("Error Message=>"+errString);
		return errString;
	}//END OF PROCESS(2)

	private String calWorkorderPrc(ArrayList tranList,Connection conn) throws Exception,ITMException
	{
		ResultSet rs1 = null,rsSql1=null,rsSql2=null;
		PreparedStatement pstmt = null,pstmtInsert=null,pstmtUpdate=null,pstmtSql1=null,pstmtSql2=null;

		int i=0;
		double quantity=0.0;
		double yieldPerc=0.0;

		String workOrder=null;
		String orderType=null;
		String routeCode=null;
		String bomCode=null;
		String unit=null;
		String mrpRunId=null;
		String acctCodeWp=null;
		String cctrCodeWp=null;
		String addnOrder=null;
		String planDueDate=null;
		String tranId=null;
		String dbdate=null;
		String tranId_db=null;
		String itemSer=null;
		String siteCode=null;
		String itemCode=null;
		String dueDate=null;
		String tranDate=null;
		String itemSer1=null,itemSer2=null,strResult=null;
		String xmlValues = "";
		String feedBackValue=null;

		StringTokenizer st=null;//for itemSeries
		ArrayList ar=new ArrayList();
		Timestamp chgDate=null;
		String deptCodeMfg = "";
		GenericUtility genericUtility = GenericUtility.getInstance();

		String tranId1 = null; //blanknull(tranId1).trim();

		String sqlSelect = " SELECT WORK_ORDER,ORDER_TYPE,QUANTITY,YIELD_PERC, ROUTE_CODE, "
					+" BOM_CODE, UNIT, MRP_RUN_ID, ACCT_CODE__WP, CCTR_CODE__WP,ADDN_ORDER,"
					+" PLAN_DUE_DATE,TRAN_ID,SITE_CODE,ITEM_CODE,DUE_DATE "
					+" FROM MPS_ORDER WHERE TRAN_ID=?";

		String sqlInsert = "INSERT INTO WORKORDER(WORK_ORDER,ORDER_TYPE,QUANTITY,YIELD_PERC,ROUTE_CODE,BOM_CODE,"
			+" UNIT,MRP_RUN_ID,ACCT_CODE__WP,CCTR_CODE__WP,ADDN_ORDER,PLAN_DUE_DATE,TRAN_ID,SITE_CODE,"
			+" ITEM_CODE,ORD_DATE,DUE_DATE,STATUS,STATUS_DATE,FEEDBACK_REQD,CHG_DATE,CHG_USER,CHG_TERM,QUANTITY__RCVD,"
			+" CURRENT_BATCH_QTY,UNIT__STD,STD_QTY,CONV__QTY_STDUOM,QUANTITY__MPS,TRAN_ID__MPS, LOT_SL, DEPT_CODE) "
			+" VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'1S',?)";


		String sqlUpdate = " UPDATE MPS_ORDER SET STATUS = 'C'	WHERE TRAN_ID =?" ;

		String sql1="SELECT VAR_VALUE FROM MFGPARM WHERE PRD_CODE='999999' AND VAR_NAME='PROC_FDBK_INTEGRATED'";
		String sql2=null;

		System.out.println("[WorkorderPrc]calWorkorderPrc() method called");

		try
		{
			// 30/06/10 manoharan
			deptCodeMfg = itmDBAccessEJB.getEnvDis("999999", "DEPT_CODE_MFG",conn);
			// end 30/06/10 manoharan
			//=========Code to seperate tokens and add to array list===============
			pstmtSql1=conn.prepareStatement(sql1);
			rsSql1=pstmtSql1.executeQuery();
			while(rsSql1.next())
			{
				strResult=rsSql1.getString(1);
				st=new StringTokenizer(strResult,",");
				while(st.hasMoreElements())
				{
					ar.add(st.nextToken());//tokens are added to array list
				}
			}
			rsSql1.close();//close rsSql1
			pstmtSql1.close();//close pstmtSql1
			//=================================================
			pstmtInsert=conn.prepareStatement(sqlInsert);
			pstmt = conn.prepareStatement(sqlSelect);
			pstmtUpdate = conn.prepareStatement(sqlUpdate);
			for (int ctr = 0; ctr < tranList.size(); ctr++)
			{
				tranId1 = (String) tranList.get(ctr);
				pstmt.setString(1,tranId1.trim());
				rs1 = pstmt.executeQuery();


				while(rs1.next())
				{
					workOrder=rs1.getString(1);
					orderType=rs1.getString(2);
					quantity=rs1.getDouble(3);
					yieldPerc=rs1.getDouble(4);
					routeCode=rs1.getString(5);
					bomCode=rs1.getString(6);
					unit=rs1.getString(7);
					mrpRunId=rs1.getString(8);
					acctCodeWp=rs1.getString(9);
					cctrCodeWp=rs1.getString(10);
					addnOrder=rs1.getString(11);
					planDueDate=rs1.getString(12);
					tranId_db=rs1.getString(13);//selected from mps_order table
					siteCode=rs1.getString(14);//for sitecode
					itemCode=rs1.getString(15);//for itemcode
					dueDate=rs1.getString(16);//for dueDate

					//=====FUNCTION blanknull() is to avoid NullPointerException==========
					workOrder=blanknull(workOrder);
					orderType=blanknull(orderType);
					routeCode=blanknull(routeCode);
					bomCode=blanknull(bomCode);
					unit=blanknull(unit);
					mrpRunId=blanknull(mrpRunId);
					acctCodeWp=blanknull(acctCodeWp);
					cctrCodeWp=blanknull(cctrCodeWp);
					addnOrder=blanknull(addnOrder);
					planDueDate=blanknull(planDueDate);
					tranId_db=blanknull(tranId_db);
					siteCode=blanknull(siteCode);
					itemCode=blanknull(itemCode);
					dueDate=blanknull(dueDate);

					tranDate=genericUtility.getValidDateString(new Timestamp(System.currentTimeMillis()).toString(),
					genericUtility.getDBDateFormat(),
					genericUtility.getApplDateFormat());
					tranDate=blanknull(tranDate);


					xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
					xmlValues = xmlValues + "<Header></Header>";
					xmlValues = xmlValues + "<Detail1>";
					xmlValues = xmlValues +	"<tran_id></tran_id>";
					xmlValues = xmlValues +	"<work_order>"+workOrder.trim()+"</work_order>";
					xmlValues = xmlValues + "<site_code>"+siteCode.trim()+"</site_code>";
					xmlValues = xmlValues +  "<ord_date>"+tranDate.trim()+"</ord_date>";
					xmlValues = xmlValues + "<order_type>"+orderType.trim()+"</order_type>";
					xmlValues = xmlValues + "</Detail1></Root>";

					tranId = generateTranId("w_worder",xmlValues);//function to generate NEW transaction id
					//tranId = generateTranId("w_work_order",xmlValues);//function to generate NEW transaction id
					if(tranId==null || blanknull(tranId).trim().equals("") || tranId.equalsIgnoreCase("error"))
					{
						errorString="Error Occured";
						break;
					}

					//************* if tranidfenerator returned error what?

					System.out.println("[WorkorderPrcEJB][workorder]=>"+workOrder);
					System.out.println("[WorkorderPrcEJB][orderType]=>"+orderType);
					System.out.println("[WorkorderPrcEJB][quantity]=>"+quantity);
					System.out.println("[WorkorderPrcEJB][yieldPerc]=>"+yieldPerc);
					System.out.println("[WorkorderPrcEJB][routeCode]=>"+routeCode);
					System.out.println("[WorkorderPrcEJB][bomCode]=>"+bomCode);
					System.out.println("[WorkorderPrcEJB][unit]=>"+unit);
					System.out.println("[WorkorderPrcEJB][mrpRunId]=>"+mrpRunId);
					System.out.println("[WorkorderPrcEJB][acctCodeWp]=>"+acctCodeWp);
					System.out.println("[WorkorderPrcEJB][cctrCodeWp]=>"+cctrCodeWp);
					System.out.println("[WorkorderPrcEJB][addnOrder]=>"+addnOrder);
					System.out.println("[WorkorderPrcEJB][planDueDate]=>"+planDueDate);
					System.out.println("[WorkorderPrcEJB][tranId]=>"+tranId);
					System.out.println("[WorkorderPrcEJB][siteCode]=>"+siteCode);
					System.out.println("[WorkorderPrcEJB][itemCode]=>"+itemCode);
					System.out.println("[WorkorderPrcEJB][dueDate]=>"+dueDate);
					System.out.println("[WorkorderPrcEJB][tranDate]=>"+tranDate);
					System.out.println("[WorkorderPrcEJB][tranIddb]=>"+tranId_db);

					pstmtInsert.setString(1,tranId.trim());//for work_order
					pstmtInsert.setString(2,orderType.trim());//for ordertype
					pstmtInsert.setDouble(3,quantity);//for quantity
					pstmtInsert.setDouble(4,yieldPerc);//for yield_perc
					if(routeCode.equalsIgnoreCase("null"))
					{
						pstmtInsert.setNull(5,java.sql.Types.VARCHAR);
					}
					else
					{
						pstmtInsert.setString(5,routeCode);//for route_code
					}
					pstmtInsert.setString(6,bomCode.trim());//for bom_code
					pstmtInsert.setString(7,unit.trim());//for unit
					pstmtInsert.setString(8,mrpRunId.trim());//for mrs_run_id
					pstmtInsert.setString(9,acctCodeWp.trim());//for acct_code_wp
					pstmtInsert.setString(10,cctrCodeWp.trim());//for cctr_code_wp
					pstmtInsert.setString(11,addnOrder.trim());//for addn_order
					//conversion of date from string to timestamp
					if (planDueDate != null && planDueDate.trim().length() > 0 )
					{
						chgDate=java.sql.Timestamp.valueOf(planDueDate.trim());
					}
					else
					{
						chgDate = java.sql.Timestamp.valueOf(dueDate.trim());
					}

					pstmtInsert.setTimestamp(12,chgDate);//for plan_duedate
					pstmtInsert.setString(13,tranId.trim());//for tranid
					pstmtInsert.setString(14,siteCode.trim());//for site_code
					pstmtInsert.setString(15,itemCode.trim());//for item_code

					System.out.println("[WorkorderPrc]=>"+java.sql.Timestamp.valueOf(getCurrdateAppFormat().toString()));
					pstmtInsert.setTimestamp(16,java.sql.Timestamp.valueOf(getCurrdateAppFormat().toString()));//for ord_date
					pstmtInsert.setTimestamp(17,java.sql.Timestamp.valueOf(dueDate.trim()));//for due_date
					pstmtInsert.setString(18,"P");//for status
					pstmtInsert.setTimestamp(19,new Timestamp(System.currentTimeMillis()));//for status_date


					sql2="SELECT ITEM_SER FROM ITEM WHERE ITEM_CODE='"+itemCode.trim()+"'";
					pstmtSql2=conn.prepareStatement(sql2);
					rsSql2=pstmtSql2.executeQuery();
					while(rsSql2.next())
					{
						itemSer=rsSql2.getString(1);
					}
					itemSer=blanknull(itemSer).trim();
					feedBackValue="N";
					for(i=0;i<ar.size();i++)
					{
						itemSer2=ar.get(i).toString();
						itemSer2=blanknull(itemSer2).trim();
						if(itemSer.equalsIgnoreCase(itemSer2))
						{
							feedBackValue="Y";
							break;
						}
					}
					pstmtInsert.setString(20,feedBackValue);//for feedback_reqd
					rsSql2.close();
					pstmtSql2.close();

					pstmtInsert.setTimestamp(21,new Timestamp(System.currentTimeMillis()));//for chg_date
					pstmtInsert.setString(22,loginCode.trim());//for chg_user
					pstmtInsert.setString(23,chgTerm.trim());//for chg_term
					pstmtInsert.setDouble(24,0);//for quantity_rcvd
					pstmtInsert.setDouble(25,quantity);//for current_batch_qty.
					pstmtInsert.setString(26,unit.trim());//for unit__std
					pstmtInsert.setDouble(27,quantity);//for std_qty
					pstmtInsert.setDouble(28,1);//foR con__qty_stduom
					pstmtInsert.setDouble(29,quantity);//for quantity__mps
					pstmtInsert.setString(30,tranId_db);//for tran_id__mps
					pstmtInsert.setString(31,deptCodeMfg); // 30/06/10 manoharan

					pstmtInsert.addBatch();

					//===========Code to update Record in MPS_ORDER table==========

					pstmtUpdate.setString(1,tranId_db.trim());
					pstmtUpdate.addBatch();
				}//end of while loop
			}
			pstmtInsert.executeBatch();
			pstmtUpdate.executeBatch();

			rs1.close();
			pstmt.close();
			pstmtInsert.close();
			pstmtUpdate.close();
		}
		catch(SQLException se)
		{
			System.out.println("SQLException in WorkorderPrcEJB:"+sqlInsert+"<====>"+sqlUpdate);
			se.printStackTrace();
			errorString=se.getMessage();
			throw new ITMException(se);
		}
		catch(Exception e)
		{
			System.out.println("SQLException in WorkorderPrcEJB:"+sqlInsert+"<====>"+sqlUpdate);
			e.printStackTrace();
			errorString=e.getMessage();
			throw new ITMException(e);
		}
		return errorString;
	}//END OF Method

	public String blanknull(String s)
	{
		if(s==null)
			return "";
		else
			return s;
	}//end of blanknull()


	private String generateTranId(String windowName,String xmlValues) throws Exception,ITMException
	{
		Statement stmt = null;
		ResultSet rs = null;
		String sql = "";
		String tranId = null;
		String newKeystring = "";
		String srType = "RS";
		 try
	     {
	    	sql = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE UPPER(TRAN_WINDOW)=UPPER('"+windowName+"')";
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			System.out.println("keyString :"+rs.toString());
			String tranSer1 = "";
			String keyString = "";
			String keyCol = "";
			if (rs.next())
			{
				keyString = rs.getString(1);
				keyCol = rs.getString(2);
				tranSer1 = rs.getString(3);
			}
			System.out.println("keyString=>"+keyString);
			System.out.println("keyCol=>"+keyCol);
			System.out.println("tranSer1"+tranSer1);

			System.out.println("xmlValues  :["+xmlValues+"]");
			loginCode=blanknull(loginCode);
			TransIDGenerator tg = new TransIDGenerator(xmlValues, loginCode.trim(), commonConstants.DB_NAME);
			tranId = tg.generateTranSeqID(tranSer1, keyCol, keyString, conn);
			System.out.println("tranId :"+tranId);
			if(rs!=null)
			 {
				rs.close();
			 }
			 if(stmt!=null)
			 {
				stmt.close();
			 }
		}
		catch(SQLException ex)
		{
			System.out.println("Exception ::" +sql+ ex.getMessage() + ":");
			ex.printStackTrace();
			tranId=null;
			throw new ITMException(ex);
		}
		catch(Exception e)
		{
			System.out.println("Exception ::" + e.getMessage() + ":");
			e.printStackTrace();
			tranId=null;
			throw new ITMException(e);
		}
		return tranId;
	}//generateTranTd()
	private Timestamp getCurrdateAppFormat()
	{
		String currAppdate ="";
		java.sql.Timestamp currDate = null;
		try
		{
				Object date = null;
				currDate =new java.sql.Timestamp(System.currentTimeMillis()) ;
				SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
				date = sdf.parse(currDate.toString());
				currDate =	java.sql.Timestamp.valueOf(sdf.format(date).toString() + " 00:00:00.0");
		}
		catch(Exception e)
		{
			System.out.println("Exception in :::WorkorderPrcEJB"+e.getMessage());
			e.printStackTrace();
		}
		return (currDate);
	}
}//END OF EJB