/*
 *  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 *  Copyright 2000-2009 Sun Microsystems, Inc. All rights reserved. 
 *
 *  The contents of this file are subject to the terms of either the GNU
 *  General Public License Version 2 only ("GPL") or the Common Development
 *  and Distribution License ("CDDL") (collectively, the "License").  You may
 *  not use this file except in compliance with the License.  You can obtain
 *  a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
 *  or mq/legal/LICENSE.txt.  See the License for the specific language
 *  governing permissions and limitations under the License.
 * 
 *  When distributing the software, include this License Header Notice in each
 *  file and include the License file at mq/legal/LICENSE.txt.  Sun designates
 *  this particular file as subject to the "Classpath" exception as provided by
 *  Sun in the GPL Version 2 section of the License file that accompanied this
 *  code.  If applicable, add the following below the License Header, with the
 *  fields enclosed by brackets [] replaced by your own identifying information:
 *  "Portions Copyrighted [year] [name of copyright owner]"
 * 
 *  Contributor(s):
 * 
 *  If you wish your version of this file to be governed by only the CDDL or
 *  only the GPL Version 2, indicate your decision by adding "[Contributor]
 *  elects to include this software in this distribution under the [CDDL or GPL
 *  Version 2] license."  If you don't indicate a single choice of license, a
 *  recipient has the option to distribute your version of this file under
 *  either the CDDL, the GPL Version 2 or  to extend the choice of license to
 *  its licensees as provided above.  However, if you add GPL Version 2 code
 *  and therefore, elected the GPL Version 2 license, then the option applies
 *  only if the new code is made subject to such option by the copyright holder. 
 *
 *  OnMessageRunner.java
 *
 *  @(#)OnMessageRunner.java	1.25 07/12/07
 */

package com.sun.messaging.jms.ra;

import java.util.logging.Logger;

import javax.jms.*;

import javax.resource.spi.UnavailableException;
import javax.resource.spi.work.*;
import javax.resource.spi.endpoint.*;

import javax.transaction.xa.XAResource;

import java.lang.reflect.Method;

/**
 *  Runs a single message through an application server endpoint
 */

public class OnMessageRunner implements Work {

    /** the id of this OnMessageRunner */
    protected int omrId;

    /** the message being processed */
    private Message message;

    /** the thread processing the message */
    private Thread omrThread;

    /** The OnMessageRunnerPool this belongs to */
    private OnMessageRunnerPool omrPool;

    com.sun.messaging.jmq.jmsclient.MessageImpl mqmsg;
    com.sun.messaging.jmq.jmsclient.SessionImpl mqsess;
    
    private DirectPacket dpMsg = null;
    private DirectSession ds = null;

    /** The MessageEndpoint for this MessageListener instance */
    private MessageEndpoint msgEndpoint = null;

    /** The MessageEndpointFactory for this onMessageRunner instance */
    private MessageEndpointFactory epFactory;

    /** The EndpointConsumer for this onMessageRunner instance */
    private EndpointConsumer epConsumer;

    /** The ActivationSpec for this MessageListener instance */
    private com.sun.messaging.jms.ra.ActivationSpec spec = null;

    /** The XAResource for this MessageListener instance */
    private com.sun.messaging.jmq.jmsclient.XAResourceForRA xar = null;
    private DirectXAResource dxar = null;
    private Object xarSyncObj = null;

    /** The onMessage Method that this MessageListener instance will call */
    private Method onMessage = null;

    /** Whether delivery is transacted or not */
    private boolean transactedDelivery = false;

    /** Whether the endpoint acquired is valid or not */
    private boolean endpointValid = false;

    /** Whether running in Direct mode or not */
    private boolean useDirect = false;

