/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 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
 *
 * Initial developer(s): ____________________________________.
 * Contributor(s): ______________________________________.
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

// EnvBean.java
// Stateless Session bean

package sampleappli;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.File;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.RemoveException;
import javax.ejb.EJBObject;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * EnvBean is a stateless session bean use to create and clean a correct
 * environement for the running of the StockClient it creates/remove the
 * StockTable and the order file
 * @author JOnAS team
 */
public class EnvBean implements SessionBean {

    SessionContext ejbContext;

    DataSource dataSource = null;

    Connection conn = null;

    Statement stmt;

    String stocktablename = null;

    String orderfilename = null;

    // ------------------------------------------------------------------
    // SessionBean implementation
    // ------------------------------------------------------------------

    /**
     * Set the associated session context. The container calls this method after
     * the instance creation. The enterprise Bean instance should store the
     * reference to the context object in an instance variable. This method is
     * called with no transaction context.
     * @param sessionContext A SessionContext interface for the instance.
     * @throws EJBException Thrown by the method to indicate a failure caused by
     *         a system-level error.
     */
    public void setSessionContext(SessionContext ctx) {
        ejbContext = ctx;
        if (dataSource == null) {
            // Finds DataSource from JNDI
            Context initialContext = null;
            try {
                initialContext = new InitialContext();
                dataSource = (DataSource) initialContext.lookup("java:comp/env/jdbc/myDS");
            } catch (Exception e) {
                System.err.println("    new InitialContext() : " + e);
                throw new EJBException("Cannot get JNDI InitialContext");
            }
            // Find the stocktablename
            try {
                stocktablename = (String) initialContext.lookup("java:comp/env/stocktablename");
            } catch (Exception e) {
                System.err.println("cannot lookup environment " + e);
                throw new EJBException("cannot lookup environment");
            }
            // Find the orderfilename
            try {
                orderfilename = (String) initialContext.lookup("java:comp/env/orderfilename");
            } catch (Exception e) {
                System.err.println("cannot lookup environment " + e);
                throw new EJBException("cannot lookup environment");
            }
        }
    }

    /**
     * A container invokes this method before it ends the life of the session
     * object. This happens as a result of a client's invoking a remove
     * operation, or when a container decides to terminate the session object
     * after a timeout. This method is called with no transaction context.
     * @throws EJBException Thrown by the method to indicate a failure caused by
     *         a system-level error.
     */
    public void ejbRemove() {
    }

    /**
     * The Session bean must define 1 or more ejbCreate methods.
     * @throws CreateException Failure to create a session EJB object.
     */
    public void ejbCreate() throws CreateException {
    }

    /**
     * A container invokes this method on an instance before the instance
     * becomes disassociated with a specific EJB object.
     */
    public void ejbPassivate() {
    }

    /**
     * A container invokes this method when the instance is taken out of the
     * pool of available instances to become associated with a specific EJB
     * object.
     */
    public void ejbActivate() {
    }

    // ------------------------------------------------------------------
    // Env implementation
    // ------------------------------------------------------------------

    /**
     * init
     */
    public void init() {
        createTableStock();
        createOrderFile();
    }

    /**
     * clean
     */
    public void clean() {
        dropTableStock();
        removeOrderFile();
    }

    // ------------------------------------------------------------------
    // Env internal methods
    // ------------------------------------------------------------------
    public void dropTableStock() {
        // drop table
        try {
            conn = dataSource.getConnection();
            stmt = conn.createStatement();
            stmt.execute("DROP TABLE " + stocktablename);
            stmt.close();
            conn.close();
        } catch (Exception e) {
            System.err.println("Exception in dropTable : \n" + stocktablename + " " + e);
        }
    }

    public void createTableStock() {
        // get connection
        try {
            conn = dataSource.getConnection();

        } catch (Exception e) {
            System.err.println("Cannot get Connection: \n" + e);
            throw new EJBException("Cannot get Connection");
        }
        try {
            stmt = conn.createStatement();
            stmt.execute("DROP TABLE " + stocktablename);
            stmt.close();
        } catch (Exception e) {
        }
        // create table
        try {
            stmt = conn.createStatement();
            stmt.execute("create table " + stocktablename + "(ID varchar(5) not null primary key, QUANTITY integer)");
            stmt.execute("insert into " + stocktablename + " values ('00000', 10)");
            stmt.execute("insert into " + stocktablename + " values ('00001', 20)");
            stmt.execute("insert into " + stocktablename + " values ('00002', 10)");
            stmt.execute("insert into " + stocktablename + " values ('00003', 20)");
            stmt.execute("insert into " + stocktablename + " values ('00004', 10)");
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            System.err.println("Exception in createTable : " + e);
            throw new EJBException("Exception in createTable");
        }
    }

    public void createOrderFile() {
        try {
            File f = new File(System.getProperty("java.io.tmpdir") + File.separator + System.getProperty("user.name")
                    + "_" + orderfilename);
            if (!f.createNewFile()) {
                f.delete();
                f.createNewFile();
            }
        } catch (Exception ex) {
            System.err.println("Exception on createOrderFile: " + ex);
            throw new EJBException("Exception in createOrderFile");
        }

    }

    public void removeOrderFile() {
        try {
            File f = new File(System.getProperty("java.io.tmpdir") + File.separator + System.getProperty("user.name")
                    + "_" + orderfilename);
            f.delete();
        } catch (Exception ex) {
            System.err.println("Exception on removeOrderFile: " + ex);
            throw new EJBException("Exception in removeOrderFile");
        }
    }
}