// InitDBSL.java
// Stateless Session bean

package org.objectweb.jonas.stests.manyops;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.objectweb.jonas.common.Log;
import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;


/**
 *
 */
public class InitDBSL implements SessionBean {

    static private Logger logger = null;
    SessionContext ejbContext;

    // ------------------------------------------------------------------
    // 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) {
        if( logger == null)
                logger = Log.getLogger("org.objectweb.jonas_tests");
	logger.log(BasicLevel.DEBUG, "");
	ejbContext = ctx;
    }
	
    /**
     * 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() {
	logger.log(BasicLevel.DEBUG, "");
    }
	
    /**
     * The Session bean must define 1 or more ejbCreate methods.
     *
     * @throws CreateException Failure to create a session EJB object.
     */
    public void ejbCreate() throws CreateException {
	logger.log(BasicLevel.DEBUG, "");
    }


    /**
     * A container invokes this method on an instance before the instance
     * becomes disassociated with a specific EJB object.
     */
    public void ejbPassivate() {
	logger.log(BasicLevel.DEBUG, "");
    }

    /**
     * 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() {
	logger.log(BasicLevel.DEBUG, "");
    }
    
    // ------------------------------------------------------------------
    // InitDB implementation
    // ------------------------------------------------------------------

    /**
     * createTable
     */
    public void createTable() {
	logger.log(BasicLevel.DEBUG, "");
	initDB("stestsmanyops");
    }

    void initDB(String tableName) {
	logger.log(BasicLevel.DEBUG, "");

	// Get my DataSource from JNDI
	DataSource ds = null;
	InitialContext ictx = null;
	try {
	    ictx = new InitialContext(); 
	} catch (Exception e) {
	    logger.log(BasicLevel.ERROR, "new InitialContext() : " + e);
	    throw new EJBException("Cannot get JNDI InitialContext");
	}
	try {
	    ds = (DataSource) ictx.lookup("java:comp/env/jdbc/mydb");
	} catch (Exception e) {
	    logger.log(BasicLevel.ERROR, "cannot lookup datasource " + e);
	    throw new EJBException("cannot lookup datasource");
	}

	// Drop table
	Connection conn = null;
	Statement stmt = null;
	try {
	    conn = ds.getConnection();
	    stmt = conn.createStatement();
	    stmt.execute("drop table " + tableName);
	    stmt.close();
	} catch(SQLException e) {
	    // The first time, table will not exist.
	    logger.log(BasicLevel.INFO, "Exception in dropTable : "+e);
	}

	// Create table.
	try {
	    stmt = conn.createStatement();
	    stmt.execute("create table " + tableName + "(name varchar(30) not null primary key, number integer, price integer)");
	    stmt.close();
	    conn.close();
	} catch(SQLException e) {
	    logger.log(BasicLevel.ERROR, "Exception in createTable : "+e);
	    throw new EJBException("Exception in createTable");
	}
    }

}
