# object.java

    /*
    ** Module   : object.java
    ** Abstract : Wrapper class for all OO 4GL instance references.
    **
    ** Copyright (c) 2018-2025, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
    ** 001 GES 20181210 First version.
    ** 002 CA  20190219 Runtime implementation.
    ** 003 HC  20190701 instantiateDefault must yield the correct class type.
    ** 004 CA  20190710 Allow this instance to be assigned a ref directly.  Fixed issues related to
    **                  working with legacy OE classes for which FWD provides support.
    **     CA  20190719 Plain object instance does not do reference counting.
    **     HC  20190721 Fixed object type not set when reference assigned.
    ** 005 CA  20191002 Added assign(object), to better isolate this usage (compared to assign(BDT))
    **                  in FWD code.
    ** 006 ME  20200412 Update compare to use legacy toString for BaseObject.
    **     CA  20200427 Replaced isValid().booleanValue() calls with _isValid().
    **     GES 20200520 Fixed compareTo() to honor enums (or any other Comparable).
    **     GES 20200529 Added isTracked() and made all constructors safe for null input.
    **     GES 20200603 Moved BaseObject legacy class registration into a BaseObject static initializer.
    ** 007 IAS 20201007 Added Type enum
    **     OM  20201102 Overrode getTypeName().
    ** 008 ME  20201106 Delete the object reference when set to unknown (if valid, the destructor is called).
    **         20201111 Decrement reference instead of delete when object set to unknown.
    **         20201217 Revert compare method to only check if the reference is the same (eq <> Equal in 4GL)
    **     CA  20210213 Reverted ME/20201106 - only ObjectVar.setUnknown must decrement references.
    **     CA  20210305 The object resource ID as reported by toString() or used at the table field must be a
    **                  numeric value (as indexes are affected).
    **     ME  20210504 Added isIncompatibleTypesOnConversion override for invalid POLY conversion.
    **     CA  20210609 Reworked INPUT/INPUT-OUTPUT parameters to a new approach, where they are explicitly
    **                  initialized at the method's execution, and not at the caller's arguments.
    **     CA  20220304 Fixed 'invalid handle' error message text.
    **     AL2 20220319 Added value proxy check in assign.
    **     VVT 20221221 Serialization support added (see #4658).
    **     CA  20220520 Even when assigned to unknown, the object's legacy type must be set.
    **     CA  20220602 Added basic support for transport of object instances over appserver call.
    **     CA  20230110 Cache the helper for ProcedureManager, ObjectOps and others (as needed), to reduce
    **                  context-local lookup.
    ** 009 CA  20230215 'duplicate()' method returns the real type instead of BDT.
    ** 010 CA  20230731 Legacy ENUM is stored in a EnumObject instance - this ensures that when they are created,
    **                  no context is saved for them, as they are JVM-wide constants.
    ** 011 CA  20240324 Use logical constants for TRUE, FALSE, UNKNOWN, within internal FWD runtime.
    ** 012 CA  20250423 Added 'object(BDT)' constructor.
    ** 013 PBB 20250522 Fixed behavior for some weird BDT to object conversions.
    ** 014 AL2 20250530 Added getIndependentFromContext.
    */

    /*
    ** 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.io.*;
    import com.goldencode.p2j.oo.lang.*;

    /**
     * Wrapper class for all OO 4GL instance references.  This is needed for compatibility with
     * unknown value, assignment, parameter passing, DELETE, SESSION:FIRST-OBJECT/LAST-OBJECT and
     * UNDO.
     * <p>
     * TODO: throwing errors from an appserver to the client will serialize the legacy instance.
     */
    public class object<T extends _BaseObject_>
    extends BaseDataType
    {
       /** The contained object instance. <code>null</code> is unknown value. */
       protected T ref = null;

       /** The object's type. */
       private Class<T> type = null;

       /**
        * Helper to use the ObjectOps without any context local lookups.
        * <p>
        * WARNING: this instance is used only in {@link #_isValid()} and {@link #isUnknown()}.  These methods
        * are overridden in {@link EnumObject}.  Any other usage must take care of this, as the enum must have no
        * context saved when is created.
        */
       protected ObjectOps.ObjectHelper helper = null;

       /**
        * Default constructor.
        */
       public object()
       {
          helper = ObjectOps.getObjectHelper();
       }

       /**
        * Initialize this object reference, allowing only assignment to objects compatible with the
        * specified type.
        *
        * @param    type
        *           The type of references this object can hold.
        */
       public object(Class<? extends _BaseObject_> type)
       {
          this();

          initialize(type, null);
       }

       /**
        * Initialize this object with the given reference.
        *
        * @param    ref
        *           The reference.
        */
       public object(BaseDataType ref)
       {
          this();

          assign(ref);
       }

       /**
        * Initialize this object with the given reference.
        *
        * @param    ref
        *           The reference.
        */
       public object(T ref)
       {
          this();

          if (ref == null)
             return;

          initialize(ref.getClass(), ref);
       }

       /**
        * Initialize this object with the reference from the specified resource.
        *
        * @param    res
        *           The object resource.
        */
       public object(ObjectResource res)
       {
          this();

          if (res == null)
          {
             return;
          }

          T ref = (T) res.ref();

          if (ref == null)
          {
             return;
          }

          initialize(ref.getClass(), ref);
       }

       /**
        * Copy constructor.
        *
        * @param    other
        *           The object from which to copy.
        */
       public object(object<T> other)
       {
          this();

          // no need to avoid assignment if null, a straight copy is just as correct
          this.ref = other.ref;
          this.type = other.type;

          // TODO: validate type?
       }

       /**
        * Returns an ID for the resource-representation of this object's reference.
        *
        * @param    obj
        *           The object for which the resource ID is required.
        *
        * @return   See above.
        */
       public static long resourceId(object<? extends _BaseObject_> obj)
       {
          Long id = ObjectOps.isValid(obj.ref) ? handle.resourceId(ObjectOps.asResource(obj.ref)) : 0;

          return id;
       }

       /**
        * Get the type.
        *
        * @return   type
        */
       @Override
       public Type getType()
       {
          return Type.OBJECT;
       }

       /**
        * Resolve the legacy instance and build an object referencing it.
        *
        * @param    resId
        *           The resource ID.
        *
        * @return   The object reference.
        */
       public static object<? extends _BaseObject_> fromResourceId(long resId)
       {
          handle h = handle.fromResourceId(resId);
          return h._isValid() ? new object<>((ObjectResource) h.get()) : new object<>();
       }

       /**
        * Return the wrapped reference if this instance is not set to unknown value.
        *
        * @return   The contained reference or raise an error if this is unknown value.
        */
       public T ref()
       {
          if (isUnknown())
          {
             String msg = "Invalid handle.  Not initialized or points to a deleted object";
             ErrorManager.recordOrThrowError(3135, msg, false);

             // TODO: is there any scenario where we can actually return null in silent error mode?
             //       (If so, that is very bad.)
             return null;
          }

          return ref;
       }

       /**
        * Compares this instance with the specified instance and returns -1 if this instance is less than the
        * instance specified, 0 if the two instances are equal and 1 if this instance is greater than the
        * specified instance.  This is the implementation of the <code>Comparable</code> interface.
        * <p>
        * The algorithm will fail to give meaningful results in the case where one tries to sort against other
        * objects that do not represent compatible values.
        *
        * @param    obj
        *           The instance to compare against.
        *
        * @return   -1, 0, or 1 depending on if this instance is less than, equal to or greater (respectively)
        *           than the specified instance <code>obj</code>.
        */
       @Override
       public int compareTo(Object obj)
       {
          if (obj instanceof object)
          {
             object other = (object) obj;

             // isUnknown and isValid return the same (true/false) value when ref == null or ref has been deleted
             boolean u1 = isUnknown();
             boolean u2 = (other == null || other.isUnknown());

             // both are unknown, then we are equal
             if (u1 && u2)
             {
                return 0;
             }
             else if (u1)
             {
                return -1;
             }
             else if (u2)
             {
                return 1;
             }

             if (ref instanceof Comparable)
             {
                Comparable c = (Comparable) ref;

                return c.compareTo(other.ref);
             }
             else
             {
                return ref.equals(other.ref) ? 0 : 1;
             }
          }

          return -1;
       }

       /**
        * A minimal implementation which satisfies the need for a concrete method.
        *
        * @return  The hash code for this object instance.
        */
       @Override
       public int hashCode()
       {
          int result = 17;

          if (isUnknown())
          {
             return result;
          }

          result = 37 * result + ref.hashCode();

          return result;
       }

       /**
        * Set this instance {@link #ref} to the specified value, directly.
        * <p>
        * If <code>ref</code> is <code>null</code>, it will be set to unknown.
        * <p>
        * If the {@link #type} is not compatible with <code>ref</code>, an error condition is raised.
        *
        * @param    ref
        *           The instance to assign.
        */
       public void assign(_BaseObject_ ref)
       {
          assign(new object(ref));
       }

       /**
        * Sets the state (data and unknown value) of this instance based on the state of the passed
        * instance.
        * <p>
        * If the value is not of the same type, some form of automatic type conversion may occur, or
        * an error will be raised.
        * <p>
        * This variant is meant to handle the cases of built-in functions and methods in the 4GL
        * which have polymorphic return types (e.g. DYNAMIC-FUNCTION()). This should NOT be used for
        * non-polymorphic assignments.
        *
        * @param    value
        *           The instance from which to copy state.
        */
       @Override
       public void assign(BaseDataType value)
       {
          if (value != null)
          {
             value = value.val();
          }

          if (!(value instanceof object))
          {
             if ((value.isUnknown()         && !(value instanceof longchar)) ||
                (value instanceof character && !value.isUnknown() && ((character) value).getValue().isEmpty()) ||
                (value instanceof integer   && !value.isUnknown() && ((integer) value).intValue() == 0))
             {
                setUnknown();
             }
             else
             {
                incompatibleTypesOnConversion();
             }

             return;
          }

          assign((object<?>) value);
       }

       /**
        * Copy the reference from another object instance to this one.
        *
        * @param    value
        *           The instance from which to copy state.
        */
       public void assign(object<?> value)
       {
          // the value may be a proxy; make sure to unwrap and work with the real value
          if (BaseDataType.isProxy(value))
          {
             assign(value.val());
             return;
          }
          if (value.isUnknown())
          {
             // don't call setUnknown here
             ref = null;

             if (type == null)
             {
                type = (Class<T>) value.type;
             }
             else
             {
                // TODO: validate it?
             }

             return;
          }

          _BaseObject_ vref = value.ref;
          if (type != null && !type.isInstance(vref))
          {
             // must be a sub-class or the same as this one
             String lt1 = ObjectOps.getLegacyName(vref.getClass());
             String lt2 = ObjectOps.getLegacyName(type());
             ErrorManager.recordOrThrowError(13448,
                                             "A variable of class '" + lt1 + "' cannot be assigned " +
                                             "to a variable of class '" + lt2 + "'");

             // reference remains unchanged
             return;
          }

          set(vref);
       }

       /**
        * Modify the contained data of the instance to copy the instance data
        * from the given instance.  Generally, the class of the given instance
        * must match the class upon which the <code>assign</code> method is
        * called, although this is not a strict requirement.
        *
        * @param    old
        *           The backup instance from which to copy data.
        */
       @Override
       public void assign(Undoable old)
       {
          if (old instanceof BaseDataType)
          {
             assign((BaseDataType) old);
          }
          else
          {
             // TODO: error out?
          }
       }

       /**
        * Reports if this instance represents the <code>unknown value</code>.
        *
        * @return   <code>true</code> if this instance is set to the
        *           <code>unknown value</code>.
        */
       @Override
       public boolean isUnknown()
       {
          return !helper.isValid(ref);
       }

       /**
        * Determines if this instance is valid (to be used).
        *
        * @return   <code>true</code> if this instance can be used.
        */
       public logical isValid()
       {
          return logical.of(_isValid());
       }

       /**
        * Determines if this instance is valid (to be used).
        *
        * @return   <code>true</code> if this instance can be used.
        */
       public boolean _isValid()
       {
          return helper.isValid(ref);
       }

       /**
        * Reports if the given instance is managed as part of the legacy 4GL object life cycle. This
        * includes reference counting, linking in the SESSION object chain, managed construction and
        * destruction.
        *
        * @return   {@code true} if the instance is tracked and {@code false} if the instance exists
        *           outside of the OO 4GL life cycle mechanisms.
        */
       public boolean isTracked()
       {
          return ref != null && ref.isTracked();
       }

       /**
        * Sets the state of this instance's <code>unknown value</code> flag or state to
        * <code>true</code>.
        * <p>
        * <b>Warning: the data stored in this instance will be invalid after calling this method.</b>
        */
       @Override
       public void setUnknown()
       {
          ref = null;
       }

       /**
        * Does the same as standard <code>clone()</code> method but returns an
        * instance of <code>BaseDataType</code> and doesn't throw the
        * <code>CloneNotSupportedException</code>.
        *
        * @return   A clone of this instance.
        */
       @Override
       public object<T> duplicate()
       {
          return new object<>(this);
       }

       /**
        * Creates a new instance of the same type that represents the <code>unknown value</code>.
        *
        * @return   An instance that represents the <code>unknown value</code>.
        */
       @Override
       public BaseDataType instantiateUnknown()
       {
          return new object<>();
       }

       /**
        * Creates a string representation of the instance data using the given
        * format string.  If the instance represents the
        *  <code>unknown value</code>, a '?' will be returned.
        *
        * @param    fmt
        *           The format string to use.
        *
        * @return   The formatted string.
        */
       @Override
       public String toString(String fmt)
       {
          return toStringMessage();
       }

       /**
        * Creates a string representation of the instance data in a form that is
        * compatible with the <code>MESSAGE</code> language statement.  If the
        * instance represents the <code>unknown value</code>, a '?' will be
        * returned.
        *
        * @return   The 'message' formatted string.
        */
       @Override
       public String toStringMessage()
       {
          return isUnknown() ? "?" : ref.toLegacyString().toStringMessage();
       }

       /**
        * Creates a string representation of the instance data using the 'export'
        * format.  If the instance represents the <code>unknown value</code>, a
        * '?' will be returned.
        *
        * @return   The 'export' formatted string.
        */
       @Override
       public String toStringExport()
       {
          return toStringMessage();
       }

       /**
        * Return the default display format string for this type.
        *
        * @return   The default format string.
        */
       @Override
       public String defaultFormatString()
       {
          // objects can't be formatted
          return null;
       }

       /**
        * The object implements the writeExternal method to save its contents
        * by calling the methods of DataOutput for its primitive values or
        * calling the writeObject method of ObjectOutput for objects, strings,
        * and arrays.
        *
        * @serialData Overriding methods should use this tag to describe
        *             the data layout of this Externalizable object.
        *             List the sequence of element types and, if possible,
        *             relate the element to a public/protected field and/or
        *             method of this Externalizable class.
        *
        * @param out the stream to write the object to
        * @exception IOException Includes any I/O exceptions that may occur
        */
       @Override
       public void writeExternal(final ObjectOutput out)
       throws IOException
       {
          out.writeObject(type);
          out.writeObject(ref);
       }

       /**
        * The object implements the readExternal method to restore its
        * contents by calling the methods of DataInput for primitive
        * types and readObject for objects, strings and arrays.  The
        * readExternal method must read the values in the same sequence
        * and with the same types as were written by writeExternal.
        *
        * @param in the stream to read data from in order to restore the object
        * @exception IOException if I/O errors occur
        * @exception ClassNotFoundException If the class for an object being
        *              restored cannot be found.
        */
       @Override
       public void readExternal(final ObjectInput in)
       throws IOException,
              ClassNotFoundException
       {
          type = (Class<T>) in.readObject();
          ref = (T) in.readObject();
       }

       /**
        * Identify if this data is dependent upon the context local. This identifies
        * if the data is safe to be cached in cross-session places or the data should
        * not leak from the context. If is is not safe to be shared cross-session, then
        * this should return {@code null}. If other representation is suitable for caching,
        * then this can return another object that wraps internal values that are not
        * dependent upon the context (e.g. date, date-time, date-time-tz).
        *
        * @return   Always. {@code null}.
        */
       @Override
       public Object getIndependentFromContext()
       {
          return null;
       }

       /**
        * Set this object's reference and type from the given instance.
        *
        * @param    ref
        *           The object instance.
        */
       void set(_BaseObject_ ref)
       {
          this.ref = (T) ref;
          if (this.type == null && ref != null)
          {
             this.type = (Class<T>) ref.getClass();
          }
       }

       /**
        * Get the object's declared class.
        *
        * @return   The {@link #type}.
        */
       Class<T> type()
       {
          return type;
       }

       /**
        * Creates a new instance of the same type that represents the
        * default initialized value.
        *
        * @return An instance that represents the default value.
        */
       @Override
       public BaseDataType instantiateDefault()
       {
          object res = new object();
          res.type = type;
          return res;
       }

       /**
        * Decrement the reference counter for this instance.
        * <p>
        * No-op for internal object instances.
        */
       protected void decrement()
       {
          // no-op
       }

       /**
        * Increment the reference counter for this instance.
        * <p>
        * No-op for internal object instances.
        */
       protected void increment()
       {
          // no-op
       }

       /**
        * Initialize this object with the given reference.
        *
        * @param    type
        *           The type of references this object can hold.  It is safe to pass {@code null}.
        * @param    ref
        *           The reference.  It is safe to pass {@code null}.
        */
       private void initialize(Class<? extends _BaseObject_> type, T ref)
       {
          if (ref != null && type == null)
          {
             type = ref.getClass();
          }

          if (type != null)
          {
             // this will not increment the reference count
             this.type = (Class<T>) type;

             String clsName = ObjectOps.getLegacyName(type);

             if (clsName != null)
             {
                ObjectOps.registerClass(clsName, type);
             }
          }

          this.ref = ref;
       }

       /**
        * Obtain a short description of the current object/state to be used in debugging.
        *
        * @return  a short description of the current object/state.
        */
       @Override
       public String toString()
       {
          if (_isValid())
          {
             return ref.toLegacyString().getValue();
          }

          return super.toString();
       }

       @Override
       protected boolean isIncompatibleTypesOnConversion(BaseDataType value)
       {
          // invalid conversion is being thrown even if unknown
          if (value instanceof raw || value instanceof blob || (value instanceof raw && !value.isUnknown()))
          {
             incompatibleTypesOnConversion();
          }
          // conversion is not attempted
          else if (value instanceof clob || value instanceof handle || date.class.equals(value.getClass()) || value instanceof NumberType || value instanceof logical)
          {
             return true;
          }

          return super.isIncompatibleTypesOnConversion(value);
       }
    }