/**
 * PURPOSE : Validation and Item Change implementation for carton deallocation component.
 * AUTHOR : Sumit
 * Date: 02/1/13
 */
package ibase.webitm.ejb.wms;

import java.io.*;
import java.rmi.RemoteException;
import java.sql.*;
import java.text.*;
import java.util.*;
import java.util.Date;

import javax.ejb.*;
import javax.naming.InitialContext;
import javax.xml.parsers.*;
import org.w3c.dom.*;

import ibase.ejb.*;
import ibase.system.config.*;
//import ibase.utility.BaseLogger;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

@javax.ejb.Stateless
public class DeallocArtIC extends ValidatorEJB implements DeallocArtICRemote, DeallocArtICLocal  
{
	/**
	 * The method is defined without any parameter and returns blank string
	 */
	public String wfValData() throws RemoteException,ITMException
	{
		return "";
	}

	/**
	 * The public method is used for converting the current form data into a document(DOM)
	 * The currDom is then given as argument to the overloaded function wfValData to perform validation
	 * Returns validation string if exists else returns null in XML format
	 * @param currFrmXmlStr contains the current form data in XML format
	 * @param hdrFrmXmlStr contains all the header information in the XML format
	 * @param allFrmXmlStr contains the data of all the forms in XML format
	 * @param objContext represents the form number
	 * @param editFlag represents the mode of transaction(A-Add or E-Edit)
	 * @param xtraParams contains additional information such as loginEmpCode,loginCode,chgTerm etc
	 */
	public String wfValData(String currFrmXmlStr, String hdrFrmXmlStr,String allFrmXmlStr, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Document currDom = null;
		Document hdrDom = null;
		Document allDom = null;
		String errString = "";

		try
		{
			System.out.println("currFrmXmlStr :: "+ currFrmXmlStr);
			System.out.println("hdrFrmXmlStr :: "+ hdrFrmXmlStr);
			System.out.println("allFrmXmlStr :: "+ allFrmXmlStr);
			if(currFrmXmlStr != null && currFrmXmlStr.trim().length()!=0)
			{
				currDom = parseString(currFrmXmlStr); 
			}
			if(hdrFrmXmlStr != null && hdrFrmXmlStr.trim().length()!=0)
			{
				hdrDom = parseString(hdrFrmXmlStr); 
			}
			if(allFrmXmlStr != null && allFrmXmlStr.trim().length()!=0)
			{
				allDom = parseString(allFrmXmlStr);
			}			
			errString = wfValData(currDom,hdrDom,allDom,objContext,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [DeallocArtIC][wfValData(String xmlCurrFrmString)] : ==>\n"+e.getMessage());
			throw new ITMException(e);
		}
		return (errString); 
	}

	/**
	 * The public overloaded method takes a document as input and is used for the validation of specified fields 
	 * Returns validation string if exist otherwise returns null in XML format
	 * @param currDom contains the current form data as a document object model
	 * @param hdrDom contains all the header information
	 * @param allDom contains the field data of all the forms 
	 * @param objContext represents form number
	 * @param editFlag represents the mode of transaction(A-Add or E-Edit)
	 * @param xtraParams contains additional information such as loginEmpCode,loginCode,chgTerm etc
	 */	
	public String wfValData(Document currDom, Document hdrDom, Document allDom, String objContext, String editFlag, String xtraParams) throws RemoteException, ITMException 	
	{
		String errString = "";
		String siteCode = "";

		ResultSet rs = null, rs1 = null;
		//ResultSet rsInner = null;
		Connection conn = null;
		PreparedStatement pstmt = null, pstmt1 = null;
		//PreparedStatement pstmtInner = null;
		
		System.out.println("obj context::"+objContext);
		System.out.println("edit flg::"+editFlag);
		System.out.println("xtraparm::"+xtraParams);

		GenericUtility genericUtility = GenericUtility.getInstance();

		StringBuffer errStringXml = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root><Errors>");
		String errorType = "", errCode = "";
		ArrayList errList = new ArrayList();
		ArrayList errFields = new ArrayList();
		String holdStatus = "N";
		String cancelStatus = "N";

		try
		{
			String columnValue = "";
			String sql = "";	
			//String tranID = "";
			String ptcn = "";
			String cartonNo = "";
			

			int currentFormNo = 0, cnt = 0, count = 0;		

			ConnDriver connDriver = null;
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");

			NodeList parentList = null;
			NodeList childList = null;

			int noOfChilds = 0;

			String childNodeName = "";

			Node childNode =null;

			String userId = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" );
			if ( objContext != null && objContext.trim().length() > 0 )
			{
				currentFormNo = Integer.parseInt( objContext );
			}

			switch(currentFormNo)
			{
			case 1 :
			{
				parentList = currDom.getElementsByTagName( "Detail" + currentFormNo );
				System.out.println("parent list="+parentList);
				childList = parentList.item( 0 ).getChildNodes();
				System.out.println("child list"+childList);
				noOfChilds = childList.getLength();
				for (int ctr = 0; ctr < noOfChilds; ctr++)
				{	
					childNode = childList.item( ctr );
					if( childNode.getNodeType() != Node.ELEMENT_NODE )
					{
						continue;
					}
					childNodeName = childNode.getNodeName();						
					if ( childNode != null && childNode.getFirstChild() != null )
					{
						columnValue = childNode.getFirstChild().getNodeValue();
					}
					System.out.println(" columnName [" + childNodeName + "] columnValue [" + columnValue + "]");
					
					if ( "ptcn".equalsIgnoreCase( childNodeName ) )
					{							
						ptcn = genericUtility.getColumnValue("ptcn", currDom );
						
						if( ptcn == null || ptcn.trim().length() == 0 )
						{
							errList.add( "NULLPTCNID" );
							errFields.add( childNodeName.toLowerCase() );
						}
						
						sql = "SELECT DISTINCT CASE WHEN H.HOLD_STATUS IS NULL THEN 'N' ELSE H.HOLD_STATUS END AS HOLD_STATUS , "
							+ " CASE WHEN H.CANCEL IS NULL THEN 'N' ELSE H.CANCEL END AS CANCEL FROM WAVE_TASK H, WAVE_TASK_DET D "
							+ " WHERE H.WAVE_ID = D.WAVE_ID "
							+ " AND D.PTCN = ? ";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, ptcn);
						rs = pstmt.executeQuery();
						if (rs.next())
						{
							holdStatus = rs.getString("HOLD_STATUS");
							cancelStatus = rs.getString("CANCEL");
							
							if( "N".equalsIgnoreCase(holdStatus) && "N".equalsIgnoreCase(cancelStatus))
							{
								/*sql = "";
								sql = "SELECT WAVE_ID, PTCN, REF_TYPE FROM WAVE_TASK_DET WHERE PTCN = ? AND REF_TYPE IN (?,?) ";
								pstmt1 = conn.prepareStatement(sql);
								pstmt1.setString(1, ptcn);
								pstmt1.setString(2, "C");
								pstmt1.setString(3, "M");
								rs1 = pstmt1.executeQuery();
								if( !rs1.next())
								{
									errList.add( "INVPTCNCAP" ); //do not have case pick task in this ptcn
									errFields.add( childNodeName.toLowerCase() );
									break;
								}
								rs1.close(); rs1 = null;
								pstmt1.close(); pstmt1 = null;*/
								
								if("A".equalsIgnoreCase(editFlag))
								{
									sql= "";
									sql = " SELECT CM.CARTON_NO, POD.SALE_ORDER, POD.LINE_NO__SORD, CM.PICK_ORDER, CM.LINE_NO__PICK, " +
											" POD.ITEM_CODE,  POD.LOC_CODE, POD.LOT_NO, POD.LOT_SL, WTD.WAVE_ID, POH.PICK_TYPE " +
											" FROM CARTON_MASTER CM, PICK_ORD_DET POD , PICK_ORD_HDR POH, WAVE_TASK_DET WTD WHERE CM.PTCN = ? " +
											" AND CM.PICK_ORDER = POD.PICK_ORDER AND POH.PICK_ORDER = POD.PICK_ORDER " +
											" AND CM.LINE_NO__PICK = POD.LINE_NO AND WTD.PTCN = CM.PTCN " +
											" AND WTD.REF_ID = CM.PICK_ORDER  ";
											//" AND POH.PICK_TYPE IN (?,?) ";
											//" AND ( FN_CHECK_DEALLOC_ARTDET(CM.PTCN, CM.CARTON_NO ) = 0 ) "+					
											//" AND CM.STATUS <> ? ";		
										
									pstmt1 = conn.prepareStatement(sql);		
									pstmt1.setString(1, ptcn);		
									//pstmt1.setString(2, "C");
									//pstmt1.setString(3, "M");
									//pstmt1.setString(4, "R");
									rs1 = pstmt1.executeQuery();
									if( !rs1.next() )
									{
										errList.add( "INVPTCASAD" ); 
										errFields.add( childNodeName.toLowerCase() );
										break;
									}
									rs1.close(); rs1 = null;
									pstmt1.close(); pstmt1 = null;
								}
							}							
							
						}
						else
						{
							errList.add( "INVPTCNNO" ); //invalid ptcn
							errFields.add( childNodeName.toLowerCase() );
						}
						
						System.out.println(" holdStatus ["+holdStatus+"] cancelStatus ["+cancelStatus+"]");
						if( "Y".equalsIgnoreCase(holdStatus) || "Y".equalsIgnoreCase(cancelStatus))
						{
							errList.add( "INVPTCNCAN" ); // ptcn is on hold or cancel
							errFields.add( childNodeName.toLowerCase() );
						}
						else
						{
							sql = " SELECT D.CONFIRMED FROM DESPATCH D, WAVE_TASK_DET W " +
									" WHERE W.PTCN = ?  AND D.WAVE_ID = W.WAVE_ID AND W.REF_ID = D.DESP_ID";
							pstmt1 = conn.prepareStatement(sql);
							pstmt1.setString(1, ptcn);
							rs1 = pstmt1.executeQuery();
							if(rs1.next())
							{
								System.out.println(" confirmed ["+rs1.getString("CONFIRMED")+"]");
								if("Y".equalsIgnoreCase(rs1.getString("CONFIRMED")))
								{
									errList.add( "INVPTCNDSP" );  // Despatch already confirmed for this ptcn
									errFields.add( childNodeName.toLowerCase() );
								}
							}
							rs1.close(); rs1 = null;
							pstmt1.close(); pstmt1 = null;
							
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						
						if( rs1 != null )
						{
							rs1.close();
							rs1 = null;
						}
						if( pstmt1 != null )
						{
							pstmt1.close(); pstmt1 = null;
						}
						
					}			
							
				}// for loop end
			}//case 1 end
			break;
			case 2 : //for hdr win val....
			{
				parentList = currDom.getElementsByTagName( "Detail" + currentFormNo );
				childList = parentList.item( 0 ).getChildNodes();
				noOfChilds = childList.getLength();
				for (int ctr = 0; ctr < noOfChilds; ctr++)
				{	
					childNode = childList.item( ctr );
					if( childNode.getNodeType() != Node.ELEMENT_NODE )
					{
						continue;
					}
					childNodeName = childNode.getNodeName();						
					if ( childNode != null && childNode.getFirstChild() != null )
					{
						columnValue = childNode.getFirstChild().getNodeValue();
					}
					System.out.println(" * columnName [" + childNodeName + "] columnValue [" + columnValue + "]");

					if ( "carton_no".equalsIgnoreCase( childNodeName ) )
					{							
						cartonNo = genericUtility.getColumnValue("carton_no", currDom );
						ptcn = checkNull(genericUtility.getColumnValue("ptcn", hdrDom ));
						System.out.println(" cartonNo ["+cartonNo+"] ptcn["+ptcn+"]");
						
						if( cartonNo == null || cartonNo.trim().length() == 0 )
						{
							errList.add( "NULLCARTNO" );
							errFields.add( childNodeName.toLowerCase() );
						}
						else
						{
							sql = "";
							sql = " SELECT C.CARTON_NO, C.STATUS, C.PTCN, W.CANCEL FROM CARTON_MASTER C, WAVE_TASK W , WAVE_TASK_DET WT " +
								  " WHERE C.CARTON_NO = ? AND C.CARTON_TYPE = 'C' AND W.WAVE_ID = WT.WAVE_ID AND WT.REF_ID = C.PICK_ORDER ";							
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, cartonNo);					 
							rs = pstmt.executeQuery();
							if (rs.next())
							{
								System.out.println(" ptcn ["+rs.getString("PTCN")+"] STATUS["+rs.getString("STATUS")+"] CANCEL ["+rs.getString("CANCEL")+"]");
								if("R".equalsIgnoreCase(rs.getString("STATUS")))
								{
									errList.add( "INVCARTON2" );
									errFields.add( childNodeName.toLowerCase() );
									break;
								}
								else if( !ptcn.equalsIgnoreCase(rs.getString("PTCN")))
								{
									errList.add( "INVPTCNCAR" );
									errFields.add( childNodeName.toLowerCase() );
									break;
								}
								else if( "Y".equalsIgnoreCase(rs.getString("CANCEL")))
								{
									errList.add( "INVCARTON3" );
									errFields.add( childNodeName.toLowerCase() );
									break;
								}
								else
								{
									sql ="";
									sql = " SELECT C.CARTON_NO, C.PICK_ORDER,C.LINE_NO__PICK, PH.PICK_TYPE, PD.ITEM_CODE, PD.QUANTITY, C.PTCN " +
											" FROM CARTON_MASTER C , PICK_ORD_HDR PH, PICK_ORD_DET PD " +
											" WHERE C.CARTON_NO = ? AND PD.PICK_ORDER = C.PICK_ORDER AND PD.LINE_NO = C.LINE_NO__PICK " +
											" AND PD.PICK_ORDER = PH.PICK_ORDER AND PH.PICK_TYPE IN (?,?) " +
											" AND C.STATUS = 'R'";
									
									pstmt1 = conn.prepareStatement(sql);
									pstmt1.setString(1, cartonNo);
									pstmt1.setString(2, "C");
									pstmt1.setString(3, "M");
									rs1 = pstmt1.executeQuery();
									if (rs1.next())
									{
										errList.add( "INVCARALEX" );
										errFields.add( childNodeName.toLowerCase() );
										break;
									}
									rs1.close(); rs1= null;
									pstmt1.close(); pstmt1 = null;
									
								}
							}
							else
							{
								errList.add( "INVCARTON1" );
								errFields.add( childNodeName.toLowerCase() );
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
							
							if(rs1 != null)
							{
								rs1.close(); rs1 = null;
							}
							if(pstmt1 != null)
							{
								pstmt1.close(); pstmt1 =null;
							}
							
							/*
							sql = ""; 
							sql = " SELECT CM.CARTON_NO, CM.STATUS, CM.PTCN FROM CARTON_MASTER CM , PICK_ISS_DET PID , PICK_ISS_HDR PIH "+
									" WHERE CM.CARTON_NO = ? AND PIH.TRAN_ID = PID.TRAN_ID AND PIH.PICK_ORDER = PID.PICK_ORDER "+
									" AND CM.PICK_ORDER = PID.PICK_ORDER AND CM.LINE_NO__PICK = PID.LINE_NO__ORD AND PIH.CONFIRMED = 'Y' ";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, cartonNo);
							rs = pstmt.executeQuery();
							if( !rs.next())
							{
								errList.add( "INVPICKISS" );
								errFields.add( childNodeName.toLowerCase() );
								break;
							}
							rs.close();rs = null;
							pstmt.close(); pstmt = null;
							*/
							
						  ArrayList arrayList = new ArrayList(); 
						  arrayList = checkDuplicateCarton(allDom);
						  Set s = new HashSet(arrayList);
						  System.out.println("Size of arrayList ["+arrayList.size()+"]");
						  System.out.println("Size of Set ["+s.size()+"]");						  
						  if(s.size() < arrayList.size())
						  {
							  	errList.add( "DUPCARTONN" );
								errFields.add( childNodeName.toLowerCase() );
								break;							  
						  }
							
						}
					}
					/*else if ( "pick_order".equalsIgnoreCase( childNodeName ) )
					{							
						siteCode = genericUtility.getColumnValue("pick_order", currDom );

						if( siteCode == null || siteCode.trim().length() == 0 )
						{
							errList.add( "NULLSITECD" );
							errFields.add( childNodeName.toLowerCase() );
						}

						sql = "SELECT COUNT(*) AS COUNT FROM SITE WHERE SITE_CODE = ?";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, siteCode);

						rs = pstmt.executeQuery();
						if (rs.next())
						{
							cnt = rs.getInt("COUNT");
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						if(cnt == 0)
						{
							errList.add( "INVSITECD" );
							errFields.add( childNodeName.toLowerCase() );
						}
					}*/
				}// for loop end 
 			}//case 2 end
			break;
			
			} //switch end
			int errListSize = errList.size();
			cnt =0;
			String errFldName = null;
			if ( errList != null && errListSize > 0 )
			{
				for (cnt = 0; cnt < errListSize; cnt++ )
				{
					errCode = (String)errList.get(cnt);
					errFldName = (String)errFields.get(cnt);
					System.out.println("errCode .........."+errCode);
					//String errMsg = hashMap.get(errCode)!=null ? hashMap.get(errCode).toString():"";
					//System.out.println("errMsg .........."+errMsg);
					errString = getErrorString( errFldName, errCode, userId );
					errorType =  errorType( conn , errCode );
					if ( errString.length() > 0)
					{
						String bifurErrString = errString.substring( errString.indexOf("<Errors>") + 8,errString.indexOf("<trace>"));
						bifurErrString =bifurErrString;//+"<trace>"+errMsg+"</trace>";
						bifurErrString =bifurErrString+errString.substring( errString.indexOf("</trace>") + 8,errString.indexOf("</Errors>"));
						errStringXml.append(bifurErrString);
						System.out.println("errStringXml .........."+errStringXml);
						errString = "";
					}
					if ( errorType.equalsIgnoreCase("E"))
					{
						break;
					}
				}
				errList.clear();
				errList = null;
				errFields.clear();
				errFields = null;

				errStringXml.append("</Errors></Root>\r\n");
			}
			else
			{
				errStringXml = new StringBuffer( "" );
			}
			errString = errStringXml.toString();
		}//try block end
		catch(Exception e)
		{
			System.out.println("Exception in DeallocArtIC  == >");
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if (rs1 != null)
				{
					rs1.close();
					rs1 = null;
				}
				if (pstmt1 != null)
				{
					pstmt1.close();
					pstmt1 = null;
				}
				if( conn != null && ! conn.isClosed() )
				{
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				System.out.println( "Exception :DeallocArtIC:wfValData :==>\n"+e.getMessage());
				throw new ITMException(e);
			}
		}
		return errString;
	}
	private String errorType( Connection conn , String errorCode ) throws ITMException
	{
		String msgType = "";
		PreparedStatement pstmt = null ; 
		ResultSet rs = null;
		try
		{			
			String  sql = " SELECT MSG_TYPE FROM MESSAGES WHERE MSG_NO =   ? ";

			pstmt = conn.prepareStatement( sql );			
			pstmt.setString(1, errorCode);			
			rs = pstmt.executeQuery();
			while( rs.next() )
			{
				msgType = rs.getString("MSG_TYPE");
			}			
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			throw new ITMException(ex);
		}		
		finally
		{
			try
			{
				if ( rs != null )
				{
					rs.close();
					rs = null;
				}
				if ( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch ( Exception e )
			{
				e.printStackTrace();
				throw new ITMException(e);
			}
		}		
		return msgType;
	}

	// Item Change Functionality. Start.		
	/**
	 * The public method is defined without any parameters and returns blank string
	 */
	public String itemChanged() throws RemoteException, ITMException
	{
		return "";
	}

	/**
	 * The public method is used for converting the current form data into a document(dom)
	 * The currDom is then given as argument to the overloaded function wfValData to perform validation
	 * Returns validation string if exists else returns null in XML format
	 * @param currFrmXmlStr contains the current form data in XML format
	 * @param hdrFrmXmlStr contains all the header information in the XML format
	 * @param allFrmXmlStr contains the data of all the forms in XML format
	 * @param objContext represents the form number
	 * @param currentColumn represents the value of current field.
	 * @param editFlag represents the mode of transaction(A-Add or E-Edit)
	 * @param xtraParams contains additional information such as loginEmpCode,loginCode,chgTerm etc
	 */
	public String itemChanged(String currFrmXmlStr, String hdrFrmXmlStr, String allFrmXmlStr, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		Document currDom = null;
		Document hdrDom = null;
		Document allDom = null;

		String errString = null;

		GenericUtility genericUtility = GenericUtility.getInstance();

		try
		{
			System.out.println("currFrmXmlStr :: "+ currFrmXmlStr);
			System.out.println("hdrFrmXmlStr :: "+ hdrFrmXmlStr);
			System.out.println("allFrmXmlStr :: "+ allFrmXmlStr);
			if (currFrmXmlStr != null && currFrmXmlStr.trim().length()!=0)
			{
				currDom = genericUtility.parseString(currFrmXmlStr); 
			}
			if (hdrFrmXmlStr != null && hdrFrmXmlStr.trim().length()!=0)
			{
				hdrDom = genericUtility.parseString(hdrFrmXmlStr); 
			}
			if (allFrmXmlStr != null && allFrmXmlStr.trim().length()!=0)
			{
				allDom = genericUtility.parseString(allFrmXmlStr); 
			}
			errString = itemChanged( currDom, hdrDom, allDom, objContext, currentColumn, editFlag, xtraParams );
			System.out.println ( "ErrString :" + errString);
		}
		catch (Exception e)
		{
			System.out.println ( "Exception : DeallocArtIC :defaul_ItemChanged(String,String):" + e.getMessage() + ":" );
			errString = genericUtility.createErrorString(e);
			throw new ITMException(e);
		}
		System.out.println ( "returning from DeallocArtIC default_Itemchanged" );
		return errString;
	}	

	/**
	 * The public overloaded method takes a document as input and is used for the validation of required fields 
	 * Returns validation string if exist otherwise returns null in XML format
	 * @param currDom contains the current form data as a document object model
	 * @param hdrDom contains all the header information
	 * @param allDom contains the field data of all the forms 
	 * @param objContext represents form number
	 * @param currentColumn represents the current field 
	 * @param editFlag represents the mode of transaction(A-Add or E-Edit)
	 * @param xtraParams contains additional information
	 * 
	 */


	public String itemChanged( Document currDom, Document hdrDom, Document allDom, String objContext, String currentColumn, String editFlag, String xtraParams ) throws RemoteException,ITMException
	{
		String sql = "";
		String sql1 = "";
		String ptcn = "";
		String siteCode = "";
		String siteDescr = "";
		String tranID = "";	
		String saleOrder ="";
		String empCodeAprv = "";		
		String tranDate = "";
		String confDate = "";
		String pickOrder = "";
		String CartonNo = "";
		int lineNo = 0;
		int count= 0;


		int currentFormNo = 0;
		int domID = 0;

		double quantity = 0d;

		ResultSet rs = null;
		Connection conn = null;
		PreparedStatement pstmt = null;

		ResultSet rs1 = null;
		PreparedStatement pstmt1 = null;

		
		
		StringBuffer valueXmlString = new StringBuffer();		

		GenericUtility genericUtility = GenericUtility.getInstance();

		try
		{
			String userId = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" );
			String chgTerm = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "chgTerm" );
			siteCode = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "site_code" );
			DateFormat dateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
			String dbDateFormat = genericUtility.getDBDateFormat();
			String applDateFormat = genericUtility.getApplDateFormat();

			ConnDriver connDriver = null;
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;

			if( objContext != null && objContext.trim().length() > 0 )
			{
				currentFormNo = Integer.parseInt( objContext );
			}
			System.out.println(" currentColumn ["+currentColumn+"]");
			valueXmlString = new StringBuffer( "<?xml version=\"1.0\"?>\r\n<Root>\r\n<Header>\r\n<editFlag>" );
			valueXmlString.append( editFlag ).append( "</editFlag>\r\n</Header>\r\n" );

			switch ( currentFormNo )
			{
			case 1:
			{
				valueXmlString.append( "<Detail1>\r\n" );
				if( currentColumn.trim().equalsIgnoreCase( "itm_default" ) )							
				{
					valueXmlString.append( "<site_code><![CDATA[" ).append( siteCode ).append( "]]></site_code>\r\n" );
					valueXmlString.append( "<cust_code__fr><![CDATA[" ).append( "00" ).append( "]]></cust_code__fr>\r\n" );
					valueXmlString.append( "<cust_code__to><![CDATA[" ).append( "ZZ" ).append( "]]></cust_code__to>\r\n" );
					valueXmlString.append( "<cust_code__dlv_fr><![CDATA[" ).append( "00" ).append( "]]></cust_code__dlv_fr>\r\n" );
					valueXmlString.append( "<cust_code__dlv_to><![CDATA[" ).append( "ZZ" ).append( "]]></cust_code__dlv_to>\r\n" );
					valueXmlString.append( "<item_ser__fr><![CDATA[" ).append( "00" ).append( "]]></item_ser__fr>\r\n" );
					valueXmlString.append( "<item_ser__to><![CDATA[" ).append( "ZZ" ).append( "]]></item_ser__to>\r\n" );
					valueXmlString.append( "<item_code__fr><![CDATA[" ).append( "00" ).append( "]]></item_code__fr>\r\n" );
					valueXmlString.append( "<item_code__to><![CDATA[" ).append( "ZZ" ).append( "]]></item_code__to>\r\n" );
					valueXmlString.append( "<lot_no__fr><![CDATA[" ).append( "00" ).append( "]]></lot_no__fr>\r\n" );
					valueXmlString.append( "<lot_no__to><![CDATA[" ).append( "ZZ" ).append( "]]></lot_no__to>\r\n" );
					valueXmlString.append( "<sale_order__fr><![CDATA[" ).append( "00" ).append( "]]></sale_order__fr>\r\n" );
					valueXmlString.append( "<sale_order__to><![CDATA[" ).append( "ZZ" ).append( "]]></sale_order__to>\r\n" );
					valueXmlString.append( "<carton_no__fr><![CDATA[" ).append( "00" ).append( "]]></carton_no__fr>\r\n" );
					valueXmlString.append( "<carton_no__to><![CDATA[" ).append( "ZZ" ).append( "]]></carton_no__to>\r\n" );					
					
				}
				else if( currentColumn.trim().equalsIgnoreCase( "itm_defaultedit" ) )							
				{					
					tranID = genericUtility.getColumnValue( "tran_id", currDom );
					System.out.println("tranID ["+tranID+"]");
					sql = "SELECT PTCN FROM DEALLOC_ART WHERE TRAN_ID = ? ";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, tranID);
					rs = pstmt.executeQuery();
					if( rs.next())
					{
						ptcn = rs.getString("PTCN");
					}
					rs.close(); rs = null;
					pstmt.close(); pstmt = null;
					
					valueXmlString.append( "<ptcn protect ='1'><![CDATA[" ).append( ptcn ).append( "]]></ptcn>\r\n" );
					
				}
				else if( currentColumn.trim().equalsIgnoreCase( "sale_order__fr" ) )							
				{					
					//valueXmlString.append( "<confirmed><![CDATA[" ).append( "N" ).append( "]]></confirmed>\r\n" );					
				}
				else if( currentColumn.trim().equalsIgnoreCase( "sale_order__to" ) )							
				{					
					//valueXmlString.append( "<confirmed><![CDATA[" ).append( "N" ).append( "]]></confirmed>\r\n" );					
				}
				else if("ptcn".equalsIgnoreCase(currentColumn.trim()))
				{
					ptcn = "";
					ptcn = genericUtility.getColumnValue( "ptcn", currDom );
					System.out.println(" ptcn ["+ptcn+"]");
					sql = " SELECT WAVE_ID FROM WAVE_TASK_DET WHERE PTCN = ? ";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, ptcn);
					rs = pstmt.executeQuery();
					if( rs.next())
					{
						valueXmlString.append( "<wave_id><![CDATA[" ).append( rs.getString("WAVE_ID") ).append( "]]></wave_id>\r\n" );
					}
					rs.close(); rs = null;
					pstmt.close(); pstmt = null;
				}
				valueXmlString.append( "</Detail1>\r\n" );
			}
			break;
			case 2:
			{
				if( currentColumn.trim().equalsIgnoreCase( "itm_default" ) )							
				{	
					/*ptcn = genericUtility.getColumnValue( "ptcn", hdrDom ); in 
					System.out.println(" ** ptcn ["+ptcn+"]");
					sql = " SELECT C.CARTON_NO, C.PICK_ORDER,C.LINE_NO__PICK, PH.PICK_TYPE, PD.ITEM_CODE, PD.QUANTITY, C.PTCN " +
							" FROM CARTON_MASTER C , PICK_ORD_HDR PH, PICK_ORD_DET PD " +
							" WHERE C.PTCN = ? " +
							" AND PD.PICK_ORDER = C.PICK_ORDER " +
							" AND PD.LINE_NO = C.LINE_NO__PICK " +
							" AND PD.PICK_ORDER = PH.PICK_ORDER " +
							" AND ( FN_CHECK_DEALLOC_ARTDET(C.PTCN, C.CARTON_NO ) = 0 ) " +
							" AND PH.PICK_TYPE = ? ";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, ptcn );
					pstmt.setString(2, "C");
					rs = pstmt.executeQuery();
					if( rs.next())
					{
						HashMap itmVolumeMap = getItemVoumeMap(rs.getString("ITEM_CODE"),"",conn);
						double packSizeActive = (Double)itmVolumeMap.get("PACK_SIZE");
						
						valueXmlString.append("<Detail2>\r\n");
						valueXmlString.append( "<carton_no><![CDATA[" ).append( rs.getString("CARTON_NO") ).append( "]]></carton_no>\r\n" );
						valueXmlString.append( "<item_code><![CDATA[" ).append( rs.getString("ITEM_CODE") ).append( "]]></item_code>\r\n" );
						valueXmlString.append( "<pick_order><![CDATA[" ).append(  rs.getString("PICK_ORDER") ).append( "]]></pick_order>\r\n" );
						valueXmlString.append( "<line_no__pick><![CDATA[" ).append(  rs.getString("LINE_NO__PICK") ).append( "]]></line_no__pick>\r\n" );
						//valueXmlString.append( "<quantity><![CDATA[" ).append(  rs.getString("QUANTITY") ).append( "]]></quantity>\r\n" );
						valueXmlString.append( "<quantity><![CDATA[" ).append( packSizeActive ).append( "]]></quantity>\r\n" );
						valueXmlString.append( "<pick_type><![CDATA[" ).append(  rs.getString("PICK_TYPE") ).append( "]]></pick_type>\r\n" );
						valueXmlString.append( "</Detail2>\r\n" );
					}
					rs.close(); rs = null;
					pstmt.close();pstmt = null;	*/			
					
				}
				else if( "carton_no".equalsIgnoreCase(currentColumn.trim()))
				{
					CartonNo = genericUtility.getColumnValue( "carton_no", currDom );
					System.out.println(" CartonNo ["+CartonNo+"] ");
					sql = "SELECT C.CARTON_NO, C.PICK_ORDER,C.LINE_NO__PICK, PH.PICK_TYPE, PD.ITEM_CODE, PD.QUANTITY, C.PTCN " +
							" FROM CARTON_MASTER C , PICK_ORD_HDR PH, PICK_ORD_DET PD " +
							" WHERE C.CARTON_NO = ? " +
							" AND PD.PICK_ORDER = C.PICK_ORDER " +
							" AND PD.LINE_NO = C.LINE_NO__PICK " +
							" AND PD.PICK_ORDER = PH.PICK_ORDER " +
							//" AND ( FN_CHECK_DEALLOC_ARTDET(C.PTCN, C.CARTON_NO ) = 0 ) "+
							" AND PH.PICK_TYPE IN (?,?) AND C.CARTON_TYPE = 'C' AND C.STATUS <> 'R'";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, CartonNo );
					pstmt.setString(2, "C");
					pstmt.setString(3, "M");
					rs = pstmt.executeQuery();
					if( rs.next())
					{
						HashMap itmVolumeMap = getItemVoumeMap(rs.getString("ITEM_CODE"),"",conn);
						double packSizeActive = (Double)itmVolumeMap.get("PACK_SIZE");
						
						valueXmlString.append("<Detail2>\r\n");		
						valueXmlString.append( "<item_code><![CDATA[" ).append( rs.getString("ITEM_CODE") ).append( "]]></item_code>\r\n" );
						valueXmlString.append( "<pick_order><![CDATA[" ).append(  rs.getString("PICK_ORDER") ).append( "]]></pick_order>\r\n" );
						valueXmlString.append( "<line_no__pick><![CDATA[" ).append(  rs.getString("LINE_NO__PICK") ).append( "]]></line_no__pick>\r\n" );
						//valueXmlString.append( "<quantity><![CDATA[" ).append(  rs.getString("QUANTITY") ).append( "]]></quantity>\r\n" );
						valueXmlString.append( "<quantity><![CDATA[" ).append( packSizeActive ).append( "]]></quantity>\r\n" );
						valueXmlString.append( "<pick_type><![CDATA[" ).append(  rs.getString("PICK_TYPE") ).append( "]]></pick_type>\r\n" );
						valueXmlString.append( "</Detail2>\r\n" );
					}
					rs.close(); rs = null;
					pstmt.close();pstmt = null;
				}
			}//case 2 end here
			break;
			
			}//switch statement ends here
		}//try block ends here
		catch(Exception e)
		{
			System.out.println( "Exception :DeallocArtIC :itemChanged(Document,String):" + e.getMessage() + ":" );
			valueXmlString = valueXmlString.append( genericUtility.createErrorString( e ) );
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if( conn != null && ! conn.isClosed() )
				{
					conn.close();
				}
			}
			catch(Exception e)
			{
				System.out.println( "Exception :DeallocArtIC:itemChanged :==>\n"+e.getMessage());
				throw new ITMException(e);
			}
		}
		valueXmlString.append( "</Root>\r\n" );	
		System.out.println( "\n****ValueXmlString :" + valueXmlString.toString() + ":********" );
		return valueXmlString.toString();
	}

	/**
	 * The function checks whether the input string is null. 
	 * If null, the function returns blank string.  
	 * @param input
	 */
	private String checkNull( String inputVal )
	{
		if ( inputVal == null )
		{
			inputVal = "";
		}
		return inputVal;
	}
	/**
	 * The function checks whether the input string is null. 
	 * If null, the function returns blank string otherwise trim the input string and return.  
	 * @param input
	 */
	private String checkNullAndTrim( String inputVal )
	{
		if ( inputVal == null )
		{
			inputVal = "";
		}
		else
		{
			inputVal = inputVal.trim();
		}
		return inputVal;
	}
	private ArrayList checkDuplicateCarton(Document dom) throws ITMException
	{
		ArrayList arryList = new ArrayList();
		
		NodeList parentNodeList = null, childNodeList  = null;
		Node parentNode = null, childNode = null;
	    int parentNodeListLength = 0;
	    String childNodeName = "";
		
		try {
			parentNodeList = dom.getElementsByTagName("Detail2");
			parentNodeListLength = parentNodeList.getLength();
			for (int row = 0; row < parentNodeList.getLength(); row++) 
			{
				parentNode = parentNodeList.item(row);
				childNodeList = parentNode.getChildNodes();
				
				String updateFlag = getAttribValue(parentNode,"attribute", "updateFlag"); //(parentNode, "attribute", "status"));
				System.out.println(" updateFlag ["+updateFlag+"]");
				childNodeList = parentNode.getChildNodes();
				
				//System.out.println("************* first For loop *************["+ parentNode.getNodeName() + "]");
				for (int col = 0; col < childNodeList.getLength(); col++) {
					childNode = childNodeList.item(col);
					
					if (childNode.getNodeType() == childNode.ELEMENT_NODE) {
						childNodeName = childNode.getNodeName();
						//System.out.println("childNodeNamechildNodeName ** ["+childNodeName+"]");
						if( !"D".equalsIgnoreCase(updateFlag))
						{
							if ("carton_no".equalsIgnoreCase(childNodeName)) {
								arryList.add(childNode.getFirstChild().getNodeValue().trim());							
								System.out.println("=====carton_no-->[" + arryList+ "]");
								
							}	
						}
					}
				}
			}
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		return arryList;
	}
	/*private String addSelectedRecToDom( Document allFormDataDom, String detailString ) throws Exception
	{
		ArrayList selectedList = new ArrayList();
		NodeList detailList = null;
		Node currDetail = null;
		NodeList currDetailList = null;
		String selectedVal = "", nodeName = "";
		String domIDVal = "";
		String updatedDetailDomStr = "";
		String attributeVal = "";
		String cartonNo = "";
		String columnValue = "";

		HashMap toUpdateMap = new HashMap();

		Node elementName = null;

		int currDetailListLength = 0;
		int	detailListLength = 0;

		int selectedValCnt = 0;

		GenericUtility genericUtility = GenericUtility.getInstance();

		try
		{
			detailList = allFormDataDom.getElementsByTagName("Detail3");
			detailListLength = detailList.getLength();
			for ( int ctr = 0; ctr < detailListLength; ctr++ )
			{
				currDetail = detailList.item(ctr);
				currDetailList = currDetail.getChildNodes();
				currDetailListLength = currDetailList.getLength();

				attributeVal = "";
				columnValue = "";

				ArrayList toUpdNodeList = new ArrayList();
				HashMap dataMap = new HashMap();

				for ( int i=0; i< currDetailListLength; i++ )
				{
					Node childNode = currDetailList.item(i);
					nodeName = childNode.getNodeName();
					if (nodeName.equalsIgnoreCase("Attribute"))
					{
						attributeVal = checkNull(currDetailList.item(i).getAttributes().getNamedItem("selected").getNodeValue());
						System.out.println("attributeVal =["+attributeVal+"]");
					}//if (nodeName = Attribute
					else if (nodeName.equalsIgnoreCase("carton_no"))
					{
						if ( childNode != null && childNode.getFirstChild() != null )
						{
							cartonNo = childNode.getFirstChild().getNodeValue();
							//toUpdNodeList.add( 1, childNode );
							dataMap.put("carton_no", childNode);
						}
					}
				}//End of inner for loop
				if ( "Y".equalsIgnoreCase(attributeVal.trim()) )
				{
					if ( currDetail.getAttributes().getNamedItem( "domID" ) != null )
					{
						domIDVal = checkNull(currDetail.getAttributes().getNamedItem( "domID" ).getNodeValue());
						System.out.println("domIDVal =["+domIDVal+"]");
					}
					toUpdateMap.put( domIDVal, dataMap );
				}
			}//End of for loop

			System.out.println("toUpdateMap:>>>>>>>>>>>: "+toUpdateMap);

			detailList = null;

			detailString = detailString + "</Root>\r\n" ;	
			System.out.println("detailString:>>>>>>>>>>> "+detailString);
			Document detailDom = genericUtility.parseString(detailString); 

			Element elementAttr = null;

			detailList = detailDom.getElementsByTagName("Detail3");
			detailListLength = detailList.getLength();
			for ( int ctr = 0; ctr < detailListLength; ctr++ )
			{
				currDetail = detailList.item(ctr);

				if ( currDetail.getAttributes().getNamedItem( "selected" ) != null )
				{
					selectedVal = checkNull(currDetail.getAttributes().getNamedItem( "selected" ).getNodeValue());
					System.out.println("selectedVal =["+selectedVal+"]");
					if ( "N".equalsIgnoreCase(selectedVal.trim()) )
					{
						if ( currDetail.getAttributes().getNamedItem( "domID" ) != null )
						{
							//ArrayList aList = null;

							HashMap dataMap = new HashMap();

							domIDVal = checkNull(currDetail.getAttributes().getNamedItem( "domID" ).getNodeValue());
							System.out.println("domIDVal =["+domIDVal+"]");
							System.out.println("toUpdateMap.containsKey(domIDVal) =["+toUpdateMap.containsKey(domIDVal)+"]");
							if ( toUpdateMap.containsKey(domIDVal) )
							{
								elementAttr = (Element)currDetail;
								elementAttr.setAttribute( "selected" , "Y" );

								--not required
								Node cartonNoNode = null;

								dataMap = (HashMap)toUpdateMap.get(domIDVal);

								if ( dataMap.get("carton_no") != null )
								{
									cartonNoNode = (Node)dataMap.get("carton_no");
								}

								Node updatedNode = null;

								currDetailList = currDetail.getChildNodes();
								currDetailListLength = currDetailList.getLength();

								for ( int i = 0; i < currDetailListLength; i++ )
								{
									elementName = currDetailList.item(i);
									nodeName = elementName.getNodeName();
									if( elementName.getNodeType() != Node.ELEMENT_NODE || nodeName.equalsIgnoreCase("#text") )
									{
										continue;
									}
									System.out.println("nodeName =["+nodeName+"]");
									if ( nodeName.equalsIgnoreCase("lot_sl") )
									{
										//System.out.println("LocCodeToNode =["+genericUtility.serializeDom( LocCodeToNode )+"]");
										updatedNode = detailDom.importNode(cartonNoNode, true);
										//System.out.println("updatedNode =["+genericUtility.serializeDom( updatedNode )+"]");
										(detailDom.getElementsByTagName("Detail3").item(ctr)).replaceChild(updatedNode, elementName );
									}
								}//inner for loop
								 
								//End commented gulzar
							}//if ( toUpdateMap.containsKey(domIDVal) )
						}//if ( currDetail.getAttributes().getNamedItem( "domID" )
					}//if ( "N".equalsIgnoreCase(selectedVal.trim()) )
				}//if ( currDetail.getAttributes().getNamedItem( "selected" )
			}//outer for loop
			updatedDetailDomStr = genericUtility.serializeDom( detailDom );
			System.out.println("updatedDetailDomStr:>>>>>>>>>>> "+updatedDetailDomStr);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}

		return updatedDetailDomStr;
	}
	*/
	private HashMap getItemVoumeMap(String itemCode,String lotNo,Connection con)throws Exception
	{
		double packSize = 0,itemSize = 0,lotSize = 0;
		PreparedStatement pstmt = null;
		String sql="";
		ResultSet rs = null;
		double itmLen = 0,itmWidth = 0,itmHeight = 0,itemWeight = 0,lotLen = 0 ,lotHeight = 0,lotWidth = 0,lotWeight = 0;
		HashMap dataVolumeMap = new HashMap();
		
		try {
			
			sql = "SELECT I.LENGTH ITEM_LEN,I.WIDTH ITEM_WID,I.HEIGHT ITEM_HEIGHT,I.GROSS_WEIGHT ITEM_WEIGHT,"
				  +" L.LENGTH LITEM_LEN,L.WIDTH LITEM_WID,L.HEIGHT LITEM_HEIGHT,L.SHIPPER_SIZE SHIPSIZE,L.GROSS_WEIGHT LOT_WEIGHT FROM"
				  +" ITEM I,ITEM_LOT_PACKSIZE L"
				  +" WHERE I.ITEM_CODE = L.ITEM_CODE"
				  +" AND L.LOT_NO__FROM <= ? AND L.LOT_NO__TO >= ?"
				  +" AND  I.ITEM_CODE = ?";
				  
			
			pstmt = con.prepareStatement(sql);
			if(lotNo != null && lotNo.length() > 0)
			{
				pstmt.setString(1, lotNo);
				pstmt.setString(2, lotNo);
			}
			else
			{
				pstmt.setString(1, "00");
				pstmt.setString(2, "ZZ");
			}
			pstmt.setString(3, itemCode);
			rs = pstmt.executeQuery();
			
			if(rs.next())
			{
				itmLen = rs.getDouble("ITEM_LEN");
				itmWidth = rs.getDouble("ITEM_WID");
				itmHeight = rs.getDouble("ITEM_HEIGHT");
				itemWeight = rs.getDouble("ITEM_WEIGHT");
				lotLen = rs.getDouble("LITEM_LEN");
				lotWidth = rs.getDouble("LITEM_WID");
				lotHeight = rs.getDouble("LITEM_HEIGHT");				
				packSize = rs.getDouble("SHIPSIZE");				
				lotWeight = rs.getDouble("LOT_WEIGHT");				
			}
			
			//packSize = (lotHeight * lotWidth * lotLen)/(itmLen * itmWidth * itmHeight);
			/*itemSize = Math.floor(itmLen * itmWidth * itmHeight);
			lotSize = Math.floor((lotHeight * lotWidth * lotLen));*/
			itemSize = itmLen * itmWidth * itmHeight;
			lotSize = lotHeight * lotWidth * lotLen;
			
			dataVolumeMap.put("PACK_SIZE", packSize);
			dataVolumeMap.put("ITEM_SIZE", itemSize);
			dataVolumeMap.put("LOT_SIZE", lotSize);
			dataVolumeMap.put("ITEM_WEIGHT", itemWeight);
			dataVolumeMap.put("PACK_WEIGHT", lotWeight);
			
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
		
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
		
			}
			
			
			
		} catch (Exception e) {			

			throw e;
		}
		finally
		{
			if(pstmt != null)
			{
				pstmt.close();
				pstmt = null;
		
			}
			if(rs != null)
			{
				rs.close();
				rs = null;
		
			}
		}
		
		return dataVolumeMap;
	}
	private String getAttribValue(Node detailNode, String nodeName, String attribStr)
	{
		String attribValue = "";
		try
		{
			String domStr = GenericUtility.getInstance().serializeDom(detailNode);
			Document dom = GenericUtility.getInstance().parseString(domStr);
			if( dom != null /*&& dom.getAttributes() != null*/)
			{
				Node attributeNode = dom.getElementsByTagName( nodeName ).item(0);
				attribValue = getAttribValue(attributeNode, attribStr);
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception : getAttribValue :" + e.getMessage());
		}
		return attribValue;
	}
	private String getAttribValue(Node detailNode, String attribStr)
	{
		String attribValue = "";
		try
		{
			if( detailNode != null && detailNode.getAttributes() != null)
			{
				Node attribNode = detailNode.getAttributes().getNamedItem( attribStr );
				if( attribNode != null )
				{
					attribValue = checkNull( attribNode.getNodeValue() );
				}
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception : getAttribValue :" + e.getMessage());
		}
		return attribValue;
	}
}
