

package ibase.webitm.ejb.wms;



import ibase.system.config.ConnDriver;

import ibase.webitm.ejb.ValidatorEJB;

import ibase.webitm.utility.GenericUtility;

import ibase.webitm.utility.ITMException;

import java.util.*;

import java.rmi.RemoteException;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.Date;

import javax.ejb.CreateException;

import javax.ejb.SessionBean;

import java.text.SimpleDateFormat;

import java.text.DateFormat;

import java.text.DecimalFormat;

import java.sql.Timestamp;



import org.apache.poi.hssf.record.formula.functions.Isnumber;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.NamedNodeMap;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import javax.ejb.Stateless; // added for ejb3

import ibase.webitm.ejb.ITMDBAccessEJB;

import ibase.webitm.ejb.dis.DistCommon;



import org.w3c.dom.CDATASection;



import java.text.*; 

import java.sql.*;



@Stateless // added for ejb3



public class PhyItemScanIC extends ValidatorEJB implements PhyItemScanICLocal, PhyItemScanICRemote

{

	GenericUtility genericUtility = GenericUtility.getInstance();	

	/**

	* 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 xmlString, String xmlString1, String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException

	{

		String errString = null;

		Document dom = null;

		Document dom1 = null;

		Document dom2 = null;

		try

		{

		    

			System.out.println("Val xmlString :: " + xmlString );

			System.out.println("Val xmlString1 :: " + xmlString1 );

			System.out.println("Val xmlString2 :: " + xmlString2 );

			//long startTime = System.currentTimeMillis();

			dom = parseString(xmlString);

			dom1 = parseString(xmlString1);

			dom2 = parseString(xmlString2);

					

			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);

		}

		catch(Exception e)

		{

			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 dom, Document dom1, Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException

	{

	  	NodeList parentNodeList = null;

		NodeList childNodeList = null;

		Node parentNode = null;

		Node childNode = null;

		int ctr=0;

		int count = 0;

		String childNodeName = null;

		String errString = "";

		Connection conn = null;

		PreparedStatement pstmt = null ;

		ResultSet rs = null , rs1 = null;

		String sql = "" ;

		String userId = "";

		int currentFormNo=0;

		int childNodeListLength;

        ConnDriver connDriver = new ConnDriver();

		

		double Quantity = 0d;

		double phyQty = 0d;

		//Changed by sumit sarkar on 26/06/12 start.

		String suggestedInvStat = "", invStat = "";

		StringTokenizer st2 = null;

		List inv = new ArrayList();

		String columnValue ="", sSQL = "", sqlForCase = "", itemCode = "", lotNo = "",phyHanBasis ="", lotSl ="";

		String unit = "", mrfPartNo ="", toUnit ="",locCode = "";
		String prdCode = "" , siteCode = "",errCode = "";
		java.util.Date utilDate = new java.util.Date();
		java.util.Date tranDate = null;
		java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
		PreparedStatement pstmt1= null;
		ResultSet rs2 = null;
		double shipperSize = 0, quantity = 0, quantityInput = 0,volumn = 0, convFact = 1, meffQty = 0;
		DistCommon discommon = new DistCommon();
		boolean isError = false;
		//Changed by sumit sarkar on 26/06/12 end.

		Timestamp currDateNew = null;
		java.util.Date currDate = null;
		String currAppdate= "";
		String winName="";
		String subCond="";
		String scanVal="";
		try

		{

			conn = connDriver.getConnectDB("DriverITM");

			connDriver = null;

			currDateNew = new java.sql.Timestamp(System.currentTimeMillis()) ;
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDateNew).toString();	

			currAppdate = genericUtility.getValidDateString(currAppdate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());

			currDateNew = Timestamp.valueOf(currAppdate + " 00:00:00.00");

			

			userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");

			if(objContext != null && objContext.trim().length()>0)

			{

				currentFormNo = Integer.parseInt(objContext);

			}

			switch(currentFormNo)
			{

				case 1 :
				{	
					parentNodeList = dom.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
					winName=getObjName(parentNode);
					childNodeList = parentNode.getChildNodes();
					childNodeListLength = childNodeList.getLength();
					for(ctr = 0; ctr < childNodeListLength; ctr++)
					{
					    childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();

						if ( childNode != null && childNode.getFirstChild() != null )
						{
							columnValue = childNode.getFirstChild().getNodeValue();
						}
						System.out.println(" columnName [" + childNodeName + "] columnValue [" + columnValue + "]");

						if( childNodeName.equalsIgnoreCase( "site_code" ))
						{ 
							if(childNode.getFirstChild() == null)
							{
								errString = getErrorString("site_code","NULLSITECO",userId);
								break;								

							}

							else

							{	

								 sql = "SELECT COUNT(*) AS COUNT FROM SITE WHERE SITE_CODE = ?";
								 pstmt = conn.prepareStatement(sql);
								 pstmt.setString(1,getColumnValue("site_code",dom));
								 rs = pstmt.executeQuery();
								 if( rs.next() )
								 {
									count = rs.getInt("COUNT");
								 }
								 if(pstmt != null)
								 {
									 pstmt.close();
									 pstmt = null;									 
								 }
								 if(rs != null)
								 {
									 rs.close();
									 rs = null;
								 }
								 
								 if( count == 0 )
								 {
									 errString = getErrorString("site_code","INVSITECOD",userId);
									 break;
								 }
								 else //added by kunal on 14-feb-14
								 {
									 siteCode = genericUtility.getColumnValue("site_code", dom);
									 System.out.println("364 site code ="+siteCode);
									 if (genericUtility.getColumnValue("tran_date", dom) != null)
									 {
										 tranDate = sdf.parse(genericUtility.getColumnValue("tran_date", dom));
										 sql = "select code from period where ?  between fr_date and to_date";
										 pstmt = conn.prepareStatement(sql);
										 pstmt.setDate(1, new java.sql.Date(tranDate.getTime()));
										 rs = pstmt.executeQuery();
										 if (rs.next())
										 {
											 prdCode = rs.getString(1);

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

										 sql = "select count(*) from period_stat where site_code = ? and prd_code = ? ";
										 pstmt = conn.prepareStatement(sql);
										 pstmt.setString(1, siteCode);
										 pstmt.setString(2, prdCode);
										 rs = pstmt.executeQuery();
										 if (rs.next())
										 {
											 count = rs.getInt(1);

										 }
										 rs.close();
										 rs = null;
										 pstmt.close();
										 pstmt = null;
										 if (count == 0)
										 {
											 errString = getErrorString("site_code","VTSITEPD",userId);
											 break;
										 }
										 // nvo_functions_adv.nf_check_period('SAL',mdate1,msite_code)
										 errCode = nfCheckPeriod("IC", tranDate, siteCode);
										 System.out.println("425 Error Code = " + errCode);
										 if (errCode != null && errCode.trim().length() > 0)
										 {
											 errString = getErrorString("site_code",errCode,userId);
											 break;
										 }
									 } 								 
								 }
								 

							 }

							 						

						}

						else if( childNodeName.equalsIgnoreCase( "tran_date" ))

						{

							if(childNode.getFirstChild() == null)

							{

								errString = getErrorString("tran_date","NULLTRANDT",userId);

								break;								

							}

						}

						//Changed by sumit sarkar on 26/06/12 validating inv stat start.

						else if( childNodeName.equalsIgnoreCase( "inv_stat" ))

						{

							System.out.println("inv_stat ");

							if(childNode.getFirstChild() == null)

							{

								errString = getErrorString("inv_stat","NULLINVSTA",userId);

								break;								

							}

							else

							{

								suggestedInvStat = checkNull(genericUtility.getColumnValue("suggested_inv_stat", dom2));

								invStat = checkNull(genericUtility.getColumnValue("inv_stat", dom2));

								System.out.println("suggestedInvStat ==>["+suggestedInvStat+"] invStat==>["+invStat+"]");										

								st2 = new StringTokenizer(suggestedInvStat, ",");								 

								while (st2.hasMoreElements()) 

								{

									inv.add(st2.nextElement().toString().trim());

								}

								System.out.println("invStat "+inv);

								if(!inv.contains(invStat))

								{

									errString = getErrorString("inv_stat","INVINVSTAT",userId);

									break;

								}

								 

							}

						 						

					    }

						//Changed by sumit sarkar on 26/06/12 validating inv stat end.

						

												

					}

				}

			    break;

				case 2:

				{

					parentNodeList = dom.getElementsByTagName("Detail2");

					

					//parentNode = dom.getElementsByTagName("Detail2")[0];

					parentNode = parentNodeList.item(0);

					winName=getObjName(parentNode);

					if("w_phy_item_scan".equalsIgnoreCase(winName))

					{

					//subCond=" and D.QUANTITY>0 ";//Changed by manoj dtd 21/09/2013 to check previous day empty records
					subCond=" and D.TRAN_TYPE<>'E' ";
					}

					else

					{
						//subCond=" and D.QUANTITY>0 ";
						subCond=" and D.TRAN_TYPE='E' ";	

					}

					childNodeList = parentNode.getChildNodes();

					childNodeListLength = childNodeList.getLength();

					String attribute = attributeValue(dom2);

//					System.out.println(" ssssssssssssss "+attribute);

					for(ctr = 0; ctr < childNodeListLength; ctr++)

					{

						System.out.println("Enter into second form validation");

						childNode = childNodeList.item(ctr);

						childNodeName = childNode.getNodeName();

						

						

						//xmlDoc=loadXMLDoc("books.xml");



						//String txt=dom.getElementsByTagName("Detail2")[0].getAttribute("lang"); 

						//Changed by sumit on 10/07/12 commented due to no use. start.

						/*if( childNodeName.equalsIgnoreCase( "qty_physical" ))

						{

							if(childNode.getFirstChild() == null)

							{

								errString = getErrorString("qty_physical","NULLPHYQTY",userId);

								break;								

							}

							else

							{

								Quantity = Double.parseDouble(genericUtility.getColumnValue("quantity", dom2));

								phyQty = Double.parseDouble(g?enericUtility.getColumnValue("qty_physical", dom2));

								System.out.println("quantity==>"+Quantity+"qty_physical==>"+phyQty);

								

								if(phyQty != Quantity)

								{

									System.out.println("inside if");

									errString = getErrorString("qty_physical","NOTMATCH",userId);

									break;		

								}

	

								 

							}

						 						

					    }*/

