// securedCASLR.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.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.JtestResourceAdapter;


/**
 *
 */
public class securedCASLR 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;
    InitialContext ic=null;
    private String res_auth = "";
    String cName = "securedCASLR";

    // ------------------------------------------------------------------
    // 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, "");
    }
        

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

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

    public void ejbActivate() {
        logger.log(BasicLevel.DEBUG, "");
    }
    
    /**
     * 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");
        }
    }
    public void setResAuth(String ra) {
        res_auth=ra;  // set to Application or Container
    }
    public void setMatchNull(boolean b) {
        mcf = (JtestResourceAdapter) cccf.getMcf(); // ManagedConnectionFactory    
        mcf.setMatchNull(b);        
    }
    // ------------------------------------------------------------------
    // secured 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;
        }
        
            //
            // Container-managed sign-on when file "secured.xml" contains line below
            //
            //   <res-auth>Container</res-auth>
            //
        try {
            conn = (ConnectionImpl)cccf.getConnection();
            logger.log(BasicLevel.DEBUG, cName+".method1 : getConnection() 'Container' 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;
        }
    }

    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;
        }
    }

}

