// Title:
// Version:
// Copyright:		Copyright Bestseller (c) 2000
// Author: 			Generated by EJBGen v0.1
// Description: 	
// Date: 				Thu Oct 12 11:15:34 EDT 2000	

package com.bestsel.acqui.server.ordtitinf;

import com.bestsel.sharedntier.ServerModuleConf;

import com.bestsel.sharedntier.DirtyReadException;

import javax.ejb.*;
import java.sql.*;
import java.rmi.*;
import java.util.*;

import javax.sql.*;
import javax.naming.*;


import com.bestsel.common.BSConstants;
import com.bestsel.bcomponents.BDateDocument;
import java.text.NumberFormat;

public class ordtitinfBean implements EntityBean {
	private int saveStatus = 0;
	String query="";
	String query2="";
	Connection Con=null;
	Statement stmt=null;
	private EntityContext ectx = null;
	private ordtitinfData rd = new ordtitinfData();
	private boolean bDirty = false;
	private NumberFormat NF = java.text.NumberFormat.getNumberInstance(Locale.US);

	private static String className ="ordtitinfBean";
	public ordtitinfBean() {
		ServerModuleConf.traceOut("in " + className + " constructor",ServerModuleConf.TRACE_EXCEPTION);
		NF.setGroupingUsed(false);
		NF.setMaximumIntegerDigits(20);
		NF.setMaximumFractionDigits(7);
	}
	public ordtitinfPK ejbCreate(ordtitinfData rd) throws RemoteException, CreateException
	{
System.out.println("Start ejbCreate...");
		ServerModuleConf.traceOut("in "+className+".ejbCreate().",ServerModuleConf.TRACE_DEBUG);
     this.rd = rd;
			String is_quebecois;
		 if (rd.is_quebecois == true)
			is_quebecois = new String ("01");
		else
			is_quebecois = new String ("00");

		String query = "insert into AC_TITLE_INFO " +
		"( "+
"AC_TITLE_INFO.SEQ_NO," +
	"AC_TITLE_INFO.COMMERCIAL_STATUS," +
	"AC_TITLE_INFO.DATE_STATUS_MO," +
	"AC_TITLE_INFO.PUBLISHER_CODE," +
	"AC_TITLE_INFO.PRICE_TITLE," +
	"AC_TITLE_INFO.DATE_PRICE_MO," +
	"AC_TITLE_INFO.CURRENCY_CODE," +
	"AC_TITLE_INFO.DOCUMENT_TYPE," +
	"AC_TITLE_INFO.IS_QUEBECOIS," +
	"AC_TITLE_INFO.DATE_CREATED," +
	"AC_TITLE_INFO.DATE_MODIFIED," +
	"AC_TITLE_INFO.USER_CODE_CR," +
	"AC_TITLE_INFO.USER_CODE_MO		)" +
		" values("
+ rd.seq_no+ ", "
	+"'"+ rd.commercial_status+"'"+ ", "
	+"'"+ rd.date_status_mo+"'"+ ", "
	+"'"+ rd.publisher_code+"'"+ ", "
	+ NF.format(rd.price_title).toString()+ ", "
	+"'"+ rd.date_price_mo+"'"+ ", "
	+"'"+ rd.currency_code+"'"+ ", "
	+"'"+ rd.document_type+"'"+ ", "
	+"'"+is_quebecois+"'"+ ", "
	+"'"+ rd.date_created+"'"+ ", "
	+"'"+ rd.date_modified+"'"+ ", "
	+"'"+ rd.user_code_cr+"'"+ ", "
	+"'"+ rd.user_code_mo+"'"+ ")";

	ServerModuleConf.traceOut(className+".ejbcreate: "+ query,ServerModuleConf.TRACE_DEBUG);
System.out.flush();

  	try{
		  Con = getConnection();
      Con.setAutoCommit(false);
		  stmt = Con.createStatement();
		  stmt.executeUpdate(query);
		  return new ordtitinfPK(rd.seq_no);
	  }
    catch(java.sql.SQLException sqlex){ }
  	finally
		{
//		    cleanConnection(Con, stmt, null);
		}
    return null;
	} // ejbCreate
	public void ejbPostCreate(ordtitinfData rd){
		ServerModuleConf.traceOut("In "+className+".ejbPostCreate().",ServerModuleConf.TRACE_DEBUG);
		this.rd = rd;
	}
	public ordtitinfPK ejbFindByPrimaryKey(ordtitinfPK pk) throws EJBException,FinderException{
		ServerModuleConf.traceOut("inside "+className+".ejbFindbyPrimaryKey(),pk :"+pk.toString(),
		ServerModuleConf.TRACE_DEBUG);
		try {
		rd = refresh(
			pk.seq_no);
			return pk;
		} catch (Exception ex) {
			if(ex instanceof FinderException){
				ServerModuleConf.traceOut(className+".ejbFindByPrimaryKey(): caught FinderException, pk= "+pk.toString(),ServerModuleConf.TRACE_EXCEPTION);
				throw new FinderException(ex.toString());
			}else
				throw new EJBException(ex);
		}
	}
	private static synchronized ordtitinfData refresh(		int seq_no) throws FinderException, EJBException{
		ordtitinfData RD = new ordtitinfData();
		Connection Con = null;
		Statement stmt = null;
		ResultSet rs = null;
		ServerModuleConf.traceOut("inside "+className+".Refresh().",ServerModuleConf.TRACE_DEBUG);
		try {
		String query = "select " + 
"AC_TITLE_INFO.SEQ_NO," + 
	"AC_TITLE_INFO.COMMERCIAL_STATUS," + 
	"AC_TITLE_INFO.DATE_STATUS_MO," + 
	"AC_TITLE_INFO.PUBLISHER_CODE," + 
	"AC_TITLE_INFO.PRICE_TITLE," + 
	"AC_TITLE_INFO.DATE_PRICE_MO," + 
	"AC_TITLE_INFO.CURRENCY_CODE," + 
	"AC_TITLE_INFO.DOCUMENT_TYPE," + 
	"AC_TITLE_INFO.IS_QUEBECOIS," + 
	"AC_TITLE_INFO.DATE_CREATED," + 
	"AC_TITLE_INFO.DATE_MODIFIED," + 
	"AC_TITLE_INFO.USER_CODE_CR," + 
	"AC_TITLE_INFO.USER_CODE_MO" +
		" from AC_TITLE_INFO " +
" where " +
		"AC_TITLE_INFO.seq_no="+ seq_no+ ""; 
			Con = ServerModuleConf.cnMgr.getConnection(10000,true);
Con.setAutoCommit(false);

			stmt = Con.createStatement();
			rs = stmt.executeQuery(query);
		if(rs.next()) {
			RD.seq_no= rs.getInt(1); 
				RD.commercial_status= rs.getString(2); 
				RD.date_status_mo= BDateDocument.toSQL(rs.getDate(3)); 
				RD.publisher_code= rs.getString(4); 
				RD.price_title= rs.getDouble(5); 
				RD.date_price_mo= BDateDocument.toSQL(rs.getDate(6)); 
				RD.currency_code= rs.getString(7); 
				RD.document_type= rs.getString(8); 
				RD.is_quebecois= rs.getBoolean(9); 
				RD.date_created= BDateDocument.toSQL(rs.getDate(10)); 
				RD.date_modified= BDateDocument.toSQL(rs.getDate(11)); 
				RD.user_code_cr= rs.getString(12); 
				RD.user_code_mo= rs.getString(13);
ServerModuleConf.traceOut("Inside Refresh rd: "+ RD.toString(),ServerModuleConf.TRACE_DEBUG);
		} else {
			throw new FinderException("ordtitinf.refresh - record not found");
		}
		} catch(SQLException e) {
			ServerModuleConf.traceOut("Exception in"+className+".refresh(): "+ServerModuleConf.getStackTrace(e),ServerModuleConf.TRACE_DEBUG);
			throw new EJBException("ordtitinf.refresh - "+e.getMessage());
		} finally {
		try {
				stmt.close();
				ServerModuleConf.cnMgr.putConnection(Con);
				Con=null;
			}catch(Exception e) {}
		}
		return RD;
	}
	public Enumeration ejbFindAll() throws FinderException,EJBException{
		ResultSet rs = null;
		Vector v = new Vector();
		try {
		String query = "select " + 
"AC_TITLE_INFO.SEQ_NO," + 
	"AC_TITLE_INFO.COMMERCIAL_STATUS," + 
	"AC_TITLE_INFO.DATE_STATUS_MO," + 
	"AC_TITLE_INFO.PUBLISHER_CODE," + 
	"AC_TITLE_INFO.PRICE_TITLE," + 
	"AC_TITLE_INFO.DATE_PRICE_MO," + 
	"AC_TITLE_INFO.CURRENCY_CODE," + 
	"AC_TITLE_INFO.DOCUMENT_TYPE," + 
	"AC_TITLE_INFO.IS_QUEBECOIS," + 
	"AC_TITLE_INFO.DATE_CREATED," + 
	"AC_TITLE_INFO.DATE_MODIFIED," + 
	"AC_TITLE_INFO.USER_CODE_CR," + 
	"AC_TITLE_INFO.USER_CODE_MO"+
		" from AC_TITLE_INFO ";
			Con = ServerModuleConf.cnMgr.getConnection(10000,true);
Con.setAutoCommit(false);

		stmt = Con.createStatement();
		rs = stmt.executeQuery(query);
		ordtitinfPK pk;
		while(rs.next()) {
		pk = new ordtitinfPK(
		 rs.getInt(1));
		v.addElement(pk);
		}
		} catch(SQLException e) {
		e.printStackTrace();
		throw new EJBException("ordtitinfBean.ejbFindAll() - error: " + e);
		} finally {
			try {
		if(rs != null) rs.close();
		if(stmt != null) stmt.close();
		ServerModuleConf.cnMgr.putConnection(Con);
		Con=null;
		}catch(Exception e) {}
	}
	return v.elements();
	}
	public ordtitinfData getData() 
	{
		return rd;
	}
	public void setData(ordtitinfData rd, ordtitinfData rdold)throws EJBException,DirtyReadException{
		ServerModuleConf.traceOut("Inside setData().",ServerModuleConf.TRACE_DEBUG);
	// reread the table from the database 
	// then check if it has been modified by another process 
	try {
	if (!recDirty(rdold)){ // Make the select for update
			this.rd = rd;
		}
		}catch (Exception ex) {
			ServerModuleConf.traceOut("Exception in "+className+"SetData(): "+ex.getMessage(),ServerModuleConf.TRACE_EXCEPTION);
			if(bDirty!=true){
				throw new EJBException(ex);
			}		}finally{
			if (bDirty == true){
				throw new DirtyReadException(BSConstants.EXCEPTION_RECORD_CONCURRENTLY_MODIFIED);
			}
		}//finally
	}
	public boolean recDirty(ordtitinfData rdOld) throws EJBException,FinderException{
		ServerModuleConf.traceOut("Inside ordtitinf.recDirty().",ServerModuleConf.TRACE_DEBUG);
		ordtitinfData rdCur = new ordtitinfData();
		ResultSet rs = null;
		bDirty = false;
		try {
		String query = "select " + 
"AC_TITLE_INFO.SEQ_NO," + 
	"AC_TITLE_INFO.COMMERCIAL_STATUS," + 
	"AC_TITLE_INFO.DATE_STATUS_MO," + 
	"AC_TITLE_INFO.PUBLISHER_CODE," + 
	"AC_TITLE_INFO.PRICE_TITLE," + 
	"AC_TITLE_INFO.DATE_PRICE_MO," + 
	"AC_TITLE_INFO.CURRENCY_CODE," + 
	"AC_TITLE_INFO.DOCUMENT_TYPE," + 
	"AC_TITLE_INFO.IS_QUEBECOIS," + 
	"AC_TITLE_INFO.DATE_CREATED," + 
	"AC_TITLE_INFO.DATE_MODIFIED," + 
	"AC_TITLE_INFO.USER_CODE_CR," + 
	"AC_TITLE_INFO.USER_CODE_MO" +
		" from AC_TITLE_INFO " +
" where " +
		"AC_TITLE_INFO.seq_no="+ rdOld.seq_no+ "";
			Con = ServerModuleConf.cnMgr.getConnection(10000,true);
Con.setAutoCommit(false);

			stmt = Con.createStatement();
			rs = stmt.executeQuery(query);
			if(rs.next()) {
				rdCur.seq_no= rs.getInt(1); 
					rdCur.commercial_status= rs.getString(2); 
					rdCur.date_status_mo= BDateDocument.toSQL(rs.getDate(3)); 
					rdCur.publisher_code= rs.getString(4); 
					rdCur.price_title= rs.getDouble(5); 
					rdCur.date_price_mo= BDateDocument.toSQL(rs.getDate(6)); 
					rdCur.currency_code= rs.getString(7); 
					rdCur.document_type= rs.getString(8); 
					rdCur.is_quebecois= rs.getBoolean(9); 
					rdCur.date_created= BDateDocument.toSQL(rs.getDate(10)); 
					rdCur.date_modified= BDateDocument.toSQL(rs.getDate(11)); 
					rdCur.user_code_cr= rs.getString(12); 
					rdCur.user_code_mo= rs.getString(13);
		if ((rdCur.toString()).compareTo(rdOld.toString()) != 0) {
			ServerModuleConf.traceOut("rdCur vs rdOld : "+rdCur.toString()+"\n"+rdOld.toString(),ServerModuleConf.TRACE_DEBUG);
			bDirty = true;
			// Unlock the Record !!!
			try{Con.rollback();}catch(SQLException sqle){}
		
}
		} else {//we got an empty resultSet
			bDirty = true;
			ServerModuleConf.traceOut(className+".recDirty(): pk "+rd.seq_no+" not found.",ServerModuleConf.TRACE_DEBUG);
			throw new FinderException(className +".recDirty - record not found");
		}
		} catch(SQLException e) {
		ServerModuleConf.traceOut(e.toString(),ServerModuleConf.TRACE_EXCEPTION);
			// Unlock the Record !!!
			try{Con.rollback();}catch(SQLException sqle){}
			throw new EJBException(className + ".recDirty - "+e.getMessage());
		} finally {
			try {
				stmt.close();
				if(bDirty==true){//We keep the con if record not dirty
					ServerModuleConf.cnMgr.putConnection(Con);
					Con = null;
				}
			}catch(Exception e) {}
	}
	return bDirty;
	}
	public void setEntityContext(EntityContext ectx) throws RemoteException 
	{
		ServerModuleConf.traceOut("inside setEntityContext(): ",ServerModuleConf.TRACE_DEBUG);
		this.ectx = ectx;
	}
	public void unsetEntityContext() throws RemoteException 
	{
		ServerModuleConf.traceOut("inside unsetEntityContext(): ",ServerModuleConf.TRACE_DEBUG);
		this.ectx = null;
	}
	public void ejbActivate() throws RemoteException
	{
		ServerModuleConf.traceOut("inside ejbActivate(): ",ServerModuleConf.TRACE_DEBUG);
	}
	public void ejbPassivate() throws RemoteException
	{
		ServerModuleConf.traceOut("inside ejbPassivate(): ",ServerModuleConf.TRACE_DEBUG);
	}
	public void ejbStore() throws RemoteException
	{
		ServerModuleConf.traceOut("inside "+className+"ejbStore(): isTimetoSave()=-"+itsTimeToSave() + " bDirty: "+bDirty,ServerModuleConf.TRACE_DEBUG);
		if (bDirty) {
			bDirty = false;
			throw new EJBException(BSConstants.EXCEPTION_RECORD_CONCURRENTLY_MODIFIED +", bDirty=true in "+className+".ejbStore");
		}
		try {
		
		 String is_quebecois;
		 if (rd.is_quebecois == true)
			is_quebecois = new String ("01");
		else
			is_quebecois = new String ("00");

			query = "update AC_TITLE_INFO set " +
"seq_no="+rd.seq_no+"," + 
	"commercial_status='"+rd.commercial_status+"'," + 
	"date_status_mo='"+rd.date_status_mo+"'," + 
	"publisher_code='"+rd.publisher_code+"'," + 
	"price_title="+NF.format(rd.price_title).toString() +" ," + 
	"date_price_mo='"+rd.date_price_mo+"'," + 
	"currency_code='"+rd.currency_code+"'," + 
	"document_type='"+rd.document_type+"'," + 
	"is_quebecois='"+is_quebecois+"'," +
	"date_created='"+rd.date_created+"'," + 
	"date_modified='"+rd.date_modified+"'," + 
	"user_code_cr='"+rd.user_code_cr+"'," + 
	"user_code_mo='"+rd.user_code_mo+"'" + " where " +
		"seq_no="+ rd.seq_no+ ""; 

//			if(Con==null || Con.isClosed())//We keep the Con opened by recDirty
/*		  Con = getConnection();
      Con.setAutoCommit(false);
		  stmt = Con.createStatement();
		  stmt.executeUpdate(query);*/

		} catch (Exception ex) {
						ServerModuleConf.traceOut("Could not update in "+className+".ejbStore()"+
							ServerModuleConf.getStackTrace(ex),
								ServerModuleConf.TRACE_DEBUG);
						throw new EJBException(ex.getMessage());
		} finally {
	try {
//		    cleanConnection(Con, stmt, null);

		}catch(Exception e) {}
	}
			ServerModuleConf.traceOut(className+".ejbStore(), done query1: " + query,ServerModuleConf.TRACE_DEBUG);
			query="";
	}
	public void ejbLoad() throws RemoteException{
		if( itsTimeToSave() ){// We are about to do a valid call to ejbStore, so we skip this ejbLoad()
			ServerModuleConf.traceOut("inside "+className+"ejbLoad(). We skip this load. ",ServerModuleConf.TRACE_DEBUG);
			return;
		}
	try {
			ServerModuleConf.traceOut("inside "+className+"ejbLoad(), calling Refresh(). ",ServerModuleConf.TRACE_DEBUG);
			 rd = refresh(((ordtitinfPK)ectx.getPrimaryKey()).seq_no);
		}catch(Exception e) {
			ServerModuleConf.traceOut("Exception in "+className+".ejbLoad(): pk = "+((ordtitinfPK)ectx.getPrimaryKey()).toString(),ServerModuleConf.TRACE_EXCEPTION);
			throw new RemoteException("ordtitinfBean.ejbLoad - can't refresh : " + e.getMessage());
		}
	}
	public void ejbRemove() throws EJBException{
		ServerModuleConf.traceOut("inside "+className+".ejbRemove(): ",ServerModuleConf.TRACE_DEBUG);
		try {
			stmt = null;
			Con = ServerModuleConf.cnMgr.getConnection(10000,true);
Con.setAutoCommit(false);

			query = "delete from AC_TITLE_INFO  " +
" where " +
		"seq_no="+ rd.seq_no+ ""; 

		stmt = Con.createStatement();
		stmt.executeUpdate(query);
		} catch (SQLException ex) {
			throw new EJBException(ex.getMessage());
		} finally {
	try {
			stmt.close();
			ServerModuleConf.cnMgr.putConnection(Con);
			Con = null;
		}catch(Exception e) {}
	}
	}
	/**
	* saveStatus managing section
	*/
	private boolean itsTimeToSave(){
		return ((saveStatus & ServerModuleConf.SAVE_STATUS_ITS_TIME_TO_SAVE) == ServerModuleConf.SAVE_STATUS_ITS_TIME_TO_SAVE);
	}
	private void setItsTimeToSave(boolean value){
		if(value==true)
	saveStatus |= ServerModuleConf.SAVE_STATUS_ITS_TIME_TO_SAVE;
	else
	if(itsTimeToSave())
		saveStatus ^= ServerModuleConf.SAVE_STATUS_ITS_TIME_TO_SAVE;//reset flag
	}
	private boolean weCreate(){
		return ( (saveStatus & ServerModuleConf.SAVE_STATUS_CREATE) == ServerModuleConf.SAVE_STATUS_CREATE);
	}
	private void setCreationMode(boolean value){
	if(value==true)
		saveStatus |= ServerModuleConf.SAVE_STATUS_CREATE;
	else
	if(weCreate())
		saveStatus ^= ServerModuleConf.SAVE_STATUS_CREATE;//reset flag
	}
	private boolean weDelete(){
		return ( (saveStatus & ServerModuleConf.SAVE_STATUS_DELETE) == ServerModuleConf.SAVE_STATUS_DELETE);
	}
	private void setDeletionMode(boolean value){
	if(value==true)
		saveStatus |= ServerModuleConf.SAVE_STATUS_DELETE;
	else
			if(weDelete())
				saveStatus ^= ServerModuleConf.SAVE_STATUS_DELETE;//reset flag
		}

   private Connection getConnection()
	{
	    try
	    {
		    Hashtable h1 = new Hashtable();
		    h1.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
		    h1.put(Context.PROVIDER_URL, "rmi://localhost:1099");
		    InitialContext context = new InitialContext(h1);

//        InitialContext context = new InitialContext();
System.out.println("in getConnection");
		    DataSource     ds      = (DataSource) context.lookup("java:comp/env/jdbc/bestSQL");
//		    DataSource     ds      = (DataSource) context.lookup("java:comp/env/jdbc/jonasDB");
System.out.println("in getConnection, after lookup");
		    return ds.getConnection();
		}
		catch (Exception ex)
		{
		    ex.printStackTrace();
		    throw new EJBException(ex);
		}
	}

	private void cleanConnection(Connection connection, Statement statement, ResultSet results)
	{
System.out.println("Closing resources ...");
	    try
	    {
	        if (results != null)
	            results.close();

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

	        if (connection != null)
	            connection.close();
	    }
	    catch (Exception ex)
	    {
	        ex.printStackTrace();
	        throw new EJBException(ex);
	    }
	}

}

