# TransactionImpl.java

    /*
    ** Module   : TransactionImpl.java
    ** Abstract : Implementation of the TRANSACTION resource.
    **
    ** Copyright (c) 2018-2023, Golden Code Development Corporation.

    **
    ** -#- -I- --Date-- --------------------------------Description-----------------------------------
    ** 001 CA  20181112 Created initial version.
    ** 002 GBB 20230512 Logging methods replaced by CentralLogger/ConversionStatus.
    ** 003 CA  20230607 TRANSACTION-MODE AUTO must preserve the tx in the root appserver block - this is required
    **                  because in modes other than State-free, requests can be executed on the same agent who had
    **                  TRANSACTION-MODE AUTO, and this must see as active the tx initially set.
    */
    /*
    ** This program is free software: you can redistribute it and/or modify
    ** it under the terms of the GNU Affero General Public License as
    ** published by the Free Software Foundation, either version 3 of the
    ** License, or (at your option) any later version.
    **
    ** This program 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 Affero General Public License for more details.
    **
    ** You may find a copy of the GNU Affero GPL version 3 at the following
    ** location: https://www.gnu.org/licenses/agpl-3.0.en.html
    **
    ** Additional terms under GNU Affero GPL version 3 section 7:
    **
    **   Under Section 7 of the GNU Affero GPL version 3, the following additional
    **   terms apply to the works covered under the License.  These additional terms
    **   are non-permissive additional terms allowed under Section 7 of the GNU
    **   Affero GPL version 3 and may not be removed by you.
    **
    **   0. Attribution Requirement.
    **
    **     You must preserve all legal notices or author attributions in the covered
    **     work or Appropriate Legal Notices displayed by works containing the covered
    **     work.  You may not remove from the covered work any author or developer
    **     credit already included within the covered work.
    **
    **   1. No License To Use Trademarks.
    **
    **     This license does not grant any license or rights to use the trademarks
    **     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
    **     of Golden Code Development Corporation. You are not authorized to use the
    **     name Golden Code, FWD, or the names of any author or contributor, for
    **     publicity purposes without written authorization.
    **
    **   2. No Misrepresentation of Affiliation.
    **
    **     You may not represent yourself as Golden Code Development Corporation or FWD.
    **
    **     You may not represent yourself for publicity purposes as associated with
    **     Golden Code Development Corporation, FWD, or any author or contributor to
    **     the covered work, without written authorization.
    **
    **   3. No Misrepresentation of Source or Origin.
    **
    **     You may not represent the covered work as solely your work.  All modified
    **     versions of the covered work must be marked in a reasonable way to make it
    **     clear that the modified work is not originating from Golden Code Development
    **     Corporation or FWD.  All modified versions must contain the notices of
    **     attribution required in this license.
    */

    package com.goldencode.p2j.util;

    import java.util.logging.Level;

    import com.goldencode.p2j.security.*;
    import com.goldencode.p2j.util.logging.*;

    /**
     * Implements the TRANSACTION resources and all associated APIs.
     */
    public class TransactionImpl
    extends HandleResource
    implements TransactionResource,
               Deletable
    {
       /** Logger */
       private static final CentralLogger LOG = CentralLogger.get(TransactionImpl.class.getName());

       /** Context local state for the TRANSACTION handle. */
       private static final ContextLocal<WorkArea> work = new ContextLocal<WorkArea>()
       {
          /**
           * Initializes the work area, the first time it is requested within a new context.
           *
           * @return   The newly instantiated work area.
           */
          @Override
          protected WorkArea initialValue()
          {
             return new WorkArea();
          }
       };

       /** The current value of the TRANS-INIT-PROCEDURE attribute. */
       private handle txInitProcedure = new handle();

       /** The current value of the DEFAULT-COMMIT attribute. */
       private boolean defaultCommit = false;

       /** Flag turned on when a pending rollback is active, via {@link #setRollback()}. */
       private boolean pendingRollback = false;

       /** Flag turned on when a pending commit is active, via {@link #setCommit()}. */
       private boolean pendingCommit = false;

       /** Flag indicating the current tx was open by TRANS-INIT-PROCEDURE. */
       private boolean openByTxInitProc = false;

       /**
        * Private c'tor, to allow a singleton instance of this resource, per each context.
        */
       private TransactionImpl()
       {
          // singleton instance, per each context
       }

       /**
        * Get the TRANSACTION resource for this context.
        *
        * @return   See above.
        */
       static TransactionImpl get()
       {
          WorkArea wa = work.get();

          if (wa.tx == null)
          {
             wa.tx = new TransactionImpl();
          }

          return wa.tx;
       }

       /**
        * Implementation for the {@link WrappedResource#valid()} API.
        *
        * @return   Always true.
        */
       @Override
       public boolean valid()
       {
          return true;
       }

       @Override
       public void delete()
       {
          if (!SessionUtils._isRemote() && LOG.isLoggable(Level.WARNING))
          {
             LOG.warning("Trying to delete the TRANSACTION-OBJECT from a non-appserver client!");
          }

          // when accessed from a appserver agent (SESSION:REMOTE is true), this can not be deleted
          // if accessed from normal clients, it can be deleted and the behavior is indeterminate
          // we always assume this can't be deleted.
       }

       /**
        * Getter for the INSTANTIATING-PROCEDURE attribute.
        *
        * @return   Always an unknown handle.
        */
       @Override
       public handle instantiatingProcedure()
       {
          return new handle();
       }

       /**
        * Getter of IS-OPEN attribute - it will return the value of the
        * {@link TransactionManager#isTransactionActive()} call.
        *
        * @return   See above.
        */
       @Override
       public logical isOpen()
       {
          return TransactionManager.isTransactionActive();
       }

       /**
        * Check the value of the DEFAULT-COMMIT attribute.
        *
        * @return   The value of the DEFAULT-COMMIT attribute.
        */
       @Override
       public logical isDefaultCommit()
       {
          return new logical(defaultCommit);
       }

       /**
        * Set the value of the DEFAULT-COMMIT attribute.
        *
        * @param    l
        *           The value of the DEFAULT-COMMIT attribute.
        */
       @Override
       public void setDefaultCommit(logical l)
       {
          if (l.isUnknown())
          {
             ErrorManager.recordOrShowError(4083,
                                            "**Unable to assign UNKNOWN value to attribute " +
                                            "DEFAULT-COMMIT on TRANSACTION-CONTEXT widget.",
                                            false, false, false, true);
             return;
          }

          setDefaultCommit(l.booleanValue());
       }

       /**
        * Set the value of the DEFAULT-COMMIT attribute.
        *
        * @param    l
        *           The value of the DEFAULT-COMMIT attribute.
        */
       @Override
       public void setDefaultCommit(boolean l)
       {
          defaultCommit = l;
       }

       /**
        * Get the TRANS-INIT-PROCEDURE attribute.
        *
        * @return   See above.
        */
       @Override
       public handle getTxInitProcedure()
       {
          if (ProcedureManager.hasReferent(txInitProcedure.get()))
          {
             return new handle(txInitProcedure);
          }
          else
          {
             txInitProcedure.setUnknown();

             return new handle();
          }
       }

       /**
        * If we are in a TRANSACTION-MODE AUTOMATIC state and a tx is open, mark a pending commit for
        * the current top-level block.
        *
        * @return   <code>true</code> if the pending commit was set or a tx is not open.
        */
       @Override
       public logical setCommit()
       {
          if (txInitProcedure.isUnknown() || pendingRollback)
          {
             ErrorManager.recordOrShowError(7355,
                                            "SET-COMMIT requires a TRANSACTION-MODE AUTOMATIC .p " +
                                            "to be running with no prior SET-ROLLBACK",
                                            false, false, false);
             return new logical(false);
          }

          if (TransactionManager.isTransaction())
          {
             // this just marks the commit to be performed when appserver request is finished
             pendingCommit = true;
          }

          return new logical(true);
       }

       /**
        * If we are in a TRANSACTION-MODE AUTOMATIC state and a tx is open, mark a pending rollback for
        * the current top-level block.
        *
        * @return   <code>true</code> if the pending rollback was set or a tx is not open.
        */
       @Override
       public logical setRollback()
       {
          if (txInitProcedure.isUnknown())
          {
             ErrorManager.recordOrShowError(7356,
                                            "SET-ROLLBACK requires a TRANSACTION-MODE AUTOMATIC .p " +
                                            "to be running persistently",
                                            false, false, false);
             return new logical(false);
          }

          // if pending commit, then deactivate it and activate the pending rollback
          pendingCommit = false;

          // this just marks the rollback to be performed when appserver request is finished
          pendingRollback = true;

          return new logical(true);
       }

       /**
        * Explicitly assign the {@link #txInitProcedure TRANS-INIT-PROCEDURE} attribute.
        *
        * @param    referent
        *           The new procedure having a TRANSACTION-MODE AUTOMATIC statement, or <code>null</code>
        *           to clear this attribute and the pending flags.
        */
       static void setTxInitProcedure(Object referent)
       {
          TransactionImpl tx = get();

          if (referent != null)
          {
             tx.defaultCommit = true;
             tx.txInitProcedure.assign(new ExternalProgramWrapper(referent));
          }
          else
          {
             tx.txInitProcedure.setUnknown();

             tx.pendingCommit = false;
             tx.pendingRollback = false;
             tx.defaultCommit = false;
          }
       }

       /**
        * Check if the given external program instance is the
        * {@link #txInitProcedure TRANS-INIT-PROCEDURE} attribute.
        *
        * @param    referent
        *           The external program instance to check.
        *
        * @return   <code>true</code> if the refernet is the same as the {@link #txInitProcedure}.
        */
       static boolean isTxInitProcedure(Object referent)
       {
          TransactionImpl tx = get();

          return !tx.txInitProcedure.isUnknown() && tx.txInitProcedure.get() == referent;
       }

       /**
        * Get the {@link #openByTxInitProc} flag.
        *
        * @return   The state of the {@link #openByTxInitProc}.
        */
       static boolean isOpenByTxInitProc()
       {
          return get().openByTxInitProc && TransactionManager.isTransaction();
       }

       /**
        * Set the {@link #openByTxInitProc} flag.
        *
        * @param    l
        *           The new state of the {@link #openByTxInitProc}.
        */
       static void setOpenByTxInitProc(boolean l)
       {
          get().openByTxInitProc = l;
       }

       /**
        * Notification that a top-level request has been finished, in the context of a top-level block
        * belonging to the TRANS-INIT-PROCEDURE external program.
        *
        * @param    chained
        *           Flag indicating a new tx will be opened.
        * @param    implicit
        *           Flag indicating if this call is for the implicit end of a request, not the delete of the tx
        *           procedure.
        *
        * @return   <code>true</code> if there is either a pending {@link #pendingCommit commit} or
        *           {@link #pendingRollback rollback}.
        */
       static boolean requestFinished(boolean chained, boolean implicit)
       {
          TransactionImpl tx = get();

          if (implicit && !(tx.pendingCommit || tx.pendingRollback))
          {
             return false;
          }

          try
          {
             if (tx.pendingCommit || (tx.defaultCommit && !tx.pendingRollback))
             {
                TransactionManager.commitTx(chained);
                return true;
             }
             else
             {
                // otherwise, rollback always
                TransactionManager.rollbackTx(chained);
                return true;
             }
          }
          finally
          {
             // this includes lock releases
             TransactionManager.notifyMasterFinish();

             tx.pendingCommit = false;
             tx.pendingRollback = false;
          }
       }

       /**
        * Context-local state.
        */
       private static class WorkArea
       {
          /** The context-local global instance for the TRANSACTION resource. */
          private TransactionImpl tx = null;
       }
    }