# TestExecutionSupport.java

    /*
    ** Module   : TestExecutionSupport.java
    ** Abstract : Static methods to support legacy class methods and legacy procedure execution.
    **
    ** Copyright (c) 2023-2025, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------Description---------------------------------
    ** 001 VVT 20230318 Created initial version.
    ** 002 VVT 20230418 Legacy method name is now used in callClassMethod.
    ** 003 VVT 20230512 Fixed error propagation (See #3827-350) and source formatting.
    **                  Class members sorted. Removed now unused ExecutionResult inner class.
    ** 004 VVT 20231215 Fixed error stack trace duplication. See #8126.
    ** 005 CA  20231221 Do not use UndoableFactory.object or TypeFactory.object for getting an ObjectVar instance;
    **                  instead, create the instance as ObjectVar as needed.
    ** 004 CA  20231107 Fixed string representation of the call mode, which must not include any option.
    ** 005 VVT 20240408 Minor style fixes. See #8406-70.
    ** 006 AP  20250121 Removed parameter from LegacyErrorException constructor call.
    */
    /*
    ** 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.testengine;

    import static com.goldencode.p2j.util.BlockManager.*;

    import java.lang.reflect.*;
    import java.util.function.*;

    import com.goldencode.p2j.oo.lang.*;
    import com.goldencode.p2j.util.*;

    /**
     * Static methods to support legacy class methods and legacy procedure execution.
     */
    public final class TestExecutionSupport
    {
       /**
        * Call a legacy class method.
        *
        * @param  method
        *         the Java method converted from the legacy class method
        * @param  o
        *         the legacy class instance or {@code null} for a static method
        * @param  parameters
        *         method arguments, {@code null} for no arguments
        *
        * @return the result of the call or {@code null} for methods returning VOID
        *         or if an error was raised
        *
        * @throws ErrorConditionException
        *         errors are not caught by this method
        * @throws LegacyErrorException
        *         legacy errors are not caught by this method
        */
       final static object<? extends _BaseObject_> callClassMethod(final Method method,
                                                                   final object<?> o,
                                                                   final CallParameter[] parameters)
       throws ErrorConditionException,
              LegacyErrorException
       {
          return doInBlock(() -> {
             final LegacySignature legacySignature = method
                      .getDeclaredAnnotation(LegacySignature.class);
             final character name = new character(
                      legacySignature != null ? legacySignature.name() : method.getName());
             final StringBuilder modeStringBuilder = new StringBuilder();
             final Object[] plainArgs;
             if (parameters != null)
             {
                final int nParams = parameters.length;
                plainArgs = new Object[nParams];
                for (int i = 0; i < nParams; i++)
                {
                   final CallParameter p = parameters[i];
                   plainArgs[i] = p.initialValue;
                   modeStringBuilder.append(p.mode.asString());
                }
             }
             else
             {
                plainArgs = null;
             }

             if (Void.TYPE.equals(method.getReturnType()))
             {
                if (plainArgs != null)
                {
                   ObjectOps.invokeStandalone(o, name, modeStringBuilder.toString(),
                            plainArgs);
                }
                else
                   ObjectOps.invokeStandalone(o, name);
                return null;
             }

             final BaseDataType retVal = plainArgs != null
                      ? ObjectOps.invoke(o, name, modeStringBuilder.toString(), plainArgs)
                      : ObjectOps.invoke(o, name);
             return (object<? extends _BaseObject_>) retVal;
          });
       }

       /**
        * Call a legacy internal procedure.
        *
        * @param  method
        *         the Java method converted from the legacy internal procedure
        * @param  h
        *         the persistent procedure handle
        *
        * @throws ErrorConditionException
        *         by the executed legacy code
        * @throws LegacyErrorException
        *         legacy errors are not caught by this method
        */
       final static void callProcedureMethod(final Method method, final handle h)
       throws ErrorConditionException,
              LegacyErrorException
       {
          // FIXME: threat artificial legacy errors the same way callClassMethod does
          final LegacySignature annotation = method.getAnnotation(LegacySignature.class);
          final String name = annotation.name();
          final InvokeConfig invokeConfig = new InvokeConfig().setTarget(name);
          doInBlock(() -> {
             invokeConfig.clone().setInHandle(h).run();
             return null;
          });
       }

       /**
        * Execute block body, catch and re-throw legacy errors including converted from ordinary errors.
        *
        * @param  action
        *         the code to execute. Must return either an object instance or {@code null}
        *         for code returning nothing
        *
        * @return the result of the call
        *
        * @throws ErrorConditionException
        *         errors are not caught by this method
        * @throws LegacyErrorException
        *         legacy errors are not caught by this method
        */
       final static object<? extends _BaseObject_> doInBlock(final Supplier<object<? extends _BaseObject_>> action)
       throws ErrorConditionException,
              LegacyErrorException
       {
          final object<? extends LegacyError> error = new ObjectVar<>(LegacyError.class);
          final object<? extends _BaseObject_> result = new ObjectVar<>(_BaseObject_.class);

          doBlock(TransactionType.SUB,
                   "blockLabel0",
                   new OnPhrase[] { new OnPhrase(Condition.ERROR, Action.THROW, "blockLabel0") },
                   new Block((Init) () -> {
                      catchError(LegacyError.class,
                               lError -> error.assign(lError));
                   },
                            (Body) () -> {
                               final object<? extends _BaseObject_> value = action.get();
                               if (value != null)
                               {
                                  result.assign(value);
                               }
                            }));

          if (error._isValid())
          {
             throw new LegacyErrorException(error, false);
          }

          return result;
       }
    }