    /* Loggers */
    private static transient final String _className =
            "com.sun.messaging.jms.ra.OnMessageRunner";
    protected static transient final String _lgrNameInboundMessage =
            "javax.resourceadapter.mqjmsra.inbound.message";
    protected static transient final Logger _loggerIM =
            Logger.getLogger(_lgrNameInboundMessage);
    protected static transient final String _lgrMIDPrefix = "MQJMSRA_MR";
    protected static transient final String _lgrMID_EET = _lgrMIDPrefix + "1001: ";
    protected static transient final String _lgrMID_INF = _lgrMIDPrefix + "1101: ";
    protected static transient final String _lgrMID_WRN = _lgrMIDPrefix + "2001: ";
    protected static transient final String _lgrMID_ERR = _lgrMIDPrefix + "3001: ";
    protected static transient final String _lgrMID_EXC = _lgrMIDPrefix + "4001: ";
 
    /** Constructs an OnMessageRunner */
    public OnMessageRunner(int omrId, OnMessageRunnerPool omrPool,
            MessageEndpointFactory epFactory,
            EndpointConsumer epConsumer,
            ActivationSpec spec, boolean useDirect)
    {
        Object params[] = new Object[5];
        params[0] = omrPool;
        params[1] = epFactory;
        params[2] = epConsumer;
        params[3] = spec;
        params[4] = new Boolean(useDirect);

        _loggerIM.entering(_className, "constructor()", params);

        this.omrId = omrId;
        this.omrPool = omrPool;
        this.epFactory = epFactory;
        this.epConsumer = epConsumer;
        this.spec = spec;
        this.useDirect = useDirect;

        if (useDirect) {
            this.dxar = new DirectXAResource(epConsumer.getDirectSession().dc,
                    epConsumer.getDirectSession().jmsservice,
                    epConsumer.getDirectSession().connectionId);
            //Flag that the XAResource is used for an MDB
            this.dxar._setUsedByMDB(true);
        } else {
            while (xar == null) {
                try {
                    xar = new com.sun.messaging.jmq.jmsclient.XAResourceForRA(this, epConsumer.ra.xac, epConsumer.xac);
                    break;
                } catch (JMSException jmse) {
                    System.err.println("MQRA:OMR:Exception on XAResource creation-"+jmse.getMessage());
                    try {
                        Thread.sleep(2000);
                    } catch (Exception e) {
                    }
                    //System.err.println("MQRA:OMR:Running as non-transacted");
                }
            }
        }
        this.xarSyncObj = (useDirect ? this.dxar : this.xar);
        ////Acquire endpoint from epFactory here
        onMessage = epConsumer.ra._getOnMessageMethod();

        try {
            transactedDelivery = epFactory.isDeliveryTransacted(onMessage);
        } catch (java.lang.NoSuchMethodException nsme) {
            //assume non-transactedDelivery
        }
        for (int i = 1; i < 6; i++ ) {
            try {
                //If it's not deactivated
                if (epConsumer.deactivated != true) {
                    msgEndpoint = epFactory.createEndpoint(useDirect ? dxar : xar);
                    break;
                }
            } catch (UnavailableException ue) {
                try {
                    System.err.println("MQRA:OMR:createEndpoint-UnavailableException:Sleeping for:"+i*200);
                    Thread.sleep(i * 200);
                } catch (InterruptedException ie) {
                }
            }    
        }
        if (msgEndpoint == null) {
            //Could not acquire - shut down delivery of messages in this session
            System.err.println("MQRA:OMR:Endpoint Unavailable:Marking OMR as invalid-omrId="+omrId+" for:"+spec.toString());
            //_logger.log(Level.SEVERE, "MQRA:ML:Endpoint Unavailable:Shutting down delivery for "+spec.toString());
            //mqmsg._getSession().closeFromRA();
            //endpoint should be shutdown normally by AS via RA.endpointDeactivation()
            return;
        } else {
            endpointValid = true;
        }
    }

    public void release() {
        //System.out.println("MQRA:OMR:release():tName="+Thread.currentThread().getName());
    }

    public void releaseEndpoint() {
        //System.out.println("MQRA:OMR:releaseEndpoint():omrId="+omrId+" tName="+Thread.currentThread().getName());
        if (msgEndpoint!= null) {
            msgEndpoint.release();
        }
    }

    public void invalidate() {
        //System.out.println("MQRA:OMR:invalidateEndpoint():omrId="+omrId+" tName="+Thread.currentThread().getName());
        endpointValid = false;
    }


