// connectorCASLR.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.cci.ConnectionMetaData;
import javax.resource.spi.ConnectionEvent;

import org.ow2.jonas.lib.util.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.JtestInteraction;
import fictional.resourceadapter.JtestResourceAdapter;

/**
 *  -
 */
public class connectorCASLR implements SessionBean {

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

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


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

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

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

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

    public void ejbActivate() {
        logger.log(BasicLevel.DEBUG, cName+".ejbActivate");
    }
    
    // ------------------------------------------------------------------
    // connectorCA implementation
    // ------------------------------------------------------------------
    /**
     * method1
     */
    public void method1(String rar_jndi_name, String testName) 
            throws Exception
    {
        logger.log(BasicLevel.DEBUG, "============================ "+testName);
        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;
        }
        
        try {
            csp = new CommonClient(); // get a new ConnectionSpec
                logger.log(BasicLevel.DEBUG, cName
                  +".method1 : ConnectionSpec o.k.");
            
        } catch (Exception e3) {
            logger.log(BasicLevel.DEBUG, cName+".method1 : new connection spec failed");
            throw e3;
        }
        try {
            conn = (ConnectionImpl)cccf.getConnection();
            logger.log(BasicLevel.DEBUG, cName+".method1 : getConnection conn="+conn);
            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;
        }
        try {
            i = (JtestInteraction)conn.createInteraction();
        } catch (Exception e5) {
            logger.log(BasicLevel.DEBUG, cName+".method1 error: create interaction failed");
            throw e5;
        }
        try {
            cMetaData = (ConnectionMetaData)conn.getMetaData();
        } catch (Exception e6) {
            logger.log(BasicLevel.DEBUG, cName+".method1 : get ConnectionMetaData failed");
            throw e6;
        }

    }

    /**
     * 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 boolean isConnectionSpec() {
        if (csp==null) return false;
        else return true;
    }
    public boolean isConnection() {
        if (conn==null) return false;
        else return true;
    }
    public boolean isInteraction() {
        if (i==null) return false;
        else return true;
    }
    public String getConnectionProduct() 
            throws Exception
    {
        String s;
        try {
            s = cMetaData.getEISProductName();
            logger.log(BasicLevel.DEBUG, cName+".getConnectionProduct : ConnectionMetaData.product="+s);
        } catch (Exception e) {
            logger.log(BasicLevel.DEBUG, cName+".getConnectionProduct error: ConnectionMetaData.getEISProductName() failed");
            throw e;
        }
        return s;
    }
    /**
     * The application server calls setter methods on the ManagedConnectionFactory instance
     * to set various configuration properties on this instance. These properties provide
     * information required by the ManagedConnectionFactory instance to create physical
     * connections to the underlying EIS. The application server uses an existing property set
     * (configured during the deployment of a resource adapter) to set the required properties on
     * the ManagedConnectionFactory instance.
     * 
     */    
    public String getServerName()
            throws Exception
    {
        logger.log(BasicLevel.DEBUG, cName+".getServerName");
        mcf = (JtestResourceAdapter) cccf.getMcf(); // ManagedConnectionFactory    
        String cp1 = "null";
        if (mcf==null) return cp1;
        try {
            cp1 = mcf.getServerName();
        } catch (Exception e) {
            logger.log(BasicLevel.DEBUG, cName+".getConfigurationProperty error: failed");
            throw e;
        }
        return cp1;
    }
    public String getProtocolProperty()
            throws Exception
    {
        logger.log(BasicLevel.DEBUG, cName+".getProtocolProperty");
        mcf = (JtestResourceAdapter) cccf.getMcf(); // ManagedConnectionFactory    
        String p = "null";
        if (mcf==null) return p;
        try {
            p = mcf.getProtocol();
        } catch (Exception e) {
            logger.log(BasicLevel.DEBUG, cName+".getProtocolProperty error: failed");
            throw e;
        }
        return p;
    }
    /**
     * After the newly created ManagedConnectionFactory instance has been configured with
     * its property set, the application server creates a new ConnectionManager instance.
     * true returned if ConnectionManager is valid
     */
    public boolean getCMInstance()
    {
        mcf = (JtestResourceAdapter) cccf.getMcf();  // ManagedConnectionFactory    
        if (mcf.getCM()==null) {                     // ConnectionManager not null
            logger.log(BasicLevel.DEBUG, cName+".getCMInstance error: ConnectionManager is null");
            return false;
        }
        else {
            logger.log(BasicLevel.DEBUG, cName+".getCMInstance ConnectionManager is o.k.");
            return true;
        }
    }
    public int getMCF_Pwriter()
    {
        int here=2;
        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 void setMatchNull(boolean b) {
        mcf = (JtestResourceAdapter) cccf.getMcf(); // ManagedConnectionFactory    
        mcf.setMatchNull(b);        
    }
    public int cntListeners()
    {
        int i = 0;
        ConnectionImpl conni = (ConnectionImpl)conn;
        try {
             JtestResourceAdapter mc = (JtestResourceAdapter)conni.getMC(); //get ManagedConnection        
             i = mc.cntListeners();
            logger.log(BasicLevel.DEBUG, cName+".cntListeners cnt="+i);
        } catch (Exception e) {
            logger.log(BasicLevel.DEBUG, cName+".cntListeners error: failed to count Listeners");
        }
        return i;
    }
}