						//Changed by sumit on 10/07/12 commented due to no use. end.

						

						//Changed by sumit sarkar on 16/07/12 validating for null detail start.

//						if( "N".equalsIgnoreCase(attribute ))

//						{

//							errString = getErrorString("","NULLDETAIL",userId);

//							break;

//						}

						//Changed by sumit sarkar on 16/07/12 validating for null detail end.

						//Changed by sumit sarkar on 27/06/12 validating item_code and lot_no start.

						//else 

						scanVal=checkNull(genericUtility.getColumnValue("isempty",dom));

						if(scanVal==null || scanVal.trim().length()==0)

						{

							scanVal="N";

						}

						System.out.println("isEmpty----"+scanVal);

						if("N".equalsIgnoreCase(scanVal))

						{

						if( childNodeName.equalsIgnoreCase( "item_code" ))								

						{
							itemCode = checkNull(genericUtility.getColumnValue("item_code",dom)).trim();
							System.out.println("itemCode = "+itemCode);
							if(itemCode.trim().length()  == 0)
							{
								errString = getErrorString("item_code","NULLITCODE",userId);

								break;								

							}

							else

							{

								//columnValue =  childNode.getFirstChild().getNodeValue();								
							      if("w_phy_item_scan".equalsIgnoreCase(winName))

							      {
								sSQL = "SELECT D.ITEM_CODE FROM PHYSCAN H,PHYSCANDET D,STOCK S,ITEM M,LOCATION L"

									   +" WHERE "
									   +" H.TRAN_ID=D.TRAN_ID AND  "
									   +" H.TRAN_DATE = ? AND D.ITEM_CODE = S.ITEM_CODE AND " 

									   + " D.ITEM_CODE = M.ITEM_CODE  "	+subCond								   

								       +" AND S.LOC_CODE = L.LOC_CODE  AND L.INV_STAT = ? "

								       +" AND D.ITEM_CODE = ?  ";

								

								System.out.println("** sSQL **["+sSQL+"]");

								pstmt = conn.prepareStatement(sSQL);

								pstmt.setTimestamp(1, currDateNew);								

								pstmt.setString(2, genericUtility.getColumnValue("inv_stat",dom1));	

								pstmt.setString(3, genericUtility.getColumnValue("item_code",dom).trim());

								rs = pstmt.executeQuery();							

								if(!rs.next())

								{  

									errString = getErrorString("item_code","INVITCODE",userId);

									break;								   

								}

								if( rs != null )

								{

									rs.close();

									rs = null;

								}

								if( pstmt != null)

								{

									pstmt.close();

									pstmt = null;

								}
							      }
							      else
							      {
								sSQL="select item_code from item where item_code=?";
								pstmt = conn.prepareStatement(sSQL);

								pstmt.setString(1, genericUtility.getColumnValue("item_code",dom).trim());

								rs = pstmt.executeQuery();							

								if(!rs.next())
								{
								    errString = getErrorString("item_code","INVITCODE",userId);

								    break;							
								}
								if( rs != null )

								{

									rs.close();

									rs = null;

								}

								if( pstmt != null)

								{

									pstmt.close();

									pstmt = null;

								}

							      }

								     

							}

						}
						else if( childNodeName.equalsIgnoreCase( "lot_sl" )) //added by Kunal on 17/09/12
						{
							lotSl = checkNull(genericUtility.getColumnValue("lot_sl",dom)).trim();
							System.out.println("lot sl = "+lotSl);
							if(lotSl.trim().length()  == 0)
							{
								errString = getErrorString("lot_sl","NULLLPNNO ",userId);
								break;
							}
							else
							{
								locCode = genericUtility.getColumnValue("loc_code", dom);
								itemCode = genericUtility.getColumnValue("item_code", dom);
								lotNo = genericUtility.getColumnValue("lot_no", dom);
								
								System.out.println("loc code="+locCode+"   item code = "+itemCode+"  lotno="+lotNo);
							      if("w_phy_item_scan".equalsIgnoreCase(winName))
							      {
									sSQL = "SELECT COUNT(*) FROM PHYSCANDET WHERE ITEM_CODE = ? AND LOC_CODE = ? AND LOT_NO = ? AND LOT_SL = ?";
									pstmt = conn.prepareStatement(sSQL);
									pstmt.setString(1, itemCode);
									pstmt.setString(2, locCode);
									pstmt.setString(3, lotNo);
									pstmt.setString(4, lotSl);
									rs = pstmt.executeQuery();							
									if(rs.next())
									{  
										count = rs.getInt(1);
									}
									pstmt.close();
									pstmt = null;
									rs.close();
									rs = null;
									
									if(count == 0)
									{
										errString = getErrorString("lot_sl","VTLPNNTVAL",userId);
										break;								
									}
							      }
							      else
							      {
							    	  if(!lotSl.startsWith("NJ") && !lotSl.startsWith("CN") && !lotSl.startsWith("DM") && !lotSl.startsWith("EX") )
										{
							    		  errString = getErrorString("lot_sl","VTINVLPN",userId);
										  break;	
							    		  
										}
										
										if(lotSl.length() != 10)
										{
											errString = getErrorString("lot_sl","VTINVLEN",userId);
											break;
											  
											
										}
							      }
							}
						}//end kunal

						else if( childNodeName.equalsIgnoreCase( "lot_no" ))

						{
							lotNo = checkNull(genericUtility.getColumnValue("lot_no",dom)).trim();
							System.out.println("lotNo = "+lotNo);
							if(lotNo.trim().length()  == 0)
							{
								errString = getErrorString("lot_no","NULLLOTNO ",userId);
								break;
							}
							else

							{
							      if("w_phy_item_scan".equalsIgnoreCase(winName))

							      {
								sSQL = "SELECT D.LOT_NO FROM PHYSCAN H,PHYSCANDET D,ITEM M,LOCATION L"

									   +" WHERE "
									    +" H.TRAN_ID=D.TRAN_ID AND "
									    +" H.TRAN_DATE = ? AND " 

									   + " D.ITEM_CODE = M.ITEM_CODE   "+subCond									   

								       +" AND D.LOC_CODE = L.LOC_CODE  AND L.INV_STAT = ? "

								       +" AND D.LOT_NO = ? AND H.TRAN_TYPE = 'A'";

								

								System.out.println("** sSQL **["+sSQL+"]");

								pstmt = conn.prepareStatement(sSQL);

								pstmt.setDate(1, sqlDate);								

								pstmt.setString(2, genericUtility.getColumnValue("inv_stat",dom1));	

								pstmt.setString(3, genericUtility.getColumnValue("lot_no",dom).trim());

								rs = pstmt.executeQuery();							

								if(!rs.next())

								{  

									errString = getErrorString("lot_no","INVLOTNUMB",userId);

									break;								   

								}

								if( rs != null )

								{

									rs.close();

									rs = null;

								}

								if( pstmt != null)

								{

									pstmt.close();

									pstmt = null;

								}
							      }

							}

						}

						//Changed by sumit sarkar on 27/06/12 validating item_code and lot_no end.

						

						//Changed by sumit sarkar on 10/07/12 validating physical quantity over phy_input  type start.

						else if( childNodeName.equalsIgnoreCase( "phy_input" ))

						{
							//CommentedBy Manoj dtd 04092012 not required

//							if(childNode.getFirstChild() == null)
//
//							{
//
//								errString = getErrorString("phy_input","NULLCASECT",userId);
//
//								break;								
//
//							}
//
//							else
//
//							{
								String phyInput=checkNull(genericUtility.getColumnValue("phy_input",dom));
								if(phyInput==null || phyInput.trim().length()==0)
								{
									phyInput="0";
								}

								if( !isInteger(phyInput))

								{

									errString = getErrorString("case_count","NOTANUMBER",userId);

									break;

								}

								else

								{

									quantity = Double.parseDouble(genericUtility.getColumnValue("quantity", dom));

									quantityInput = Double.parseDouble(genericUtility.getColumnValue("phy_input", dom) == null ?"0":genericUtility.getColumnValue("phy_input", dom)); //chnage done by Kunal On 10/09/12

									itemCode = checkNull(genericUtility.getColumnValue("item_code",dom)).trim();

									lotNo = checkNull(genericUtility.getColumnValue("lot_no",dom)).trim();

									lotSl = checkNull(genericUtility.getColumnValue("lot_sl",dom)).trim();

									System.out.println("quantity ["+quantity+"] quantityInput ["+quantityInput+"] itemCode ["+itemCode+"] lotNo ["+lotNo+"] lotSl ["+lotSl+"]");

									if("w_empty_loc_scan".equalsIgnoreCase(winName))
									{
										quantity = Double.parseDouble(genericUtility.getColumnValue("quantity", dom));
										System.out.println("quantityInput ::["+quantityInput+"]");
										if(quantityInput == 0)            // ADDED BU RITESH ON 26/MAR/14 START
										{
											errString = getErrorString("phy_input","VTPHYQTYS",userId);

											break;
										}	 							// ADDED BU RITESH ON 26/MAR/14 END
									}
								      if("w_phy_item_scan".equalsIgnoreCase(winName))

								      {
									sSQL = "SELECT L.PHY_HAN_BASIS, L.PHY_HAN_UOM , D.UNIT FROM PHYSCAN H,PHYSCANDET D,ITEM M,LOCATION L "

										   +" WHERE H.TRAN_ID=D.TRAN_ID AND "
										   +" H.TRAN_DATE = ? AND  " 

										   +" D.ITEM_CODE = M.ITEM_CODE   "	+subCond								   

									       +" AND D.LOC_CODE = L.LOC_CODE  AND L.INV_STAT = ? "

									       +" AND D.LOT_NO = ? AND D.ITEM_CODE = ? AND D.LOT_SL = ?  AND H.TRAN_TYPE = 'A'";

									

									System.out.println("** sSQL **["+sSQL+"]");

									pstmt = conn.prepareStatement(sSQL);

									pstmt.setDate(1, sqlDate);								

									pstmt.setString(2, genericUtility.getColumnValue("inv_stat",dom1));	

									pstmt.setString(3, lotNo);

									pstmt.setString(4, itemCode);

									pstmt.setString(5, lotSl);

									rs = pstmt.executeQuery();

									if(rs.next())

									{

										

										phyHanBasis = rs.getString("PHY_HAN_BASIS");

										unit = checkNull( rs.getString("PHY_HAN_UOM")); //change done by Kunal on 07/09/12

										toUnit = checkNull( rs.getString("UNIT")); //change done by Kunal on 07/09/12

										System.out.println(" Physical handel basis is ["+phyHanBasis+"]");

										phyHanBasis = checkNull(phyHanBasis);

										

										sqlForCase =" SELECT ILP.SHIPPER_SIZE, I.UNIT, I.MFR_PART_NO, I.VOLUME FROM ITEM I,  ITEM_LOT_PACKSIZE ILP " +

													" WHERE ILP.ITEM_CODE = ? " +

													" AND I.ITEM_CODE = ILP.ITEM_CODE "+

													" AND ? BETWEEN LOT_NO__FROM AND LOT_NO__TO ";

										

										pstmt1 = conn.prepareStatement(sqlForCase);

										pstmt1.setString(1, itemCode);

										pstmt1.setString(2, lotNo);

										rs2 = pstmt1.executeQuery();

										if( rs2.next())

										{

											shipperSize = rs2.getInt("SHIPPER_SIZE");

											//unit = rs2.getString("UNIT");

											mrfPartNo = rs2.getString("MFR_PART_NO");

											volumn = rs2.getDouble("VOLUME");

										}

										rs2.close();rs2 = null;

										pstmt1.close();pstmt1 = null;

										if( "".equalsIgnoreCase(phyHanBasis))

										{

											errString = getErrorString("phy_input","SCANTYPE",userId);

											break;

										}

										if("L".equalsIgnoreCase(phyHanBasis))

										{

											if( (shipperSize * quantityInput) != quantity)

											{

												//System.out.println(" as per 'L' ");

												errString = getErrorString("phy_input","NOTMATCH",userId);

												break;

											}

										}

										else if("I".equalsIgnoreCase(phyHanBasis))

										{

											if( quantityInput != quantity)

											{

												//System.out.println(" as per 'I' ");

												errString = getErrorString("phy_input","NOTMATCH",userId);

												break;

											}

										}

										else if ("U".equalsIgnoreCase(phyHanBasis))

										{

											System.out.println(" as per 'U' ");


											if(!unit.equalsIgnoreCase(toUnit))

											{

												if(volumn != 0)

												{

													convFact = volumn;

												}

												ArrayList convQtyList = discommon.getConvQuantityFact(unit, toUnit, itemCode, quantityInput, convFact,conn);

												System.out.println("convQtyList = "+convQtyList);

												meffQty = Double.parseDouble(convQtyList.get(1).toString());

												System.out.println("meffQty ["+meffQty+"]");

												

												if(meffQty == -999999999)

												{

													meffQty = 0;	

													errString = getErrorString("phy_input","CONVQTYNFD",userId);

													break;

												}

												if (volumn == 0)

												{

													volumn= Double.parseDouble(convQtyList.get(0).toString());

												}

												

											}

											else

											{

												meffQty = quantityInput ; //change done by Kunal on 12/09/12 

												if (volumn == 0) 

												{

													volumn=1;

												}

												

											}

											System.out.println("meffQty ["+meffQty+"] and quantity ["+quantity+"]");

											if( meffQty != quantity )

											{

												//System.out.println(" in side (meffQty != quantity) ");

												errString = getErrorString("phy_input","NOTMATCH",userId);

												break;

											}

											

											

										}

										else if ("P".equalsIgnoreCase(phyHanBasis))

										{											

											quantityInput = quanitityPerPallet(itemCode,lotNo, quantityInput ,conn );

											if( quantityInput != quantity)

											{

												//System.out.println(" as per 'P' ");

												errString = getErrorString("phy_input","NOTMATCH",userId);

												break;

											}

										}

									}

									if( rs != null )

									{

										rs.close();

										rs = null;

									}

									if( pstmt != null)

									{

										pstmt.close();

										pstmt = null;

									}
								      }

								}

							//}

						}

					}

						