    public void run() {
        synchronized (this.xarSyncObj) {
        boolean sendUndeliverableMsgsToDMQ = spec.getSendUndeliverableMsgsToDMQ();
        if (!endpointValid) {
            System.err.println("MQRA:OMR:run:msgEP invalid-Ack Undeliverable & remove OMR fr pool-omrId="+omrId+":msg="+mqmsg.toString());
            omrPool.removeOnMessageRunner(this);
            try {
                if (this.useDirect) {
                    //Acknowledge this message as DEAD
                } else {
                    mqsess.acknowledgeUndeliverableFromRAEndpoint(mqmsg, xar, sendUndeliverableMsgsToDMQ);
                }
            } catch (JMSException jmse) {
                System.err.println("MQRA:OMR:run:msgEP invalid:JMSException on Ack Undeliverable-"+jmse.getMessage());
                jmse.printStackTrace();
            }
            return;
        }
        //System.err.println("MQRA:OMR:run:omrId="+omrId+" in thread name="+Thread.currentThread().getName()+" transacted="+transactedDelivery);

        ClassLoader cl = spec.getContextClassLoader();
        int exRedeliveryAttempts = spec.getEndpointExceptionRedeliveryAttempts();
        int exRedeliveryInterval = spec.getEndpointExceptionRedeliveryInterval();
        //Deliver message to msgEndpoint
        boolean redeliver = true;
        while (redeliver == true) {
            try {
                if (transactedDelivery) {
                    //System.err.println("MQRA:OMR:run:beforeDelivery()");
                    msgEndpoint.beforeDelivery(onMessage);
                }
                try {
                    //System.out.println("MQRA:OMR:run:Delivering to onMessage()");
                    if (cl != null) {
                        //System.out.println("MQRA:OMR:run:Setting ContextClassLoader:"+cl.toString());
                        try {
                            Thread.currentThread().setContextClassLoader(cl);
                        } catch (Exception sccle) {
                            System.err.println("MQRA:ML:run:Exception setting ContextClassLoader:"+sccle.getMessage());
                        }
                    }
                    //System.err.println("MQRA:OMR:run:Deliver Msg:JMSRedeliver="+message.getJMSRedelivered()+" Msg="+message.toString());
                    ((javax.jms.MessageListener)msgEndpoint).onMessage(message);
                    redeliver = false;
                    //System.err.println("MQRA:OMR:run:Delivered successfully-Msg="+message.toString());
                    try {
                        if (this.useDirect) {
                            //Acknowledge direct message
                            this.dpMsg._acknowledgeThisMessageForMDB(this.dxar);
                            this.dxar.setRollback(false, null);
                        } else {
                            mqsess.acknowledgeFromRAEndpoint(mqmsg, xar);
                            //System.err.println("MQRA:OMR:run:Acknowledged successfully");
                            //System.err.println("MQRA:OMR:run:omrId="+omrId+" msg acknowledged-msg="+mqmsg.toString());
                            xar.setRollback(false, null);
                        }
                    } catch (JMSException jmse) {
                        System.err.println("MQRA:OMR:run:JMSException on message acknowledgement:Rolling back if in txn");
                        if (this.useDirect) {
                            this.dxar.setRollback(true, jmse);
                        } else {
                            xar.setRollback(true, jmse);
                        }
                        jmse.printStackTrace();
                    }
                } catch (Exception rte) {
                    System.err.println("MQRA:OMR:run:Caught Exception from onMessage():Redelivering:"+rte.getMessage());
                    try {
                        message.setJMSRedelivered(true);
                    } catch (Exception jmsesr) {
                        System.err.println("MQRA:OMR:run:Exception on setJMSRedelivered():"+jmsesr.getMessage());
                        jmsesr.printStackTrace();
                    }
                    if (exRedeliveryAttempts > 0) {
                        try {
                            //System.out.println("MQRA:OMR:run:RedeliverInterval-start");
                            Thread.sleep(exRedeliveryInterval);
                            //System.out.println("MQRA:OMR:run:RedeliverInterval-stop");
                        } catch (InterruptedException ie) {
                            //System.out.println("MQRA:OMR:run:RedeliverInterval-interrupted");
                        }
                        exRedeliveryAttempts -= 1;
                    } else {
                        System.err.println("MQRA:OMR:run:Exhausted redeliveryAttempts-msg="+message.toString());
                        System.err.println("MQRA:OMR:run:Exhausted redeliveryAttempts-spec="+spec.toString());
                        //if (false) { //ackSendToDMQ not tested  - disabling for alpha
                        if (sendUndeliverableMsgsToDMQ) {
                            System.err.println("MQRA:OMR:run:Message returned & marked for routing to the DMQ");
                        } else {
                            System.err.println("MQRA:OMR:run:Message returned & marked for redelivery by the broker");
                        }
                        try {
                            if (this.useDirect){
                                this.dpMsg._acknowledgeThisMessageAsDeadForMDB(this.dxar);
                                System.err.println("MQRA:OMR:run:omrId="+omrId+":Acked Undeliverable-Msg="+dpMsg.toString());
                            } else {
                                mqsess.acknowledgeUndeliverableFromRAEndpoint(mqmsg, xar, sendUndeliverableMsgsToDMQ);
                                System.err.println("MQRA:OMR:run:omrId="+omrId+":Acked Undeliverable-Msg="+mqmsg.toString());
                            }
                        } catch (JMSException jmse) {
                            System.err.println("MQRA:OMR:run:JMSException on Acked Undeliverable-"+jmse.getMessage());
                            jmse.printStackTrace();
                        }
                        redeliver = false;
                    }
                }
                if (transactedDelivery) {
                    //System.err.println("MQRA:OMR:run:afterDelivery()");
                    msgEndpoint.afterDelivery();
                }
            } catch (Throwable t) {
                System.err.println("MQRA:OMR:run:onMessage caught Throwable-before/on/afterDelivery:Class="
                        +t.getClass().getName()
                        +"Msg="+t.getMessage());
                redeliver = false;
                t.printStackTrace();
            }
        }
        message = null;
        //System.out.println("MQRA:OMR:run:putting back omrId="+omrId);
        omrPool.putOnMessageRunner(this);
        }
    }

