// RuntimeCASLR.java
// Stateless Session bean

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

import java.rmi.RemoteException;
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.resource.cci.Connection;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ConnectionManager;
import ersatz.resourceadapter.*;
import javax.resource.spi.ConnectionEvent;


/*
 */
public class RuntimeCASLR implements SessionBean {

    SessionContext ejbContext;
    private ManagedConnectionFactoryImpl mcf = null; //Managed Connection Factory
    private ConnectionFactoryImpl cccf = null;   //Common Client Connection Factory
    private ConnectionImpl conn = null;
    private ConnectionSpecImpl csp = null;    //ConnectionSpec
    private ConnectionRequestInfoImpl crii = null;
    InitialContext ic=null;
    private String res_auth = "";
    String cName = "RuntimeCASLR";

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


    public void setSessionContext(SessionContext ctx) {
        Utility.log(cName+".setSessionContext");
        ejbContext = ctx;
    }
        

    public void ejbRemove() {
        Utility.log(cName+".ejbRemove");
    }
        

    public void ejbCreate() throws CreateException {
        Utility.log(cName+".ejbCreate");
    }

    public void ejbPassivate() {
        Utility.log(cName+".ejbPassivate");
    }

    public void ejbActivate() {
        Utility.log(cName+".ejbActivate");
    }
    
    // ------------------------------------------------------------------
    // 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
    {
        Utility.log("============================ "+testName);
        Utility.log(cName+".method1 : lookup "+rar_jndi_name);
        try {
            ic = new InitialContext();
        } catch (Exception e1) {
            Utility.log(cName+".method1 error: InitialContext failed");
            throw e1;
        }
        try {
            cccf = (ConnectionFactoryImpl)ic.lookup(rar_jndi_name);
            Utility.log(cName+".method1 : found "+rar_jndi_name);
        } catch (Exception e2) {
            Utility.log(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 ConnectionSpecImpl(); // get a new ConnectionSpecImpl
            csp.setUserName("Ersatz_User_Name");
            csp.setPassword("__Jtest_Pass_word__");
            Utility.log(cName
                  +".method1 : ConnectionSpecImpl + Ersatz_User_Name,__Jtest_Pass_word__");
        } catch (Exception e3) {
            Utility.log(cName+".method1 : new connection spec failed");
            throw e3;
        }
        try {
            conn = (ConnectionImpl)cccf.getConnection();
            if (conn==null) {
                Utility.log(cName+".method1 error: getConnection returned null connection.");
                throw new Exception("");
            }
        } catch (Exception e4) {
            Utility.log(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 
                // ManagedConnectionImpl instance is now invalid and unusable.
                conn.close(ConnectionEvent.CONNECTION_ERROR_OCCURRED);
                Utility.log(cName+".closeUp : closed physical connection");
            } else {
                // The CONNECTION_CLOSED indicates that connection handle
                // is closed, but physical connection still exists
                conn.close();
                Utility.log(cName+".closeUp : closed connection");
            }
        } catch (Exception e) {
            Utility.log(cName+".closeUp error: close handle/physical connection failed");
        }
    }
    /**
     * JUnit tests
     */
    public int getMCF_Pwriter()
    {
        int here=2;
        mcf = cccf.getMcf();  // ManagedConnectionFactory    
        try {
            if (mcf.getLogWriter()==null) {              // PrintWriter is null
                Utility.log(cName+".getMCF_Pwriter No PrintWriter registered in "+
                            "ManagedConnectionFactoryImpl");
                here=0;
            }
            else {
                Utility.log(cName+".getMCF_Pwriter PrintWriter is o.k.in "+
                            "ManagedConnectionFactoryImpl");
                here=1;
            }
        } catch (Exception e) {
            Utility.log(cName+
                ".getMCF_Pwriter error: "+e.toString());
        }
        return here;
    }
    public int getMC_Pwriter()
    {
        int here=2;
        try {
            ManagedConnectionImpl mc = conn.getMC();        
            if (mc.getLogWriter()==null) {              // PrintWriter not null
                Utility.log(cName+
                    ".getMC_Pwriter No PrintWriter registered in ManagedConnectionImpl");
                here=0;
            }
            else {
                Utility.log(cName+
                    ".getMC_Pwriter PrintWriter in ManagedConnectionImpl is o.k.");
                here=1;
            }
        } catch (Exception e) {
            Utility.log(cName+
                ".getMC_Pwriter error: "+e.toString());
        }
        return here;
    }
    public String getResAuth() {
        try {
            ManagedConnectionImpl mc = conn.getMC();
            String ra = mc.res_auth;              // get real "Application" or "Container"
            Utility.log(cName+".getResAuth "
                       +"<res-auth>"+ra+"</res-auth>");
            if (ra==null || ra.length()==0) 
                throw new Exception("");
            return ra;
        } catch (Exception e) {
            Utility.log(cName
                   +".getResAuth error: failed to find <res-auth> "
                   +"in ManagedConnectionImpl");
            return "";
        }
    }
    public String getSecurityPassword() {
        crii = conn.crii;  // look at ConnectionRequestInfoImpl
        try {
            ManagedConnectionImpl mc = conn.getMC();
            String pw = crii.getPassword();
            Utility.log(cName+".getSecurityPassword ("
                          +mc.res_auth+")password="+pw);
            if (pw==null || pw.length()==0) 
                throw new Exception("");
            return pw;
        } catch (Exception e) {
            mcf = cccf.getMcf();
            String pw = mcf.defaultPassword;    // find default
            Utility.log(cName
                   +".getSecurityPassword error: failed to find ConnectionRequestInfoImpl "
                   +"instance containing password. Using default="+pw);
            return pw;
        }
    }
    public String getSecurityUserName() {
        crii = conn.crii;  // look at ConnectionRequestInfoImpl
        try {
            ManagedConnectionImpl mc = conn.getMC();
            String u = crii.getUserName();
            Utility.log(cName+".getSecurityUserName ("
                          +mcf.getRes_Auth()+")userName="+u);
            if (u==null || u.length()==0) 
                throw new Exception("");
            return u;
        } catch (Exception e) {
            mcf = cccf.getMcf();
            String u = mcf.defaultUserName;     // find default
            Utility.log(cName
                   +".getSecurityUserName error: failed to find ConnectionRequestInfoImpl "
                   +"instance containing userName. Using default="+u);
            return u;
        }
    }
}

