/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: JEntitySwitchCRW.java 19262 2010-02-18 09:23:36Z durieuxp $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.ejb21;

import javax.ejb.EJBException;
import javax.ejb.NoSuchObjectLocalException;
import javax.ejb.TransactionRolledbackLocalException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.Transaction;

import org.ow2.jonas.deployment.ejb.EntityDesc;


import org.objectweb.util.monolog.api.BasicLevel;

/**
 * Container Optimistic lock-policy.
 * Only 1 thread can write. All other threads can read, without
 * waiting for a committed state. There is no wait.
 * This policy cannot be used with shared=true.
 * This policy is only possible for CMP2 entitybeans.
 * @author Philippe Durieux
 */
public class JEntitySwitchCRW extends JEntitySwitchCST {

    /**
     * empty constructor. Object is initialized via init() because it is
     * implemented differently according to jorm mappers.
     */
    public JEntitySwitchCRW() {
        lockpolicy = EntityDesc.LOCK_CONTAINER_READ_WRITE;
    }

    protected void initpolicy(JEntityFactory bf) {
        // This policy implies CMP2, necessary for lazy registering
        lazyregister = !bf.isPrefetch();
    }

    /**
     * Wait until I'm allowed to work on this instance.
     * Transaction isolation may be done here, depending on lock-policy.
     * @param tx Transaction
     */
    public void waitmyturn(Transaction tx) {
        if (tx != null) {
            int waitcount = 0;
            Transaction lastrunning = null;
            // Must wait in case of other TX
            while (runningtx != null && !tx.equals(runningtx)) {
                if (TraceEjb.isDebugSynchro())
                    TraceEjb.synchro.log(BasicLevel.DEBUG, ident + "mapICtx IT: WAIT end IT");
                // deadlock detection
                blockedtx.add(tx);
                if (waitcount > 0 && runningtx.equals(lastrunning) && bf.isDeadLocked(runningtx)) {
                    blockedtx.remove(tx);
                    try {
                        tx.setRollbackOnly();
                    } catch (SystemException e) {
                        TraceEjb.logger.log(BasicLevel.ERROR, ident
                                + "getICtx IT: unexpected exception setting rollbackonly");
                    }
                    TraceEjb.logger.log(BasicLevel.WARN, ident + "getICtx IT: transaction rolled back");
                    throw new TransactionRolledbackLocalException("possible deadlock");
                }
                lastrunning = runningtx;
                waitcount++;
                waiters++;
                try {
                    wait(deadlockTimeout);
                    if (TraceEjb.isDebugSynchro())
                        TraceEjb.synchro.log(BasicLevel.DEBUG, ident + "mapICtx IT: NOTIFIED");
                } catch (InterruptedException e) {
                    if (TraceEjb.isDebugSynchro())
                        TraceEjb.synchro.log(BasicLevel.DEBUG, ident + "mapICtx IT: INTERRUPTED");
                } catch (Exception e) {
                    throw new EJBException("JEntitySwitch synchronization pb", e);
                } finally {
                    waiters--;
                    blockedtx.remove(tx);
                }
                // If transaction has been rolledback or set rollback only, give
                // up.
                int status = Status.STATUS_ROLLEDBACK;
                try {
                    status = tx.getStatus();
                } catch (SystemException e) {
                    TraceEjb.logger.log(BasicLevel.ERROR, ident
                            + "getICtx IT: unexpected exception getting transaction status");
                }
                switch (status) {
                    case Status.STATUS_MARKED_ROLLBACK:
                    case Status.STATUS_ROLLEDBACK:
                    case Status.STATUS_ROLLING_BACK:
                        TraceEjb.logger.log(BasicLevel.WARN, ident + "getICtx IT: transaction rolled back");
                        throw new TransactionRolledbackLocalException("rollback occured while waiting");
                }
            }
        }
    }

    /**
     * Map a context and its instance.
     * Could use the inherited method here. This is just a simplified
     * version for performances.
     * @param tx - the Transaction object
     * @param bctx - the JEntityContext to bind if not null
     * @param forced - force to take this context. (case of create)
     * @param holdit - increment count to hold it, a release will be called
     *        later.
     * @return JEntityContext actually mapped
     */
    public synchronized JEntityContext mapICtx(Transaction tx, JEntityContext bctx, boolean forced, boolean holdit, boolean checkreentrance) {

            // Check non-reentrance (See spec EJB 2.1 section 12.1.13)
            if (!reentrant && checkreentrance) {
                if (runningtx != null && countIT > 0 && tx != null && tx.equals(runningtx)) {
                    throw new EJBException("non-reentrant bean accessed twice in same transaction");
                }
                if (tx == null && countIH > 0) {
                    throw new EJBException("non-reentrant bean accessed twice outside transaction");
                }
            }
        waitmyturn(tx);

        // Set the timestamp to a big value because instance will be used.
        estimestamp = System.currentTimeMillis() + FEW_SECONDS;

        // Check the case where the object is detached
        if (isdetached) {
            JEntityFactory fact = (JEntityFactory) bf;
            JEntitySwitch old = fact.existEJB(getPrimaryKey(), this, false);
            if (old != null) {
                throw new NoSuchObjectLocalException("Inactivity timeout expired");
            }
            if (TraceEjb.isDebugSwapper()) {
                TraceEjb.swapper.log(BasicLevel.DEBUG, "*** Reuse " + ident + " after timeout");
            }
            isdetached = false;
        }

        // Choose the context to use.
        boolean newtrans = false;
        boolean isdirty = false;
        JEntityContext jec = itContext;
        if (forced) {
            // If the new context is enforced, we must first release the older
            if (jec != null) {
                discardContext(tx, false, true);
            }
            jec = bctx;
            itContext = jec;
            isdirty = jec.initEntityContext(this);
            newtrans = true;
        } else {
            // First check if bean still exists
            if (isremoved) {
                TraceEjb.logger.log(BasicLevel.WARN, ident + " has been removed.");
                throw new NoSuchObjectLocalException("Try to access a bean previously removed");
            }
            if (jec != null) {
                if (todiscard) {
                    TraceEjb.logger.log(BasicLevel.WARN, ident + " has been discarded.");
                    throw new NoSuchObjectLocalException("Try to access a bean previously discarded");
                }
                // Reuse the Context for this transaction.
                // If a context was supplied, release it first.
                if (bctx != null) {
                    bf.releaseJContext(bctx, 2);
                }
                if (runningtx == null) {    // TODO change this checking
                    newtrans = true;
                }
                jec.reuseEntityContext(newtrans);
            } else {
                if (bctx != null) {
                    jec = bctx;
                } else {
                    // no Context available : get one from the pool.
                    jec = (JEntityContext) bf.getJContext(this);
                }
                isdirty = jec.initEntityContext(this);
                jec.activate(true);
                itContext = jec; // after activate
                newtrans = true;
            }
        }

        if (tx != null) {
            // Register Context now, except if no new transaction
            if (newtrans && (!lazyregister || isdirty)) {
                try {
                    registerCtx(tx, jec);
                } catch (IllegalStateException e) {
                    TraceEjb.synchro.log(BasicLevel.WARN, ident + "mapICtx IT: not registered!", e);
                    // must not continue, since Tx is probably rolled back
                    // don't risk to modify database without registering the Ctx
                    throw e;
                }
            }
            if (holdit) {
                countIT++;
            }
        } else {
            if (holdit) {
                countIH++;
                if (shared && countIH == 1) {
                    // reload state that could have been modified by
                    // transactions.
                    jec.activate(false);
                }
            }
        }
        return jec;
    }

}