						//Changed by sumit sarkar on 10/07/12 validating physical quantity over phy_input  type end.

				    }//End of for loop		

				}

					

			} //END switch

			

			

		}//END TRY

		catch(Exception e)

		{

			isError = true;

			e.printStackTrace();			

			errString=e.getMessage();			

			throw new ITMException( e );

		}

		finally

		{

			try

			{

				

				if(conn!=null)

				{

					if(rs != null )rs.close();

					if(rs1 != null )rs.close();

					rs = null;

					rs1 = null;

					if(pstmt != null )pstmt.close();

					pstmt =null;

					conn.close();

					conn = null;

				}

				conn = null;

			}catch(Exception d)

				{

				  d.printStackTrace();

				  throw new ITMException( d );

				}

		}

		

		return errString;

	}

	

	

	/**

	* 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 xmlString, String xmlString1,String xmlString2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException

	{

		Document dom = null;

		Document dom1 = null;

		Document dom2 = null;

		String valueXmlString = "";

		try

		{   

			dom = parseString(xmlString);

			dom1 = parseString(xmlString1);

			if (xmlString != null && xmlString.trim().length()!=0)

			{

				dom = genericUtility.parseString(xmlString); 

			}

			if (xmlString1 != null && xmlString1.trim().length()!=0)

			{

				dom1 = genericUtility.parseString(xmlString1); 

			}

			if (xmlString2 != null && xmlString2.trim().length()!=0)

			{

				dom2 = genericUtility.parseString(xmlString2); 

			}

			System.out.println("xmlString----"+xmlString);

			System.out.println("xmlString1----"+xmlString1);

			System.out.println("xmlString2----"+xmlString2);

			valueXmlString = itemChanged( dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams );

		}

		catch(Exception e)

		{

			System.out.println("Exception : [TrainingEJB][itemChanged(String,String)] :==>\n"+e.getMessage());

		}

        return valueXmlString;

	}

	/**

	 * 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 dom, Document dom1, Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException

	{

		StringBuffer valueXmlString = new StringBuffer();

		Connection conn = null;

		PreparedStatement pstmt = null, pstmt1 = null;

		PreparedStatement pstmtDet = null;

		ResultSet rs = null ;

		ResultSet rsDet = null ;

		String  sSQL = "";

		String sql = "";

		String sqlDet = "";

		int currentFormNo = 0 ;

		int lineNo = 0 ;

		

		double physicalQty = 0d;

		

		GenericUtility genericUtility = GenericUtility.getInstance();

		String siteCode = "";

		String loginCode = "";

		String chgTerm = "";

		String siteDescr = "";

		String itemDescr = "";

		String locDescr = "";

		String tranId = "";

		String locCodeFrom = "", locCodeTo = "", itemCode = "",locCode = "", lotNo = "", lotSl = "", quantity = "", unit = "";

		//Changed by sumit sarkar Start.

		String refId = "", empCodeUser = "", currAppdate= "", empCode = "";

		String suggestedInvStat = "", phyHanBasis = "", phyHanBasisDesc = "";

		StringBuffer valueString = new StringBuffer();

		//Changed by sumit sarkar end

		Timestamp currDateNew = null;

		java.util.Date currDate = null;

		java.util.Date utilDate = new java.util.Date();

		java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

		

		String currDateStr = null;

		SimpleDateFormat sdf = null;

		

		ConnDriver connDriver = new ConnDriver();

		DistCommon discommon = new DistCommon();	

		boolean isSelected=false;

		String selectValue="";

		String status="";

		String mrefId="";

		String emptyStatus="N";

		

		//Changed by sumit sarkar on 2/07/12 

		/*double shipperSize = 0;*/

		String phyHanUOM = "";

		String winName="",subCond="";

		NodeList parentNodeList = null;

		Node parentNode=null;

		

		try

		{   

			conn = connDriver.getConnectDB("DriverITM");

			conn.setAutoCommit(false);

			connDriver=null;

		

			DateFormat dateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());

			String dbDateFormat = genericUtility.getDBDateFormat();

			String applDateFormat = genericUtility.getApplDateFormat();

			

			if(objContext != null && objContext.trim().length()>0)

			{

				currentFormNo = Integer.parseInt(objContext);

			}

			

			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");

			valueXmlString.append(editFlag).append("</editFlag></header>");

			currDate = new java.util.Date();

			sdf = new SimpleDateFormat(applDateFormat);

			currDateStr = sdf.format(currDate);

	    	//Changed by sumit sarkar to get login code  start.						

	    	loginCode = checkNull(genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" ));

	    	currDateNew = new java.sql.Timestamp(System.currentTimeMillis()) ;

			currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDateNew).toString();	

			currAppdate = genericUtility.getValidDateString(currAppdate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat());

			currDateNew = Timestamp.valueOf(currAppdate + " 00:00:00.00");

	    	System.out.println("********* login code ["+loginCode+"]");

			switch(currentFormNo)

			{

				case 1 :

				{	

					
					

					parentNodeList = dom.getElementsByTagName("Detail1");

					

					//parentNode = dom.getElementsByTagName("Detail2")[0];

					parentNode = parentNodeList.item(0);

					winName=getObjName(parentNode);

					System.out.println("winName----"+winName);

					if("w_phy_item_scan".equalsIgnoreCase(winName))

					{

					//subCond=" and D.QUANTITY>0 ";//Changed by manoj dtd 21/09/2013 to check previous day empty records
					subCond=" and D.TRAN_TYPE<>'E' ";
					}

					else

					{
						//subCond=" and D.QUANTITY>0 ";
						subCond=" and D.TRAN_TYPE='E' ";	

					}


					

					siteCode =(genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode"));

				    if(currentColumn.trim().equalsIgnoreCase("itm_default"))

					{


				    	//sql="select tran_id from physcan where tran_date=?  and tran_type = 'A' ";
				    	sql="select tran_id from physcan where tran_date=?  and tran_type = 'A' and site_code = ? "; // SQL CHANGE ON 28/MAR/14 BY RITESH
				    	pstmt=conn.prepareStatement(sql);

				    	pstmt.setTimestamp(1,currDateNew);
				    	pstmt.setString(2,siteCode);

				    	rs=pstmt.executeQuery();

				    	if(rs.next())

				    	{

				    		tranId=rs.getString("tran_id");

				    	}

				    	rs.close();

				    	rs=null;

				    	pstmt.close();

				    	pstmt=null;

				    	

				    	if(tranId!=null && tranId.trim().length()>0)

				    	{

				    		valueXmlString.append("<Detail1 domID='1'  selected=\"Y\">");

				    		valueXmlString.append( "<attribute selected=\"Y\" updateFlag=\"E\" status=\"O\" pkNames=\"\"/>\r\n" );

				    		valueXmlString.append( "<tran_id><![CDATA[" ).append( tranId ).append( "]]></tran_id>\r\n" );

				    	}

				    	else

				    	{

				    		valueXmlString.append("<Detail1 domID='1'  selected=\"N\">");

				    		valueXmlString.append( "<attribute selected=\"N\" updateFlag=\"A\" status=\"N\" pkNames=\"\"/>\r\n" );

				    	}

				    	sql = "SELECT EMP_CODE FROM USERS WHERE CODE = ?";

				    	pstmt = conn.prepareStatement( sql );

						pstmt.setString(1, loginCode);						

						rs = pstmt.executeQuery();	

						if( rs.next() )

						{

							empCode = rs.getString("EMP_CODE");

						}

						if(rs != null)

						{	

							rs.close();

							rs = null;

						}

						if(pstmt != null)

						{	

							pstmt.close();

							pstmt = null;

						}				    	

				    	//Changed by sumit sarkar to get login code  end.
						valueXmlString.append( "<tran_type><![CDATA[" ).append("A").append( "]]></tran_type>\r\n" );

						chgTerm = checkNull(genericUtility.getValueFromXTRA_PARAMS( xtraParams, "chgTerm" ));

						siteCode = checkNull(genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginSiteCode" ));

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

						valueXmlString.append("<confirmed protect=\"1\">").append("<![CDATA[N]]>").append("</confirmed>");

						valueXmlString.append( "<tran_date><![CDATA[" ).append( currDateStr ).append( "]]></tran_date>\r\n" );

					    //valueXmlString.append("<eff_date protect=\"1\">").append("<![CDATA["+simpleDateFormat.format(new Date())+"]]>").append("</eff_date>");

						valueXmlString.append("<site_code>").append("<![CDATA["+siteCode+"]]>").append("</site_code>");

						

						//Changed by sumit sarkar on 20/06/12 to set emp_code__user and ref_id start.						

						String resrvLoc  = discommon.getDisparams("999999","RESERV_LOCATION",conn);

						String casePickLoc  = discommon.getDisparams("999999","CASE_PICK_INVSTAT",conn);

						//String activePickLoc  = discommon.getDisparams("999999","ACTIVE_PICK_INVSTAT",conn);

						String deepStoreLoc  = discommon.getDisparams("999999","DEEP_STORE_INVSTAT",conn);						

							

						sSQL = "SELECT DISTINCT L.INV_STAT FROM PHYSCAN H,PHYSCANDET D,ITEM M,LOCATION L"

							   +" WHERE H.TRAN_DATE = ? AND  H.SITE_CODE = '"+siteCode+"' AND "   // SITE_CODE ADDED ON 28/MAR/2014 BY RITESH FOR EMPTY LOCATION SCAN

							   + " D.ITEM_CODE = M.ITEM_CODE(+)   "+subCond
							   //Changed By Pragyan 17-11-12 as the join fails for header and detail
							   //Changed by manoj shrama on 1-11-12
							  // +" AND D.LOC_CODE = L.LOC_CODE  AND L.INV_STAT IN(?,?,?) AND H.TRAN_TYPE = 'A' AND D.STATUS <> 'Y' "; //change done by  Kunal on 13/10/12 add cond. for status
							 //+" AND D.LOC_CODE = L.LOC_CODE  AND L.INV_STAT IN(?,?,?) AND H.TRAN_TYPE = 'A' AND CASE WHEN D.STATUS IS NULL THEN 'N' ELSE D.STATUS END <> 'Y' "; //change done by  Kunal on 13/10/12 add cond. for status
							   +" AND H.TRAN_ID = D.TRAN_ID AND D.LOC_CODE = L.LOC_CODE  AND L.INV_STAT IN(?,?,?) AND H.TRAN_TYPE = 'A' AND CASE WHEN D.STATUS IS NULL THEN 'N' ELSE D.STATUS END <> 'Y' "; //change done by  Kunal on 13/10/12 add cond. for status

	

						System.out.println("** sSQL **["+sSQL+"]");

						pstmt = conn.prepareStatement(sSQL);

						pstmt.setDate(1, sqlDate);

						pstmt.setString(2, resrvLoc);

						pstmt.setString(3, casePickLoc);						

						pstmt.setString(4, deepStoreLoc);

						

						rs = pstmt.executeQuery();							

						while(rs.next())

						{

							valueString.append( rs.getString("INV_STAT").trim() ).append(" , ");

						}

						if( valueString.length() > 0)

						{

							valueString = valueString.deleteCharAt(valueString.toString().length()-2) ;

						}

						else

						{

							valueString.append("");

						}

						suggestedInvStat = valueString.toString();

						

						if(rs != null)

						{	

							rs.close();

							rs = null;

						}

						if(pstmt != null)

						{	

							pstmt.close();

							pstmt = null;

						}

						

						

						valueXmlString.append( "<suggested_inv_stat><![CDATA[" ).append( checkNull(suggestedInvStat) ).append( "]]></suggested_inv_stat>\r\n" );

						valueXmlString.append( "<emp_code__user><![CDATA[" ).append( empCode ).append( "]]></emp_code__user>\r\n" );

						//valueXmlString.append( "<ref_id><![CDATA[" ).append( refId ).append( "]]></ref_id>\r\n" );

						//Changed by sumit sarkar on 20/06/12 to set emp_code__user and ref_id end.

						

						sql = "SELECT DESCR FROM SITE WHERE SITE_CODE = ?";

						pstmt = conn.prepareStatement( sql );

						pstmt.setString( 1, siteCode );						

						rs = pstmt.executeQuery();	

						if( rs.next() )

						{

							siteDescr = rs.getString("DESCR");

						}

						if(rs != null)

						{	

							rs.close();

							rs = null;

						}

						if(pstmt != null)

						{	

							pstmt.close();

							pstmt = null;

						}	

						valueXmlString.append( "<descr><![CDATA[" ).append( checkNull( siteDescr )).append( "]]></descr>\r\n" );

						valueXmlString.append( "<chg_user><![CDATA[" ).append( loginCode ).append( "]]></chg_user>\r\n" );

						valueXmlString.append( "<chg_date><![CDATA[" ).append( currDateStr ).append( "]]></chg_date>\r\n" );

						valueXmlString.append( "<chg_term><![CDATA[" ).append( chgTerm ).append( "]]></chg_term>\r\n" );

												

	                }

					

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

				  }	

	              break;

				  case 2 :

				  {	  

					  //Changed by sumit sarkar on 18/06/12 taking loginCode variable 

					  loginCode = checkNull(genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" ));

					  System.out.println("loginCode --->["+loginCode+"]");
					  
					  
					  parentNodeList = dom.getElementsByTagName("Detail2");

						

						//parentNode = dom.getElementsByTagName("Detail2")[0];

						parentNode = parentNodeList.item(0);

						winName=getObjName(parentNode);

						if("w_phy_item_scan".equalsIgnoreCase(winName))

						{

						//subCond=" and D.QUANTITY>0 ";//Changed by manoj dtd 21/09/2013 to check previous day empty records
						subCond=" and D.TRAN_TYPE<>'E' ";
						}

						else

						{
							//subCond=" and D.QUANTITY>0 ";
							subCond=" and D.TRAN_TYPE='E' ";	

						}

						System.out.println("subCond----"+subCond);

						tranId=genericUtility.getColumnValue("tran_id",dom1);

					  if(currentColumn.trim().equalsIgnoreCase("itm_default"))

					  {

						  

						  	String resrvLoc  = discommon.getDisparams("999999","RESERV_LOCATION",conn);

							String casePickLoc  = discommon.getDisparams("999999","CASE_PICK_INVSTAT",conn);

							String activePickLoc  = discommon.getDisparams("999999","ACTIVE_PICK_INVSTAT",conn);

							String deepStoreLoc  = discommon.getDisparams("999999","DEEP_STORE_INVSTAT",conn);

							refId=genericUtility.getColumnValue("ref_id",dom1);

							

							

						  System.out.println("Default Data Set 8888888888888888888**************"+genericUtility.getColumnValue("inv_stat",dom1));			

//						sSQL = "SELECT I.ITEM_CODE,S.SITE_CODE,S.LOC_CODE,S.LOT_NO,S.LOT_SL,"

//							   //Changed by sumit on 10/07/12 taking data of PHY_HAN_BASIS from location table.

//							   //+" S.QUANTITY,S.UNIT,M.DESCR AS ITEM_DESCR,L.DESCR AS LOC_DESCR FROM CYCLECNT_SCH I,STOCK S,ITEM M,LOCATION L"

//							   +" S.QUANTITY,S.UNIT,M.DESCR AS ITEM_DESCR,L.DESCR AS LOC_DESCR, L.PHY_HAN_BASIS, L.PHY_HAN_UOM FROM CYCLECNT_SCH I,STOCK S,ITEM M,LOCATION L"

//							   +" WHERE I.TRAN_DATE = ? AND I.ITEM_CODE = S.ITEM_CODE AND " 

//							   + " I.ITEM_CODE = M.ITEM_CODE  AND S.QUANTITY > 0 "

//							   //Changed By sumit sarka    start.

//							   //+" AND S.LOC_CODE = L.LOC_CODE  AND L.INV_STAT IN(?,?,?,?) " 							   

//							   //Changed as Per Kandarp Sir 18/06/2012

//							   //+ " ORDER BY I.PRIORITY_SEQ";

//							   //+ " ORDER BY I.PRIORITY_SEQ,S.LOC_CODE";

//						       +" AND S.LOC_CODE = L.LOC_CODE  AND L.INV_STAT = ? "

//						       + " ORDER BY S.LOC_CODE";

//						     //Changed By sumit sarka    end.

						  

						  sSQL="SELECT D.LINE_NO,D.ITEM_CODE,B.DESCR,D.SITE_CODE,D.LOC_CODE,C.DESCR LOC_DESCR,D.LOT_SL,D.LOT_NO,D.QUANTITY,B.UNIT,C.PHY_HAN_BASIS,C.PHY_HAN_UOM,CASE WHEN D.STATUS IS NULL THEN 'N' ELSE D.STATUS END AS STATUS "+//, CASE WHEN D.ISEMPTY IS NULL THEN 'N' ELSE D.ISEMPTY END AS ISEMPTY  " +
						  	   " ,CASE WHEN D.PHY_INPUT IS NULL THEN 0 ELSE D.PHY_INPUT END PHY_INPUT "+
						  		" FROM PHYSCAN S,PHYSCANDET D,ITEM B,LOCATION C WHERE S.TRAN_ID=D.TRAN_ID "+subCond+" AND  D.ITEM_CODE=B.ITEM_CODE(+) AND D.LOC_CODE=C.LOC_CODE AND  D.TRAN_ID=? AND C.INV_STAT=?  ORDER BY PRIORITY_SEQ ASC"; //change done by kunal on 07/09/12 add order by



						System.out.println("** sSQL **["+sSQL+"]");

						pstmt = conn.prepareStatement(sSQL);

						pstmt.setString(1,tranId);

						pstmt.setString(2,genericUtility.getColumnValue("inv_stat",dom1));

						//pstmt.setDate(1, sqlDate);

						//Changed by sumit sarkar

						/*pstmt.setString(2, resrvLoc);

						pstmt.setString(3, casePickLoc);

						pstmt.setString(4, activePickLoc);

						pstmt.setString(5, deepStoreLoc);*/

						//pstmt.setString(2, genericUtility.getColumnValue("inv_stat",dom1));						

						rs = pstmt.executeQuery();	

						int count=0;

						while(rs.next())

						{

							//lineNo++;		

							count=0;

							itemCode = checkNull(rs.getString("ITEM_CODE"));

							itemDescr = checkNull(rs.getString("DESCR"));

							siteCode = checkNull(rs.getString("SITE_CODE"));

							locCode = checkNull(rs.getString("LOC_CODE"));

							locDescr = checkNull(rs.getString("LOC_DESCR"));

							lotNo = checkNull(rs.getString("LOT_NO"));

							lotSl = checkNull(rs.getString("LOT_SL"));

							quantity  = checkNull(rs.getString("QUANTITY"));														

							unit = checkNull(rs.getString("UNIT"));

							//Changed by sumit on 10/07/12 

							phyHanBasis = checkNull(rs.getString("PHY_HAN_BASIS"));

							phyHanUOM = checkNull(rs.getString("PHY_HAN_UOM"));

							status=checkNull(rs.getString("STATUS"));

							lineNo=rs.getInt("LINE_NO");

							System.out.println("phyHanBasis - >["+phyHanBasis+"] phyHanUOM ["+phyHanUOM+"]" );

							//if this record exist then append												

							isSelected=false;

							selectValue="N";

							count=1;

							//emptyStatus=rs.getString("ISEMPTY");

							

							phyHanBasisDesc = "";

							if (phyHanBasis != null ) 

							{

								if ("L".equalsIgnoreCase(phyHanBasis)) {

									phyHanBasisDesc = "Lot Wise Shipper";

								} else if ("I".equalsIgnoreCase(phyHanBasis)) 

								{

									phyHanBasisDesc = " Integral Quantity";

								} else if ("U".equalsIgnoreCase(phyHanBasis)) 

								{

									phyHanBasisDesc = "UOM";

									

								} else if ("P".equalsIgnoreCase(phyHanBasis)) 

								{

									phyHanBasisDesc = "Pallet Basis";

								}

							}

							System.out.println(" phyHanBasisDesc ["+phyHanBasisDesc+"]");

							//change done by kunal on 28/01/13 add CDATA
									if("Y".equalsIgnoreCase(status))

									{

										valueXmlString.append( "<Detail2 domID='"+ lineNo +"' selected=\"Y\">\r\n" );

										valueXmlString.append( "<attribute selected=\"Y\" updateFlag=\"E\" status=\"O\" pkNames=\"\"/>\r\n" );

										valueXmlString.append( "<tran_id><![CDATA[").append(tranId).append("]]></tran_id>\r\n" );

										valueXmlString.append("<line_no><![CDATA[").append(lineNo).append("]]></line_no>\r\n");

										//valueXmlString.append( "<tran_id>" ).append(tranId).append("</tran_id");

									}

									else

									{

										valueXmlString.append( "<Detail2 domID='"+ lineNo +"' selected=\"N\">\r\n" );

										valueXmlString.append( "<attribute selected=\"Y\" updateFlag=\"E\" status=\"O\" pkNames=\"\"/>\r\n" );

										valueXmlString.append( "<tran_id><![CDATA[").append(tranId).append("]]></tran_id>\r\n" );

										valueXmlString.append("<line_no><![CDATA[").append(lineNo).append("]]></line_no>\r\n");

									}

									valueXmlString.append("<item_code><![CDATA[").append(checkNullAndTrim(itemCode)).append("]]></item_code>\r\n");

									valueXmlString.append("<descr><![CDATA[").append(itemDescr).append("]]></descr>\r\n");

									valueXmlString.append("<site_code><![CDATA[").append(siteCode).append("]]></site_code>\r\n");

									valueXmlString.append("<loc_code><![CDATA[").append(checkNullAndTrim(locCode)).append("]]></loc_code>\r\n");

									valueXmlString.append("<location_descr><![CDATA[").append(locDescr).append("]]></location_descr>\r\n");

									valueXmlString.append("<lot_no><![CDATA[").append(checkNullAndTrim(lotNo)).append("]]></lot_no>\r\n");

									valueXmlString.append("<lot_sl><![CDATA[").append(checkNullAndTrim(lotSl)).append("]]></lot_sl>\r\n");

									valueXmlString.append("<quantity><![CDATA[").append(quantity).append("]]></quantity>\r\n");														

									valueXmlString.append("<unit><![CDATA[").append(unit).append("]]></unit>\r\n");														

									valueXmlString.append("<qty_physical><![CDATA[").append(("0")).append("]]></qty_physical>\r\n");

									valueXmlString.append("<phy_han_basis><![CDATA[").append(checkNull(phyHanBasis)).append("]]></phy_han_basis>\r\n");

									valueXmlString.append("<phy_input_scan><![CDATA[").append(phyHanBasisDesc).append("]]></phy_input_scan>\r\n");

									valueXmlString.append("<phy_input><![CDATA[").append(rs.getInt("PHY_INPUT")).append("]]></phy_input>\r\n");

									if("w_empty_loc_scan".equalsIgnoreCase(winName))

									{

										valueXmlString.append("<isempty><![CDATA[").append(emptyStatus).append("]]></isempty>\r\n");

									}

									if( "U".equalsIgnoreCase(phyHanBasis))

									{

										valueXmlString.append("<conv_fact><![CDATA[").append(checkNull(phyHanUOM)).append("]]></conv_fact>\r\n");

									}

									else

									{

										valueXmlString.append("<conv_fact>").append("").append("</conv_fact>\r\n");

									}
									valueXmlString.append("<emp_code__user><![CDATA[").append(genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginEmpCode" )).append("]]></emp_code__user>\r\n"); // Added By Mahesh Patidar on 20/08/12
									valueXmlString.append("</Detail2>\r\n");

									System.out.println("valueXmlString----"+valueXmlString.toString());							

							

							empCodeUser = "";

							if(pstmt1 != null)

							 {

								 pstmt1.close();

								 pstmt1 = null;									 

							 }

							if(rsDet != null)

							{
								rsDet.close();
								rsDet = null;

							}
						
							//Changed by sumit sarkar on 20/06/12 done item not needed to display  END.

							

							System.out.println("\n&&&&&&&&&&&&&\n");

							//System.out.println("updatedDetailDomStr[1]:>>>>>>>>>>> "+updatedDetailDomStr);				

						}

						//Changed by sumit srkar on 14/07/12 commented below code

						/*System.out.println("ALLLLLLLLLLLL   ------------Going For add Selected Dom****888888******");

						String updatedDetailDomStr = addSelectedRecToDom( dom2, valueXmlString.toString() );

						System.out.println("END  For add Selected Dom*******");

						valueXmlString = null;

						valueXmlString = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root>\r\n<Header>\r\n<editFlag>").append( editFlag );

						valueXmlString.append("</editFlag>\r\n</Header>\r\n");

						updatedDetailDomStr = updatedDetailDomStr.substring(updatedDetailDomStr.indexOf("<Root>") + "<Root>".length(), updatedDetailDomStr.indexOf("</Root>") );

						valueXmlString.append(updatedDetailDomStr);*/

						if(pstmt != null)

						 {

							 pstmt.close();

							 pstmt = null;									 

						 }

						

						if(rs != null)

						{

							 rs.close();

							 rs = null;

						}		

					  }	

				   }

				  break;

			}

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

			System.out.println("=================["+valueXmlString+"]");

		}

		catch(Exception e)

		{

			e.printStackTrace();

			System.out.println("Exception ::"+e.getMessage());

			throw new ITMException(e);

		}

		finally

		{

			try

			{

				if(conn!=null)

				{

					if(pstmt != null)

					{	

						pstmt.close();

						pstmt = null;

					}	

					if(rs != null)

					{	

						rs.close();

						rs = null;

					}	

					if(conn != null)

					{	

						conn.close();

						conn = null;

					}	

				}

				

			}

			catch(Exception d)

			{

			  d.printStackTrace();

			}			

		}

		return valueXmlString.toString();

	}

	

	private String addSelectedRecToDom( Document allFormDataDom, String detailString ) throws Exception

	{

		System.out.println("Enter in All Selected DOM");

		ArrayList selectedList = new ArrayList();

		NodeList detailList = null;

		Node currDetail = null;

		NodeList currDetailList = null;

		String selectedVal = "", nodeName = "", updateStatus = "";

		String domIDVal = "";

		String updatedDetailDomStr = "";

		String attributeVal = "";

		String locCodeTo = "";

		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("Detail2");

			detailListLength = detailList.getLength();

			for ( int ctr = 0; ctr < detailListLength; ctr++ )

			{

				System.out.println("FOR LP");

				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("qty_physical"))

					{

						if ( childNode != null && childNode.getFirstChild() != null )

						{

							System.out.println("Adding TO dataMap["+childNode);

							//locCodeTo = childNode.getFirstChild().getNodeValue();

							//toUpdNodeList.add( 1, childNode );

							dataMap.put("qty_physical", childNode);

						}

					}

				}//End of inner for loop

				if ( "Y".equalsIgnoreCase(attributeVal.trim()) )

				{

					System.out.println("Enter in Sele DOM");

					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("Detail2");

			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) )

							{

								System.out.println("Going For Checking SELECTED DOM");

								elementAttr = (Element)currDetail;

								elementAttr.setAttribute( "selected" , "Y" );

								

								Node QtyPhy = null;



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



								if ( dataMap.get("qty_physical") != null )

								{

									QtyPhy = (Node)dataMap.get("qty_physical");

								}

								

								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("qty_physical") )

									{

										//System.out.println("LocCodeToNode =["+genericUtility.serializeDom( LocCodeToNode )+"]");

										updatedNode = detailDom.importNode(QtyPhy, true);

										//System.out.println("updatedNode =["+genericUtility.serializeDom( updatedNode )+"]");

										(detailDom.getElementsByTagName("Detail2").item(ctr)).replaceChild(updatedNode, elementName );

									}

								}//inner for loop

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

		}

		

		return updatedDetailDomStr;

	}



	private String checkNullAndTrim( String inputVal )

	{

		if ( inputVal == null )

		{

			inputVal = "";

		}

		else

		{

			inputVal = inputVal.trim();

		}

		return inputVal;

	}

	private String checkNull( String inputVal )

	{

		if ( inputVal == null )

		{

			inputVal = "";

		}

		return inputVal;

	}

	//Changed by sumit sarkar on 2/07/12 checking numeric value start.

	private boolean isInteger( String input )  

    {  

       try  

       {  

    	   System.out.println(" Value of input ["+input+"]");

          Integer.parseInt( input );  

          return true;  

       }  

       catch( Exception e)  

       {  

          return false;  

       }  

    }

	//Changed by sumit sarkar on 2/07/12 checking numeric value end.

	

	//c

	private double quanitityPerPallet(String itemCode,String lotNo, double pallet ,Connection conn)

	{

		int findNosOfPallet=0;

		int nosOfPalletPerVolume=0;

		int nosOfPalletPerWeight=0;

		int perPalletArticle=0;

		

		String sql="";

		PreparedStatement pstmt = null;

		ResultSet rs =null;

		double shipperSize =0.0;

		double grossWeight =0.0;

		double netWeight =0.0;

		double length=0.0;

		double width=0.0;

		double height=0.0;

		Double nosOfPallet=0.0;

		double quantity = 0.0;

		DistCommon distComm = new DistCommon();

		

		sql= "SELECT SHIPPER_SIZE, GROSS_WEIGHT, NET_WEIGHT, LENGTH, WIDTH ,HEIGHT FROM ITEM_LOT_PACKSIZE WHERE ITEM_CODE = ? " +

				" AND ? BETWEEN LOT_NO__FROM AND LOT_NO__TO "; 

		try {

			pstmt =conn.prepareStatement(sql);

			pstmt.setString(1,itemCode);

			pstmt.setString(2,lotNo);

			rs=pstmt.executeQuery();

			if(rs.next())

			{

				shipperSize=rs.getDouble(1);

				grossWeight =rs.getDouble(2);

				netWeight=rs.getDouble(3);

				length=rs.getDouble(4);

				width=rs.getDouble(5);

				height=rs.getDouble(6);

			}

			rs.close();

			pstmt.close();

			rs=null;

			pstmt =null;

			double perPallateVolume = Double.parseDouble(distComm.getDisparams("999999","PER_PALLET__VOLUME",conn));

			System.out.println("shipperSize ["+shipperSize+"] grossWeight ["+grossWeight+"] netWeight ["+netWeight+"] length ["+length+"] width ["+width+"] height ["+height+"]");

			//nosOfPallet=(quantity*length*width*height/shipperSize)/(Double.parseDouble(distComm.getDisparams("999999","PER_PALLET__VOLUME",conn)));

			double newValue = Math.floor((pallet * perPallateVolume)/(length*width*height));

			System.out.println(" before Math.floor -->["+newValue+"]");

			quantity = newValue * shipperSize;			

			System.out.println("<!@#>QUANTITY  " +quantity);

			/*//nosOfPalletPerVolume=(new Double((Math.round(nosOfPallet)))).intValue();

			System.out.println("<!@#>nosOfPalletPerVolume" +nosOfPalletPerVolume);*/						

			//System.out.println("<!@#>findNosOfPallet" +findNosOfPallet);

			

		} catch (SQLException e) {

			

			e.printStackTrace();

		}		

		return quantity; 

	}

	private String getObjName(Node node) throws Exception

	{

		String objName = null;

		NodeList nodeList = null;

		Node detaulNode = null;

		Node detailNode = null;

		nodeList = node.getChildNodes();

		NamedNodeMap attrMap = node.getAttributes();

		objName = attrMap.getNamedItem( "objName" ).getNodeValue();

		/*

		for(int ctr = 0; ctr < nodeList.getLength(); ctr++ )

		{

			detailNode = nodeList.item(ctr);

			if(detailNode.getNodeName().equalsIgnoreCase("attribute") )

			{

				objName = detailNode.getAttributes().getNamedItem("objName").getNodeValue();

			}

		}

		*/

		return "w_" + objName;



	}

	

	//Changed by sumit sarkar on 16/07/12 method to get attribute value start.

	private String attributeValue(Document allFormDataDom) throws Exception

	{



		ArrayList selectedList = new ArrayList();

		NodeList detailList = null;

		Node currDetail = null;

		NodeList currDetailList = null;

		String selectedVal = "", nodeName = "", updateStatus = "";

		String domIDVal = "";

		String updatedDetailDomStr = "";

		String attributeVal = "";

		String locCodeTo = "";

		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("Detail2");

			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					

				}

			}

			System.out.println("attributeVal @@>>>>>>>>>>> "+updatedDetailDomStr);

		}

		catch (Exception e)

		{

			e.printStackTrace();

			throw e;

		}

		return attributeVal;

	}

	//Changed by sumit sarkar on 16/07/12 method to get attribute value end.

}// END OF MAIN CLASS

		

		