package com.sap.mw.jco.jra.examples;

//import com.sap.mw.jco.jra.JRA;
import java.io.PrintStream;
import java.rmi.RemoteException;
import java.util.Map;
import java.util.Properties;
import javax.ejb.*;
import javax.naming.InitialContext;
import javax.resource.cci.*;
import javax.transaction.UserTransaction;

/**
 * Before you start using this bean, check, if you system contains RFMs used here.
 * This is an example of a bean managed stateless session bean (component-managed demarcation).
 * The container managed authentication is used here.
 * (check, if you set the tag <res-auth>Container</res-auth> correct)
 */
public class ExampleBMBean
    implements SessionBean
{

    private SessionContext m_sessionContext;

    public ExampleBMBean()
    {
    }

    public void ejbCreate()
    {
    }

    public void ejbRemove()
        throws RemoteException
    {
    }

    public void ejbActivate()
        throws RemoteException
    {
    }

    public void ejbPassivate()
        throws RemoteException
    {
    }

    public void setSessionContext(SessionContext sessionContext)
        throws RemoteException
    {
        m_sessionContext = sessionContext;
    }

     /**
     * This method creats a new record in the table.
     * It uses Bean-Managed demarcation.
     * The application can use here the UserTransaction for writing accesses on the DB.
     * The application should call begin, commit/rollback transaction by itself.
     */
    public String callBapiBankCreateUsingUserTransaction(String bankCountry, String bankKey, String bankName, String bankCity)
        throws RemoteException
    {
        String result = "";
        Connection connection = null;
        try
        {
            System.out.println("\n*************************************************\n");
            System.out.println("method callBapiBankCreateUsingUserTransaction");
            InitialContext initialcontext = new InitialContext();

            // look up for ConnectinFactory
            ConnectionFactory connectionfactory = (ConnectionFactory) initialcontext.lookup("eis/SAPJRAFactory");
            //ConnectionFactory connectionfactory = (ConnectionFactory) initialcontext.lookup("java:comp/env/eis/SAPJRAFactory");

            // get RecordFactory
            RecordFactory recordfactory = connectionfactory.getRecordFactory();

            // create UserTransaction
            UserTransaction userTransaction = (UserTransaction) initialcontext.lookup("java:comp/UserTransaction");
            // or get UserTransaction from Context
            //UserTransaction userTransaction = m_sessionContext.getUserTransaction();
            System.out.println("call userTransaction.begin()");

            // start userTransaction
            userTransaction.begin();
            result = "Transaction started.\n";

            // get Connection
            connection = connectionfactory.getConnection();

            // create Interaction
            Interaction interaction = connection.createInteraction();

            // create data structure for BAPI_BANK_CREATE
            MappedRecord input = recordfactory.createMappedRecord("BAPI_BANK_CREATE");
            System.out.println("MappedRecord(\"BAPI_BANK_CREATE\") was created");

            // fill out the structure with data
            MappedRecord bankAddressStructure = (MappedRecord)input.get("BANK_ADDRESS");
            bankAddressStructure.put("BANK_NAME", bankName);
            bankAddressStructure.put("CITY", bankCity);
            input.put("BANK_CTRY", bankCountry);
            input.put("BANK_KEY", bankKey);

            // execute interaction (call RFC) and get output
            MappedRecord output = (MappedRecord)interaction.execute(null, input);

            // extract results
            String resultBankCountry = (String)output.get("BANKCOUNTRY");
            String resultBankKey = (String)output.get("BANKKEY");
            MappedRecord returnStructure = (MappedRecord)output.get("RETURN");
            String resultMessage = (String)returnStructure.get("MESSAGE");
            if(resultMessage != null && resultMessage.trim().length() != 0)
                throw new Exception("Error-Message from SAP-system: "+resultMessage);
            result = result + "Created Bank ("+resultBankCountry+", "+resultBankKey+").\n";

            // commit transaction
            userTransaction.commit();
            result = result+"Transaction commited.";

            // release interaction
            interaction.close();

            return result;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            throw new RemoteException(e.getMessage(), e);
        }
        finally
        {
            if (connection != null)
            {
                try
                {
                    connection.close();
                }
                catch(Exception exception1) { }
            }
        }
    }

    /**
     * This method creats a new record in the table.
     * It uses Bean-Managed demarcation.
     * The application can use here the LocalTransaction for writing accesses on the DB.
     * The application should call begin, commit/rollback transaction by itself.
     */
    public String callBapiBankCreateUsingLocalTransaction(String bankCountry, String bankKey, String bankName, String bankCity)
        throws RemoteException
    {
        String result = "";
        Connection connection = null;
        try
        {
            System.out.println("\n*************************************************\n");
            System.out.println("method callBapiBankCreateUsingLocalTransaction");
            InitialContext initialcontext = new InitialContext();

            // look up for ConnectinFactory
            ConnectionFactory connectionfactory = (ConnectionFactory) initialcontext.lookup("eis/SAPJRAFactory");
            //ConnectionFactory connectionfactory = (ConnectionFactory) initialcontext.lookup("java:comp/env/eis/SAPJRAFactory");

            // get RecordFactory
            RecordFactory recordfactory = connectionfactory.getRecordFactory();

            // get Connection
            connection = connectionfactory.getConnection();

            // start LocalTransaction
            result = "Transaction started.\n";
            connection.getLocalTransaction().begin();

            // create Interaction
            Interaction interaction = connection.createInteraction();

            // create data structure for BAPI_BANK_CREATE
            MappedRecord input = recordfactory.createMappedRecord("BAPI_BANK_CREATE");
            System.out.println("MappedRecord(\"BAPI_BANK_CREATE\") was created");

            // fill out the structure with data
            MappedRecord bankAddressStructure = (MappedRecord)input.get("BANK_ADDRESS");
            bankAddressStructure.put("BANK_NAME", bankName);
            bankAddressStructure.put("CITY", bankCity);
            input.put("BANK_CTRY", bankCountry);
            input.put("BANK_KEY", bankKey);

            // execute interaction (call RFC) and get output
            MappedRecord output = (MappedRecord)interaction.execute(null, input);

            // extract results
            String resultBankCountry = (String)output.get("BANKCOUNTRY");
            String resultBankKey = (String)output.get("BANKKEY");
            MappedRecord returnStructure = (MappedRecord)output.get("RETURN");
            String resultMessage = (String)returnStructure.get("MESSAGE");
            if(resultMessage != null && resultMessage.trim().length() != 0)
                throw new Exception("Error-Message from SAP-system: "+resultMessage);
            result = result + "Created Bank ("+resultBankCountry+", "+resultBankKey+").\n";

            // commit transaction
            connection.getLocalTransaction().commit();
            result = result+"Transaction commited.";

            // release interaction
            interaction.close();

            return result;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            throw new RemoteException(e.getMessage(), e);
        }
        finally
        {
            if (connection != null)
            {
                try
                {
                    connection.close();
                }
                catch(Exception exception1) { }
            }
        }
    }
}