/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@objectweb.org
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.jtests.beans.transacted;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.FinderException;
import javax.ejb.ObjectNotFoundException;
import javax.ejb.RemoveException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

/**
 * Entity bean with bean managed persistence.
 * 
 */
public class SimpleEB extends SimpleEC implements EntityBean {

 
    // Database related information
    private DataSource dataSource = null;
    static final String tableName = "transactedSimpleEB";


    /*
     * ejbCreate(.....) method
     */
    public java.lang.String ejbCreate()
        throws javax.ejb.CreateException {
        
        super.ejbCreate();

        java.lang.String pk;
        // Initialize the pk with the primkey-field
        pk = this.accno;

        Connection conn = null;
        PreparedStatement pStmt = null;
        try {
            conn = getConnection();
            pStmt = conn.prepareStatement("insert into "+tableName+" (c_accno, c_customer, c_balance) values (?, ?, ?)");
            if ( this.accno == null ) {
                pStmt.setNull(1, Types.VARCHAR);
            } else {
                pStmt.setString(1, this.accno);
            }
            if ( this.customer == null ) {
                pStmt.setNull(2, Types.VARCHAR);
            } else {
                pStmt.setString(2, this.customer);
            }
            pStmt.setLong(3, this.balance);
            pStmt.executeUpdate();
        } catch (Exception e) {
            throw new CreateException(e.toString());
        } finally {
            if (pStmt != null) {
                try {
                    pStmt.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
        }

        return pk;

    }



    /*
     * ejbCreate(.....) method
     */
    public java.lang.String ejbCreate(int p1)
        throws javax.ejb.CreateException {


        // Container-managed fields must be set to the Java language default values
        this.accno = null;
        this.customer = null;
        this.balance = 0L;

        super.ejbCreate(p1);

        java.lang.String pk;
        // Initialize the pk with the primkey-field
        pk = this.accno;

        Connection conn = null;
        PreparedStatement pStmt = null;
        try {
            conn = getConnection();
            pStmt = conn.prepareStatement("insert into "+tableName+" (c_accno, c_customer, c_balance) values (?, ?, ?)");
            if ( this.accno == null ) {
                pStmt.setNull(1, Types.VARCHAR);
            } else {
                pStmt.setString(1, this.accno);
            }
            if ( this.customer == null ) {
                pStmt.setNull(2, Types.VARCHAR);
            } else {
                pStmt.setString(2, this.customer);
            }
            pStmt.setLong(3, this.balance);
            pStmt.executeUpdate();
        } catch (Exception e) {
            throw new CreateException(e.toString());
        } finally {
            if (pStmt != null) {
                try {
                    pStmt.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
        }

        return pk;

    }


    /*
     * ejbCreate(.....) method
     */
    public java.lang.String ejbCreateForMandatory(char p1)
        throws javax.ejb.CreateException {


        // Container-managed fields must be set to the Java language default values
        this.accno = null;
        this.customer = null;
        this.balance = 0L;

        super.ejbCreateForMandatory(p1);

        java.lang.String pk;
        // Initialize the pk with the primkey-field
        pk = this.accno;

        Connection conn = null;
        PreparedStatement pStmt = null;
        try {
            conn = getConnection();
            pStmt = conn.prepareStatement("insert into "+tableName+" (c_accno, c_customer, c_balance) values (?, ?, ?)");
            if ( this.accno == null ) {
                pStmt.setNull(1, Types.VARCHAR);
            } else {
                pStmt.setString(1, this.accno);
            }
            if ( this.customer == null ) {
                pStmt.setNull(2, Types.VARCHAR);
            } else {
                pStmt.setString(2, this.customer);
            }
            pStmt.setLong(3, this.balance);
            pStmt.executeUpdate();
        } catch (Exception e) {
            throw new CreateException(e.toString());
        } finally {
            if (pStmt != null) {
                try {
                    pStmt.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
        }

        return pk;

    }


    /*
     * ejbCreate(.....) method
     */
    public java.lang.String ejbCreateForNever(short p1)
        throws javax.ejb.CreateException {


        // Container-managed fields must be set to the Java language default values
        this.accno = null;
        this.customer = null;
        this.balance = 0L;

        super.ejbCreateForNever(p1);

        java.lang.String pk;
        // Initialize the pk with the primkey-field
        pk = this.accno;

        Connection conn = null;
        PreparedStatement pStmt = null;
        try {
            conn = getConnection();
            pStmt = conn.prepareStatement("insert into "+tableName+" (c_accno, c_customer, c_balance) values (?, ?, ?)");
            if ( this.accno == null ) {
                pStmt.setNull(1, Types.VARCHAR);
            } else {
                pStmt.setString(1, this.accno);
            }
            if ( this.customer == null ) {
                pStmt.setNull(2, Types.VARCHAR);
            } else {
                pStmt.setString(2, this.customer);
            }
            pStmt.setLong(3, this.balance);
            pStmt.executeUpdate();
        } catch (Exception e) {
            throw new CreateException(e.toString());
        } finally {
            if (pStmt != null) {
                try {
                    pStmt.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
        }

        return pk;

    }


    /*
     * ejbCreate(.....) method
     */
    public java.lang.String ejbCreateForRequired(long p1)
        throws javax.ejb.CreateException {


        // Container-managed fields must be set to the Java language default values
        this.accno = null;
        this.customer = null;
        this.balance = 0L;

        super.ejbCreateForRequired(p1);

        java.lang.String pk;
        // Initialize the pk with the primkey-field
        pk = this.accno;

        Connection conn = null;
        PreparedStatement pStmt = null;
        try {
            conn = getConnection();
            pStmt = conn.prepareStatement("insert into "+tableName+" (c_accno, c_customer, c_balance) values (?, ?, ?)");
            if ( this.accno == null ) {
                pStmt.setNull(1, Types.VARCHAR);
            } else {
                pStmt.setString(1, this.accno);
            }
            if ( this.customer == null ) {
                pStmt.setNull(2, Types.VARCHAR);
            } else {
                pStmt.setString(2, this.customer);
            }
            pStmt.setLong(3, this.balance);
            pStmt.executeUpdate();
        } catch (Exception e) {
            throw new CreateException(e.toString());
        } finally {
            if (pStmt != null) {
                try {
                    pStmt.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
        }

        return pk;

    }


    /*
     * ejbCreate(.....) method
     */
    public java.lang.String ejbCreateForRequiresNew(java.lang.String p1)
        throws javax.ejb.CreateException {


        // Container-managed fields must be set to the Java language default values
        this.accno = null;
        this.customer = null;
        this.balance = 0L;

        super.ejbCreateForRequiresNew(p1);

        java.lang.String pk;
        // Initialize the pk with the primkey-field
        pk = this.accno;

        Connection conn = null;
        PreparedStatement pStmt = null;
        try {
            conn = getConnection();
            pStmt = conn.prepareStatement("insert into "+tableName+" (c_accno, c_customer, c_balance) values (?, ?, ?)");
            if ( this.accno == null ) {
                pStmt.setNull(1, Types.VARCHAR);
            } else {
                pStmt.setString(1, this.accno);
            }
            if ( this.customer == null ) {
                pStmt.setNull(2, Types.VARCHAR);
            } else {
                pStmt.setString(2, this.customer);
            }
            pStmt.setLong(3, this.balance);
            pStmt.executeUpdate();
        } catch (Exception e) {
            throw new CreateException(e.toString());
        } finally {
            if (pStmt != null) {
                try {
                    pStmt.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
        }

        return pk;

    }


    /*
     * ejbCreate(.....) method
     */
    public java.lang.String ejbCreateForSupports(boolean p1)
        throws javax.ejb.CreateException {


        // Container-managed fields must be set to the Java language default values
        this.accno = null;
        this.customer = null;
        this.balance = 0L;

        super.ejbCreateForSupports(p1);

        java.lang.String pk;
        // Initialize the pk with the primkey-field
        pk = this.accno;

        Connection conn = null;
        PreparedStatement pStmt = null;
        try {
            conn = getConnection();
            pStmt = conn.prepareStatement("insert into "+tableName+" (c_accno, c_customer, c_balance) values (?, ?, ?)");
            if ( this.accno == null ) {
                pStmt.setNull(1, Types.VARCHAR);
            } else {
                pStmt.setString(1, this.accno);
            }
            if ( this.customer == null ) {
                pStmt.setNull(2, Types.VARCHAR);
            } else {
                pStmt.setString(2, this.customer);
            }
            pStmt.setLong(3, this.balance);
            pStmt.executeUpdate();
        } catch (Exception e) {
            throw new CreateException(e.toString());
        } finally {
            if (pStmt != null) {
                try {
                    pStmt.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
        }

        return pk;

    }


    /*
     * ejbFindByPrimaryKey(...) method
     */
    public java.lang.String ejbFindByPrimaryKey(java.lang.String pk)
        throws FinderException {

        Connection conn = null;
        PreparedStatement pStmt = null;
        try {
            conn = getConnection();
            pStmt = conn.prepareStatement("select c_accno from "+tableName+" where c_accno=?");
            pStmt.setString(1, pk);
            ResultSet rs = pStmt.executeQuery();
            if (rs.next() == false) {
                throw new ObjectNotFoundException("Object not found in database (ejbFindByPrimaryKey("+pk.toString()+"))");				  
            }
        } catch (ObjectNotFoundException oe) {
            throw oe;
        } catch (Exception e) {
            throw new FinderException("Failed to find bean from database in ejbFindByPrimaryKey");
        } finally {
            if (pStmt != null) {
                try {
                    pStmt.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
        }
        return pk;
    }


    /*
     * ejbFinder_mandatory(...) transaction attribute = notsupported
     */
    public java.lang.String ejbFinder_mandatory()
        throws FinderException {
 

        // We must be outside any transaction
        if (!isAssociated()) {
            throw new EJBException("ejbFinder_mandatory: should not be in a transaction");
        }

        return commonFind("Mandatory");
    }


    /*
     * ejbFinder_never(...) transaction attribute = never
     */
    public java.lang.String ejbFinder_never()
        throws FinderException {

        if (isAssociated()) {
            throw new EJBException("ejbFinder_never in a transaction");
        }

        return commonFind("Never");
    }


    /*
     * ejbFinder_notsupported(...) transaction attribute = notsupported
     */
    public java.lang.String ejbFinder_notsupported()
        throws FinderException {
        // We must be outside any transaction
        if (isAssociated()) {
            throw new EJBException("ejbFinder_notsupported: should not be in a transaction");
        }

        return commonFind("NotSupported");
    }


    /*
     * ejbFinder_required(...)
     */
    public java.lang.String ejbFinder_required()
        throws FinderException {
 
        // We must be outside any transaction
        if (!isAssociated()) {
            throw new EJBException("ejbFinder_notsupported: should not be in a transaction");
        }

        return commonFind("Required");

    }


    /*
     * ejbFinder_requiresnew transaction attribute = requiresnew
     */
    public java.lang.String ejbFinder_requiresnew()
        throws FinderException {
 
        // We must be in a transaction
        if (!isAssociated()) {
            throw new EJBException("ejbFinder_requiresnew not in a transaction");
        }

        return commonFind("RequiresNew");
    }


    /*
     * ejbFinder_supports(...) transaction attribute = supports
     */
    public java.lang.String ejbFinder_supports(boolean p1)
        throws FinderException {


        if (p1 == true) {
            if (!isAssociated()) {
                throw new EJBException("ejbFinder_supports: should be in a transaction");
            }
        } else {
            if (isAssociated()) {
                throw new EJBException("ejbFinder_supports: should not be in a transaction");
            }
        }
        return commonFind("Supports");
    }


    /*
     * ejbLoad() method
     */
    public void ejbLoad()
    {
        Connection conn = null;
        PreparedStatement pStmt = null;
        try {
            String pk = (String)entityContext.getPrimaryKey();
            conn = getConnection();
            pStmt = conn.prepareStatement("select c_accno, c_customer, c_balance from "+tableName+" where c_accno=?");
            pStmt.setString(1, pk);
            ResultSet rs = pStmt.executeQuery();
            if (rs.next() == false) {
                throw new EJBException("Failed to load bean from database pk= "+pk.toString());
            }
            this.accno = rs.getString(1);
            this.customer = rs.getString(2);
            this.balance = rs.getLong(3);
        } catch (Exception e) {
            throw new EJBException(e);
        } finally {
            if (pStmt != null) {
                try {
                    pStmt.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
        }
        super.ejbLoad();
    }


    /*
     * ejbStore() method
     */
    public void ejbStore()
    {
        super.ejbStore();
        Connection conn = null;
        PreparedStatement pStmt = null;
        try {
            String pk = (String)entityContext.getPrimaryKey();;
            conn = getConnection();
            pStmt = conn.prepareStatement("update "+tableName+" set c_customer=?, c_balance=? where c_accno=?");
            if ( this.customer == null ) {
                pStmt.setNull(1, Types.VARCHAR);
            } else {
                pStmt.setString(1, this.customer);
            }
            pStmt.setLong(2, this.balance);
            pStmt.setString(3, pk);
            pStmt.executeUpdate();
        } catch (Exception e) {
            throw new EJBException(e);
        } finally {
            if (pStmt != null) {
                try {
                    pStmt.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
        }
    }


    /*
     * ejbRemove() method
     */
    public void ejbRemove()
        throws javax.ejb.RemoveException {

        super.ejbRemove();
        Connection conn = null;
        PreparedStatement pStmt = null;
        try {
            String pk = (String)entityContext.getPrimaryKey();; 
            conn = getConnection();
            pStmt = conn.prepareStatement("delete from "+tableName+" where c_accno=?");
            pStmt.setString(1, pk);
            pStmt.executeUpdate();
        } catch (Exception e) {
            throw new RemoveException(e.toString());
        } finally {
            if (pStmt != null) {
                try {
                    pStmt.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
        }
    }



    public void setEntityContext(EntityContext ctx) {
        this.entityContext = ctx;
    }

    public void unsetEntityContext() {
        this.entityContext = null;
    }


    /*
     * commonFind is the common part of the ejbFinder_XX methods
     *
     */

    private java.lang.String commonFind(String  p1) throws FinderException {
        java.lang.String pk;
        Connection conn = null;
        PreparedStatement pStmt = null;
        try {
            conn = getConnection();
            pStmt = conn.prepareStatement("select c_accno from "+tableName+" where c_customer = "+"'"+p1+"'");
            ResultSet rs = pStmt.executeQuery();
            if (rs.next() == false) { 
                throw new ObjectNotFoundException("Object not found in database ");
            }
            pk = rs.getString(1);
        } catch (ObjectNotFoundException oe) {
            throw oe;
        } catch (Exception e) {
            throw new FinderException(e.toString());
        } finally {
            if (pStmt != null) {
                try {
                    pStmt.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception ignore) {
                    // just ignore
                }
            }
        }
        return pk;
    }


    private Connection getConnection() throws java.sql.SQLException {
        if (dataSource == null) {
            // Finds DataSource from JNDI
            Context    initialContext = null;
            try {
                initialContext = new InitialContext();
                dataSource = (DataSource)initialContext.lookup("java:comp/env/jdbc/BMP");
            } catch (Exception e) {
                throw new javax.ejb.EJBException("Pb with naming context "+e);
            }
        }
        Connection ret = dataSource.getConnection();
        if (ret == null) {
            throw new javax.ejb.EJBException("dataSource.getConnection() returned null");
        }
        return ret;
    }

}
