/*
 * Created on January 13, 2004
 *
 * WorkImpl.java is used to test JCA 1.5
 * as implemented by JOnAS. This class implements the Work Interface
 *  
 */
package ersatz.resourceadapter;

import javax.resource.spi.work.Work;
import javax.resource.spi.endpoint.MessageEndpointFactory;
import javax.resource.spi.endpoint.MessageEndpoint;
import javax.resource.spi.UnavailableException;
import javax.resource.ResourceException;

/**
 * @author Bob Kruse
 *
 * JCA1.5 Work class
 *
 * used to test the J2EE Connector as implemented by JOnAS.
 * 
 */
public class WorkImpl 
        implements Work
{
    private String workType;
    private MessageEndpointFactory factory = null;
    private String message;
    private MessageEndpoint ep = null;
    String cName = "WorkImpl";
    
    // constructor #1
    public WorkImpl(String w) { 
        workType=w;
    }
    // constructor #2
    public WorkImpl(MessageEndpointFactory factory, String message) 
            throws Exception
    { 
        Utility.log(cName+".constructor factory="+factory+" message="+message);
        this.factory=factory;
	    this.message=message;
        workType="Message Delivery";
        if (factory==null) throw new Exception("MessageEndpointFactory==null");
    }
    public void release()
    {
        Utility.log(cName+".release workType="+workType);
    }
    public void run()
    {
        ersatz.resourceadapter.MsgListenerInterface mli = null;
        Utility.log(cName+".run workType="+workType) ;
        if (workType.equals("Message Delivery")) {
            try {
                // create endpoint     ---cannot handle XA
                // deliver message
                ep = factory.createEndpoint(null);
                Utility.log(cName+".run factory.CreateEndpoint created. ep="+ep);
                
                mli = (ersatz.resourceadapter.MsgListenerInterface)ep;
                if (ep != null) {
/* tmp */           //mli.offMessage(message);
/* tmp */           //Utility.log(cName+".run onMessage successful.");
                    mli.onMessage(message);
                    Utility.log(cName+".run onMessage successful.");
                } else {
                    Utility.log(cName+".run error: endpoint="+ep);
                }
            } catch (UnavailableException ue) {
                Utility.log(cName+".run error: UnavailableException");
                ue.printStackTrace();
            } catch (Exception e) {
                Utility.log(cName+".run error: Exception e="+e);
                e.printStackTrace();
            } catch (Throwable t) {
                Utility.log(cName+".run error: Throwable t="+t);
                t.printStackTrace();
            }
        }
        if (ep!=null) {
            ep.release();
        }
        
    }
    public String getWorkType()
    {
        return workType;
    }
}