/*
 *
 * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * This software is the proprietary information of Sun Microsystems, Inc.  
 * Use is subject to license terms.
 * 
 */


package ejb.grids;

import java.sql.*;
import javax.sql.*;
import java.util.*;
import javax.ejb.*;
import javax.naming.*;
import javax.rmi.*;
import java.rmi.*;
import utils.*;
import ejb.dataAccess.*;
import helpers.*;



public class GridsEJB implements EntityBean {


    

    private EntityContext context;
    private Data dataAccess;

    private String dbName = ServerConstants.gridsDB;
    private String schema = ServerConstants.serverGridSchema;
    private String serverGrigClass = ServerConstants.serverGridClass;

    private String dataAccessSessionBean = ServerConstants.dataAccessBean;
    private String dataTable = ServerConstants.gridsTableName;

    private String ipFileName;
    private String ip;
    private String fileName;
    private Timestamp creatDate;
    private ServerGrid grid;




    public String ejbCreate(String ipFileName,String ip,String fileName,Timestamp creatDate,
                                ServerGrid grid)
                            throws CreateException {


        if(ServerConstants.debug) {
            System.out.println("GridsEJB.ejbCreate()");
        }//if(ServerConstants.debug)


        try {

            insertRow(ipFileName,ip,fileName,creatDate,grid);

        } //try

        catch (Exception ex) {

           throw new EJBException("ejbCreate: " + 
              ex.getMessage());

        } //catch (Exception ex)

        this.ipFileName = ipFileName;
        this.ip = ip;
        this.fileName = fileName;
        this.grid = grid;
        this.creatDate = creatDate;


        if(ServerConstants.debug) {
            System.out.println("GridsEJB.ejbCreate(), dataTable : " + dataTable);
        }//if(ServerConstants.debug)


        return ipFileName;


    } //public String ejbCreate(String ipFileName,String ip,String fileName,Timestamp creatDate,ServerGrid grid)





    public String ejbFindByPrimaryKey(String ipFile) 
        throws FinderException {

        boolean result;
        //dataTable = dataTableName;

        if(ServerConstants.debug) {
            System.out.println("GridsEJB.ejbFindByPrimaryKey()");
        }//if(ServerConstants.debug)


        try {
            result = selectByPrimaryKey(ipFile);
        } catch (Exception ex) {
            throw new EJBException("GridsEJB.ejbFindByPrimaryKey(): " + 
                ex.getMessage());
        }
        if (result) {
            return ipFile;
        }
        else {
            throw new ObjectNotFoundException
                ("GridsEJB.ejbFindByPrimaryKey(): Row for ipFileName " + ipFile + " not found.");
        }

    } //public String ejbFindByPrimaryKey(String ipFile)






    public Collection ejbFindByIp(String ip) 
        throws FinderException {

        Collection result;
        //dataTable = dataTableName;


        if(ServerConstants.debug) {
            System.out.println("GridsEJB.ejbFindByIp()");
        }//if(ServerConstants.debug)


        try {
            result = selectByIp(ip);
        } catch (Exception ex) {
            throw new EJBException("GridsEJB.ejbFindByIp(): " + 
                ex.getMessage());
        }
        if (result.isEmpty()) {
            throw new ObjectNotFoundException
                ("GridsEJB.ejbFindByIp(): Row for ip " + ip + " not found.");
        }
        else {
            return result;
        }

    } //public Collection ejbFindByIp(String ip)








    public Collection ejbFindAll()
        throws FinderException {

        Collection result;
        //dataTable = dataTableName;

        if(ServerConstants.debug) {
            System.out.println("GridsEJB.ejbFinAll()");
        }//if(ServerConstants.debug)

        try {
            result = selectAll();
            
        } catch (Exception ex) {
            throw new EJBException("GridsEJB.ejbFindAll() : " + 
                ex.getMessage());
        }
        if (result.isEmpty()) {
            throw new ObjectNotFoundException("GridsEJB.ejbFindAll() : No rows found.");
        }
        else {
            return result;
        }
    }