    public boolean equals(Object other) {
        if (other instanceof OnMessageRunner) {
            if (omrId == ((OnMessageRunner)other).getId()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public int hashCode() {
        return omrId;
    }

    public void onMessage(Message msg) {

        if (this.useDirect) {
        	// RADIRECT
            this.message = msg;
            this.dpMsg = (DirectPacket)message;
            this.ds = (DirectSession)epConsumer.getDirectSession();
            //mqmsg._setConsumerInRA();

            //System.out.println("MQRA:OMR:onMessage():starting Work on omrId="+omrId);
            try {
                epConsumer.ra.workMgr.scheduleWork(this);
            } catch (WorkException we) {
                System.err.println("MQRA:OMR:onMessage:WorkException-"+we.getMessage()+" on omrId="+omrId);
                we.printStackTrace();
            }
        } else {
        	// LOCAL, REMOTE, APIDIRECT
            //System.err.println("MQRA:OMR:onMessage()");
            message = msg;
            mqmsg = (com.sun.messaging.jmq.jmsclient.MessageImpl)message;
            mqsess = (com.sun.messaging.jmq.jmsclient.SessionImpl)epConsumer.getXASession();
            mqmsg._setConsumerInRA();

            //System.out.println("MQRA:OMR:onMessage():starting Work on omrId="+omrId);
            try {
                epConsumer.ra.workMgr.startWork(this);
            } catch (WorkException we) {
                System.err.println("MQRA:OMR:onMessage:WorkException-"+we.getMessage()+" on omrId="+omrId);
                we.printStackTrace();
            }
            ////////Replaced with Work above
            //omrThread = new Thread(this);
            //omrThread.setName("imqOnMessageRunner-Id#"+omrId);
            //
            //omrThread.start();
            ////////
        }
    }

    public int getId() {
        return omrId;
    }

    public boolean isValid() {
        return endpointValid;
    }
    
    public EndpointConsumer getEndpointConsumer() {
    	return this.epConsumer;
    }

}

