// runtimeCASLR.java
// Stateless Session bean

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

import javax.ejb.CreateException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.InitialContext;
import javax.resource.spi.ConnectionEvent;

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

import fictional.resourceadapter.CommonClient;
import fictional.resourceadapter.ConnectionImpl;
import fictional.resourceadapter.JtestResourceAdapter;


/*
 */
public class runtimeCASLR implements SessionBean {

    static private Logger logger = null;
    SessionContext ejbContext;
    private JtestResourceAdapter mcf = null; //Managed Connection Factory
    private CommonClient cccf = null;   //Common Client Connection Factory
    private ConnectionImpl conn = null;
    private CommonClient csp = null;    //ConnectionSpec
    InitialContext ic=null;
    private String res_auth = "";
    String cName = "runtimeCASLR";

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


    public void setSessionContext(SessionContext ctx) {
        if (logger == null) {
            logger = Log.getLogger("org.objectweb.jonas.jtests.j2eeca");
        }
        logger.log(BasicLevel.DEBUG, "");
        ejbContext = ctx;
    }
        

    public void ejbRemove() {
        logger.log(BasicLevel.DEBUG, "");
    }
        

    public void ejbCreate() throws CreateException {
        logger.log(BasicLevel.DEBUG, "");
    }

    public void ejbPassivate() {
        logger.log(BasicLevel.DEBUG, "");
    }

    public void ejbActivate() {
        logger.log(BasicLevel.DEBUG, "");
    }
    
    // ------------------------------------------------------------------
    // runtime implementation
    // ------------------------------------------------------------------
    public void setResAuth(String ra) {
        res_auth=ra;  // set to Application or Container
    }

    /**
     * method1
     */
    public void method1(String rar_jndi_name, String testName) 
            throws Exception
    {
        logger.log(BasicLevel.DEBUG, "============================ "+testName);
        logger.log(BasicLevel.DEBUG, cName+".method1 : lookup "+rar_jndi_name);
        try {
            ic = new InitialContext();
        } catch (Exception e1) {
            logger.log(BasicLevel.DEBUG, cName+".method1 error: InitialContext failed");
            throw e1;
        }
        try {
            cccf = (CommonClient)ic.lookup(rar_jndi_name);
            logger.log(BasicLevel.DEBUG, cName+".method1 : found "+rar_jndi_name);
        } catch (Exception e2) {
            logger.log(BasicLevel.DEBUG, cName+".method1 error: lookup failed for "+rar_jndi_name);
            throw e2;
        }

        //
        // Component-managed sign-on when file "runtime.xml" contains line below
        //
        //  <res-auth>Application</res-auth>
        //
        try {
            csp = new CommonClient(); // get a new ConnectionSpec
            csp.setUserName("Fictional_User_Name");
            csp.setPassword("__Jtest_Pass_word__");
            logger.log(BasicLevel.DEBUG, cName
                  +".method1 : ConnectionSpec + Fictional_User_Name,__Jtest_Pass_word__");
        } catch (Exception e3) {
            logger.log(BasicLevel.DEBUG, cName+".method1 : new connection spec failed");
            throw e3;
        }
        try {
            conn = (ConnectionImpl)cccf.getConnection();
            if (conn==null) {
                logger.log(BasicLevel.DEBUG, cName+".method1 error: getConnection returned null connection.");
                throw new Exception("");
            }
        } catch (Exception e4) {
            logger.log(BasicLevel.DEBUG, cName+".method1 error: getConnection failed "
                    +e4.toString());
            throw e4;
        }
    }