    public Collection ejbFindInRange(Timestamp startDate,Timestamp endDate)
        throws FinderException {

        Collection result;
        //dataTable = dataTableName;

        if(ServerConstants.debug) {
            System.out.println("GridsEJB.ejbFindInRange()");
        }//if(ServerConstants.debug)

        try {
            result = selectInRange(startDate, endDate);
            
        } catch (Exception ex) {
            throw new EJBException("GridsEJB.ejbFindInRange() : " + 
                ex.getMessage());
        }
        if (result.isEmpty()) {
            throw new ObjectNotFoundException("GridsEJB.ejbFindInRange() : No rows found.");
        }
        else {
            return result;
        }

    } //public Collection ejbFindInRange(String startDate,String endDate)









    public void ejbRemove() {


        if(ServerConstants.debug) {
            System.out.println("GridsEJB.ejbRemove()");
        }//if(ServerConstants.debug)

        try {
            deleteRow(ipFileName);
        } catch (Exception ex) {
            throw new EJBException("GridsEJB.ejbRemove() : " + 
                ex.getMessage());
        }
    } 






    public void setEntityContext(EntityContext context) {

        this.context = context;

        if(ServerConstants.debug) {
            System.out.println("GridsEJB.setEntityContext()");
        }//if(ServerConstants.debug)

        try {

            Context initial = new InitialContext();
            Object objref = initial.lookup(dataAccessSessionBean);

            DataHome home = 
                (DataHome)PortableRemoteObject.narrow(objref, 
                                            DataHome.class);

            dataAccess = home.create(dbName);

            Context environment = (Context)initial.lookup("java:comp/env");
            String schemaName = (String)environment.lookup(schema);
            String serverGrigClassName = (String)environment.lookup(serverGrigClass);

            System.out.println("GridsEJB.setEntityContext(), schemaName : " + schemaName);
            System.out.println("GridsEJB.setEntityContext(), serverGrigClassName : " + serverGrigClassName);

            //dataAccess.setTypeMap(schemaName,serverGrigClassName);

        } //try

        catch(NamingException e) {

            System.out.println("GridsEJB.setEntityContext(), NamingException : " + e.toString());
            e.printStackTrace();
            System.exit(0);

        } //catch(NamingException e)


        catch(RemoteException re) {

            System.out.println("GridsEJB.setEntityContext(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)


        catch(CreateException re) {

            System.out.println("GridsEJB.setEntityContext(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)



   }//public void setEntityContext(EntityContext context)






    public void unsetEntityContext() {

        if(ServerConstants.debug) {
            System.out.println("GridsEJB.unsetEntityContext()");
        }//if(ServerConstants.debug)

        dataAccess = null;

    } //public void unsetEntityContext()





    public void ejbActivate() {

        if(ServerConstants.debug) {
            System.out.println("GridsEJB.ejbActivate()");
        }//if(ServerConstants.debug)

        ipFileName = (String)context.getPrimaryKey();

    }//public void ejbActivate()






    public void ejbPassivate() {

        if(ServerConstants.debug) {
            System.out.println("GridsEJB.passivate()");
        }//if(ServerConstants.debug)

        ipFileName = null;

    }//public void ejbPassivate()






    public void ejbLoad() {


        if(ServerConstants.debug) {
            System.out.println("GridsEJB.ejbLoad()");
        }//if(ServerConstants.debug)

        try {
            loadRow();
        } //try

        catch (Exception ex) {
           throw new EJBException("Grids.ejbLoad(): " + 
              ex.getMessage());
        } //catch (Exception ex)
    }
   






    public void ejbStore() {

        if(ServerConstants.debug) {
            System.out.println("GridsEJB.ejbStore()");
        }//if(ServerConstants.debug)

        try {
           storeRow();
        }//try

        catch (Exception ex) {
            throw new EJBException("Grids.ejbStore() : " + 
                ex.getMessage());
        }//catch (Exception ex)

    }//public void ejbStore()






    public void ejbPostCreate(String ipFileName,String ip,String fileName,
                                Timestamp creatDate,ServerGrid grid) { }



/*********************** Business Methods *************************/


    public String getIpFileName() {

        if(ServerConstants.debug) {
            System.out.println("GridsEJB.getIpFileName()");
        }//if(ServerConstants.debug)

        return ipFileName;

    } //public String getIpFileName()


    public String getIp() {

        return ip;

    } //public String getIp()


    public String getFileName() {

        return fileName;

    } //public String getFileName()



    public Timestamp getCreatDate() {

        return creatDate;

    } //public Timestamp getCreatDate()




    public ServerGrid getGrid() {

        return grid;

    } //public ServerGrid getGrid()




    public void setIpFileName(String ipFile) {

        ipFileName = ipFile;

    } //public void setIpFileName(String ipFile)



    public void setCreatDate(Timestamp t) {

        creatDate = t;

    } //public void setCreatDate(Timestamp t)




    public void setGrid(ServerGrid g) {

        grid = g;

    } //public void setGrid(ServerGrid g)





/*********************** Database Routines *************************/


    private void insertRow (String ipFileName,String ip,String fileName,
                            Timestamp creatDate,ServerGrid grid)
                            throws SQLException {


        if(ServerConstants.debug) {
            System.out.println("GridsEJB.insertRow()");
            System.out.println("grid.toString() : " + grid.toString());
        }//if(ServerConstants.debug)



        String sql = "insert into " + dataTable + 
                    " (ipFileName,ip,fileName,creatDate,grid) values " + 
                    "(" +
                    "'" + ipFileName + "'" + "," +
                    "'" + ip + "'" + "," +
                    "'" + fileName + "'" + "," +
                    "'" + creatDate.toString() + "'" + "," +
                    "?" + ")";


        if(ServerConstants.debug) {
            System.out.println("sql : " + sql);
        }//if(ServerConstants.debug)


        try {

            dataAccess.insert(sql,dbName,grid);

        } //try

        catch(RemoteException re) {

            System.out.println("GridsEJB.insertRow(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)


   } //private void insertRow (....)





    private void deleteRow(String ipFileName) throws SQLException {


        if(ServerConstants.debug) {
            System.out.println("GridsEJB.deleteRow()");
        }//if(ServerConstants.debug)


        String deleteStatement = "delete from " + dataTable + " where ipFileName='" +
                                    ipFileName + "'";

        try {
            dataAccess.delete(deleteStatement,dbName);
        }

        catch(RemoteException re) {

            System.out.println("GridsEJB.deleteRow(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)




    } //private void deleteRow(String ipFileName) throws SQLException




    private boolean selectByPrimaryKey(String ipFileName) 
                                        throws SQLException {

        boolean result = false;

        if(ServerConstants.debug) {
            System.out.println("GridsEJB.selectByPrimaryKey()");
        }//if(ServerConstants.debug)


        String selectStatement = "select ipFileName from " + dataTable + 
                                 " where ipFileName='" + ipFileName + "'";

        try {
            DataSet ds = dataAccess.select(selectStatement,dbName);

            Vector rows = ds.getRowsOfDataVector();

            if(rows.size() > 0)
                result = true;

            return result;


        } //try

        catch(RemoteException re) {

            System.out.println("GridsEJB.selectByPrimaryKey(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)

        return result;

    } //private boolean selectByPrimaryKey(String ipFileName)








    private Collection selectAll() throws SQLException {


        if(ServerConstants.debug) {
            System.out.println("GridsEJB.selectAll()");
        }//if(ServerConstants.debug)

        String selectStatement = "select * from " + dataTable;

        if(ServerConstants.debug) {
            System.out.println("selectStatement : " + selectStatement);
        }//if(ServerConstants.debug)

        DataSet ds = null;

        try {
            ds = dataAccess.select(selectStatement,dbName);
        }

        catch(RemoteException re) {

            System.out.println("GridsEJB.selectInRange(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)




        ArrayList a = new ArrayList();

        Vector rows = ds.getRowsOfDataVector();

        for(int i=0;i<rows.size();i++) {

            Vector oneRow = (Vector)rows.elementAt(i);
            String ipFile = (String)oneRow.elementAt(0);
            a.add(ipFile);

        } //for(int i=0;i<rows.size();i++)

        return a;


   } //private Collection selectAll()













    private Collection selectByIp(String ip) throws SQLException {


        if(ServerConstants.debug) {
            System.out.println("GridsEJB.selectByIp()");
        }//if(ServerConstants.debug)

        String selectStatement = "select ipFileName from " + dataTable + " where " +
                                "ip='" + ip + "'";

        DataSet ds = null;

        try {
            ds = dataAccess.select(selectStatement,dbName);
        }

        catch(RemoteException re) {

            System.out.println("GridsEJB.selectByIp(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)




        ArrayList a = new ArrayList();

        Vector rows = ds.getRowsOfDataVector();

        for(int i=0;i<rows.size();i++) {

            Vector oneRow = (Vector)rows.elementAt(i);
            String ipFile = (String)oneRow.elementAt(0);
            a.add(ipFile);

        } //for(int i=0;i<rows.size();i++)

        return a;



   } //private Collection selectByIp(String ip)






    private Collection selectInRange(Timestamp start,Timestamp end) throws SQLException {


        if(ServerConstants.debug) {
            System.out.println("GridsEJB.selectInRange()");
        }//if(ServerConstants.debug)

        String selectStatement = "select ipFileName from " + dataTable + " where " +
                                "creatDate>=" + start + " and creatDate<=" + end + "";

        DataSet ds = null;

        try {
            ds = dataAccess.select(selectStatement,dbName);
        }

        catch(RemoteException re) {

            System.out.println("GridsEJB.selectInRange(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)




        ArrayList a = new ArrayList();

        Vector rows = ds.getRowsOfDataVector();

        for(int i=0;i<rows.size();i++) {

            Vector oneRow = (Vector)rows.elementAt(i);
            String ipFile = (String)oneRow.elementAt(0);
            a.add(ipFile);

        } //for(int i=0;i<rows.size();i++)

        return a;



   } //private Collection selectInRange(Timestamp start,Timestamp end)











    private void loadRow() throws SQLException {


        if(ServerConstants.debug) {
            System.out.println("GridsEJB.loadRow()");
        }//if(ServerConstants.debug)

        String selectStatement = "select ipFileName,ip,fileName,creatDate,grid from " +
                                 dataTable + " where " +
                                 "ipFileName='" + ipFileName + "'";

        DataSet ds = null;

        try {
            ds = dataAccess.select(selectStatement,dbName);
        }

        catch(RemoteException re) {

            System.out.println("GridsEJB.loadRow(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)



        Vector rows = ds.getRowsOfDataVector();

        if(rows.size() > 0) {

            Vector oneRow = (Vector)rows.elementAt(0);

            this.ipFileName = (String)oneRow.elementAt(0);
            this.ip = (String)oneRow.elementAt(1);
            this.fileName = (String)oneRow.elementAt(2);
            this.creatDate = (Timestamp)oneRow.elementAt(3);
            this.grid = (ServerGrid)oneRow.elementAt(4);

        } //if(rows.size() > 0)

        else {

            throw new NoSuchEntityException("GridsEJB.loadRow(), Row for ipFileName " + ipFileName +
                    " not found in database.");


        } //else



    } //private void loadRow() throws SQLException








    private void storeRow() throws SQLException {


        if(ServerConstants.debug) {
            System.out.println("GridsEJB.storeRow()");
        }//if(ServerConstants.debug)




        try {
            deleteRow(ipFileName);
        } catch (Exception ex) {
            throw new EJBException("GridsEJB.storeRow() : " + 
                ex.getMessage());
        }



        try {

            insertRow(ipFileName,ip,fileName,creatDate,grid);

        } //try

        catch (Exception ex) {

           throw new EJBException("GridsEJB.storeRow(): " + 
              ex.getMessage());

        } //catch (Exception ex)


/*** The following update code is replaced by delete-insert code above because of problems with ***/
/*** PreparedStatement.setObject() with executeUpdate method ***/
/****
        String updateStatement = "update " + dataTable + " set " +
                            "ipFileName='" + ipFileName + "'," +
                            "ip='" + ip + "'," +
                            "fileName='" + fileName + "'," +
                            "creatDate='" + creatDate.toString() + "'," +
                            "grid='" + "?" + "'" +
                            " where ipFileName='" + ipFileName + "'";



        try {
            int rowCount = dataAccess.update(updateStatement,dbName,grid);

            if (rowCount == 0) {

                throw new EJBException("Storing row for ipFileName " + ipFileName + " failed.");

            } //if (rowCount == 0)

        } //try


        catch(RemoteException re) {

            System.out.println("GridsEJB.storeRow(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)

****/


    }//private void storeRow() throws SQLException 


} // TidalStationsEJB