    /**
     * closeUp
     */
    public void closeUp(int w) {
        try {
            if (w>0) {
                // The CONNECTION_ERROR_OCCURRED indicates that the associated 
                // ManagedConnection instance is now invalid and unusable.
                conn.close(ConnectionEvent.CONNECTION_ERROR_OCCURRED);
                logger.log(BasicLevel.DEBUG, cName+".closeUp : closed physical connection");
            } else {
                // The CONNECTION_CLOSED indicates that connection handle
                // is closed, but physical connection still exists
                conn.close();
                logger.log(BasicLevel.DEBUG, cName+".closeUp : closed connection");
            }
        } catch (Exception e) {
            logger.log(BasicLevel.DEBUG, cName+".closeUp error: close handle/physical connection failed");
        }
    }
    /**
     * JUnit tests
     */
    public int getMCF_Pwriter()
    {
        int here=2;
        JtestResourceAdapter mcf = (JtestResourceAdapter) cccf.getMcf();  // ManagedConnectionFactory    
        try {
            if (mcf.getLogWriter()==null) {              // PrintWriter not null
                logger.log(BasicLevel.DEBUG, cName+".getMCF_Pwriter No PrintWriter registered");
                here=0;
            }
            else {
                logger.log(BasicLevel.DEBUG, cName+".getMCF_Pwriter PrintWriter is o.k.");
                here=1;
            }
        } catch (Exception e) {
            logger.log(BasicLevel.DEBUG, cName+
                ".getMCF_Pwriter error: "+e.toString());
        }
        return here;
    }
    public int getMC_Pwriter()
    {
        int here=2;
        ConnectionImpl conni = (ConnectionImpl)conn;
        try {
            JtestResourceAdapter mc = (JtestResourceAdapter)conni.getMC(); //get ManagedConnection        
            if (mc.getLogWriter()==null) {              // PrintWriter not null
                logger.log(BasicLevel.DEBUG, cName+
                    ".getMC_Pwriter No PrintWriter registered in ManagedConnection");
                here=0;
            }
            else {
                logger.log(BasicLevel.DEBUG, cName+
                    ".getMC_Pwriter PrintWriter in ManagedConnection is o.k.");
                here=1;
            }
        } catch (Exception e) {
            logger.log(BasicLevel.DEBUG, cName+
                ".getMC_Pwriter error: "+e.toString());
        }
        return here;
    }
    public String getResAuth() {
        mcf = (JtestResourceAdapter) cccf.getMcf(); // get ManagedConnectionFactory    
        try {
            //JtestResourceAdapter mc = (JtestResourceAdapter)conni.getMC(); //get ManagedConnection        
            String ra = mcf.getRes_Auth();              // get real "Application" or "Container"
            logger.log(BasicLevel.DEBUG, cName+".getResAuth "
                       +"<res-auth>"+ra+"</res-auth>");
            return ra;
        } catch (Exception e) {
            logger.log(BasicLevel.DEBUG, cName
                   +".getResAuth error: failed to find <res-auth> "
                   +"in ManagedConnectionFactory");
            return "";
        }
    }
    public String getSecurityPassword() {
        mcf = (JtestResourceAdapter) cccf.getMcf(); // get ManagedConnectionFactory    
        //ConnectionImpl conni = (ConnectionImpl)conn;
        try {
            //JtestResourceAdapter mc = (JtestResourceAdapter)conni.getMC(); //get ManagedConnection        
            String pw = mcf.getPassword();
            logger.log(BasicLevel.DEBUG, cName+".getSecurityPassword ("
                          +mcf.getRes_Auth()+")password="+pw);
            return pw;
        } catch (Exception e) {
            String pw = mcf.getPassword();    // find default
            logger.log(BasicLevel.DEBUG, cName
                   +".getSecurityPassword error: failed to find ManagedConnectionFactory "
                   +"instance containing password. Using pw="+pw);
            return pw;
        }
    }
    public String getSecurityUserName() {
        mcf = (JtestResourceAdapter) cccf.getMcf();    // get ManagedConnectionFactory    
        //ConnectionImpl conni = (ConnectionImpl)conn;   // get ConnectionImpl
        try {
            //JtestResourceAdapter mc = (JtestResourceAdapter)conni.getMC(); //get ManagedConnection        
            String u = mcf.getUserName();
            logger.log(BasicLevel.DEBUG, cName+".getSecurityUserName ("
                          +mcf.getRes_Auth()+")userName="+u);
            return u;
        } catch (Exception e) {
            String u = mcf.getUserName();     // find default
            logger.log(BasicLevel.DEBUG, cName
                   +".getSecurityUserName error: failed to find ManagedConnectionFactory "
                   +"instance containing userName. Using="+u);
            return u;
        }
    }
}

