LegacyMap.java

/*
** Module   : LegacyMap.java
** Abstract : Implementation of the builtin class.
**
** Copyright (c) 2019-2023, Golden Code Development Corporation.
**
** -#- -I- --Date-- ---------------------------------------Description----------------------------------------
** 001 ME  20200427 First version, stubs taken by converting the skeleton using FWD.
** 002 CA  20210113 Renamed Iiterator.next to Iiterator.next_, to follow NameConverter's rules.
**                  Renamed clear() to clear_(), to follow NameConverter's rules.
**     ME  20210205 Removed getMap method from interface definition, this is FWD specific.
** 003 CA  20210221 Fixed 'qualified', 'extent' and 'returns' annotations at the legacy
**                  signature.
** 004 ME  20210325 Increment/decrement object references (key/value) when added/removed.
**     ME  20210521 Use a 'key' object with hashCode/equals overrides.
**     ME  20210902 Do not decrement reference for input parameter on remove.
**     ME  20210929 Fix return object on get/put/remove.
**     ME  20220402 Check for valid key using reference and fallback to legacy equals.
** 005 CA  20231113 The 'execute' method must be annotated with LegacySignature Type.Execute, and also can be
**                  dropped if is a no-op.
** 006 AL2 20240930 Made destructor call Clear. Added reference count management to Clear. 
*/

/*
** 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.oo.core.collections;

import com.goldencode.p2j.util.*;
import com.goldencode.p2j.util.BlockManager.Action;
import com.goldencode.p2j.util.BlockManager.Condition;
import com.goldencode.p2j.oo.core.Assert;
import com.goldencode.p2j.oo.lang.*;

import static com.goldencode.p2j.report.ReportConstants.*;
import static com.goldencode.p2j.util.BlockManager.*;
import static com.goldencode.p2j.util.InternalEntry.Type;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Business logic (converted to Java from the 4GL source code
 * in OpenEdge/Core/Collections/Map.cls).
 */
@LegacyResource(resource = "OpenEdge.Core.Collections.Map")
@LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
public class LegacyMap extends BaseObject implements com.goldencode.p2j.oo.core.collections.Imap
{
   private HashMap<object, object> map = new LinkedHashMap<object, object>();
   
   // 4GL BUG, size not reset on clear
   private int size = 0;

   @LegacySignature(type = Type.EXECUTE)
   public void __core_collections_LegacyMap_execute__()
   {
      onBlockLevel(Condition.ERROR, Action.THROW);
   }

   @LegacySignature(returns = "INTEGER", type = Type.GETTER, name = "Size")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public integer getSize()
   {
      return function(LegacyMap.class, this, "Size", integer.class, new Block((Body) () ->
      {
         returnNormal(new integer(size));
      }));
   }

   @LegacySignature(returns = "OBJECT", type = Type.GETTER, name = "Values", qualified = "OpenEdge.Core.Collections.ICollection")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public object<? extends com.goldencode.p2j.oo.core.collections.Icollection> getValues()
   {
      return function(LegacyMap.class, this, "Values", object.class, new Block((Body) () ->
      {
         returnNormal(ObjectOps.newInstance(ValueCollection.class, "III", new object(this),
                  new handle(new TransparentWrapper(map)), new character("ValueRef")));
      }));
   }

   @LegacySignature(returns = "OBJECT", type = Type.GETTER, name = "KeySet", qualified = "OpenEdge.Core.Collections.ISet")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public object<? extends com.goldencode.p2j.oo.core.collections.Iset> getKeySet()
   {
      return function(LegacyMap.class, this, "KeySet", object.class, new Block((Body) () ->
      {
         returnNormal(ObjectOps.newInstance(KeySet.class, "III", new object(this),
                  new handle(new TransparentWrapper(map)), new character("KeyRef")));
      }));
   }

   @LegacySignature(returns = "OBJECT", type = Type.GETTER, name = "EntrySet", qualified = "OpenEdge.Core.Collections.ISet")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public object<? extends com.goldencode.p2j.oo.core.collections.Iset> getEntrySet()
   {
      return function(LegacyMap.class, this, "EntrySet", object.class, new Block((Body) () ->
      {
         returnNormal(ObjectOps.newInstance(EntrySet.class, "III", new object(this),
                  new handle(new TransparentWrapper(map)), new character("KeyRef")));
      }));
   }

   @LegacySignature(type = Type.METHOD, name = "Clear")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public void clear_()
   {
      internalProcedure(LegacyMap.class, this, "Clear", new Block((Body) () ->
      {
         map.entrySet().forEach(entry -> {
            object<?> key = entry.getKey();
            object<?> value = entry.getValue();
            
            if (key != null && key._isValid())
            {
               ObjectOps.decrement(key.ref());
            }
            
            if (value != null && value._isValid())
            {
               ObjectOps.decrement(value.ref());
            }
         });
         
         map.clear();
      }));
   }

   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "Equals", parameters = {
            @LegacyParameter(name = "o", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   @Override
   public logical legacyEquals(
            final object<? extends com.goldencode.p2j.oo.lang._BaseObject_> other)
   {
      if (!other.isUnknown() && other.ref() instanceof Imap)
      {
         Imap omap = (Imap) other.ref();

         if (!omap.equals(this))
         {
            if (map.size() != omap.getSize().intValue())
               return new logical(false);

            for (Entry<object, object> e : map.entrySet())
            {
               if (!omap.containsKey(e.getKey()).booleanValue())
                  return new logical(false);

               object obj = omap.get(e.getKey());

               if ((obj.isUnknown() && !obj.equals(e.getValue()))
                        || (!obj.isUnknown() && e.getValue().isUnknown()))
                  return new logical(false);
            }
         }
         return new logical(true);
      }

      return new logical(false);
   }

   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "IsEmpty")
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public logical isEmpty()
   {
      return function(LegacyMap.class, this, "IsEmpty", logical.class, new Block((Body) () ->
      {
         returnNormal(new logical(map.isEmpty()));
      }));
   }

   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "ContainsKey", parameters = {
            @LegacyParameter(name = "poKey", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public logical containsKey(
            final object<? extends com.goldencode.p2j.oo.lang._BaseObject_> _poKey)
   {
      object<? extends com.goldencode.p2j.oo.lang._BaseObject_> poKey = TypeFactory
               .initInput(_poKey);

      return function(LegacyMap.class, this, "ContainsKey", logical.class, new Block((Body) () ->
      {
         returnNormal(new logical(_getKey(poKey) != null));
      }));
   }

   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "ContainsAllKeys", parameters = {
            @LegacyParameter(name = "poKeys", type = "OBJECT", qualified = "openedge.core.collections.icollection", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public logical containsAllKeys(
            final object<? extends com.goldencode.p2j.oo.core.collections.Icollection> _poKeys)
   {
      object<? extends com.goldencode.p2j.oo.core.collections.Icollection> poKeys = TypeFactory
               .initInput(_poKeys);

      return function(LegacyMap.class, this, "ContainsAllKeys", logical.class,
               new Block((Body) () ->
               {
                  Assert.notNull(poKeys, new character("Check keys"));

                  if (poKeys.ref().getSize().intValue() > getSize().intValue())
                     returnNormal(new logical(false));

                  object<? extends Iiterator> iterator = poKeys.ref().iterator();

                  while (iterator.ref().hasNext().booleanValue())
                  {
                     if (!containsKey(iterator.ref().next_()).booleanValue())
                        returnNormal(new logical(false));
                  }

                  returnNormal(new logical(true));
               }));
   }

   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "ContainsAllValues", parameters = {
            @LegacyParameter(name = "poValues", type = "OBJECT", qualified = "openedge.core.collections.icollection", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public logical containsAllValues(
            final object<? extends com.goldencode.p2j.oo.core.collections.Icollection> _poValues)
   {
      object<? extends com.goldencode.p2j.oo.core.collections.Icollection> poValues = TypeFactory
               .initInput(_poValues);

      return function(LegacyMap.class, this, "ContainsAllValues", logical.class,
               new Block((Body) () ->
               {
                  Assert.notNull(poValues, new character("Check values"));

                  if (poValues.ref().getSize().intValue() > getSize().intValue())
                     returnNormal(new logical(false));

                  object<? extends Iiterator> iterator = poValues.ref().iterator();

                  while (iterator.ref().hasNext().booleanValue())
                  {
                     if (!containsValue(iterator.ref().next_()).booleanValue())
                        returnNormal(new logical(false));
                  }

                  returnNormal(new logical(true));
               }));
   }

   @LegacySignature(returns = "LOGICAL", type = Type.METHOD, name = "ContainsValue", parameters = {
            @LegacyParameter(name = "poValue", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public logical containsValue(
            final object<? extends com.goldencode.p2j.oo.lang._BaseObject_> _poValue)
   {
      object<? extends com.goldencode.p2j.oo.lang._BaseObject_> poValue = TypeFactory
               .initInput(_poValue);

      return function(LegacyMap.class, this, "ContainsValue", logical.class,
               new Block((Body) () ->
               {
                  if (!poValue.isUnknown()) {
                     // walk through all values instead of containsValue 
                     // 4GL BUG: because if one of the values in the list is invalid error is thrown
                     for (object value : map.values())
                     {
                        if (value.ref().legacyEquals(poValue).booleanValue())
                           returnNormal(new logical(true));
                     }
                  } 
                  
                  returnNormal(new logical(false));
                  
               }));
   }

   @LegacySignature(returns = "OBJECT", type = Type.METHOD, name = "Get", qualified = "progress.lang.object", parameters = {
            @LegacyParameter(name = "poKey", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public object<? extends com.goldencode.p2j.oo.lang._BaseObject_> get(
            final object<? extends com.goldencode.p2j.oo.lang._BaseObject_> _poKey)
   {
      object<? extends com.goldencode.p2j.oo.lang._BaseObject_> poKey = TypeFactory
               .initInput(_poKey);
      object<? extends com.goldencode.p2j.oo.lang._BaseObject_> poRet = TypeFactory.object(_BaseObject_.class);
      
      return function(LegacyMap.class, this, "Get", object.class, new Block((Body) () ->
      {
         if (poKey._isValid())
         {
            object<? extends com.goldencode.p2j.oo.lang._BaseObject_> key = _getKey(poKey);
            
            if (key != null)
               poRet.assign(map.get(key));
         }
         returnNormal(poRet);
      }));
   }
   
   /**
    * Locate an key object in the map's key set, reference equality is used first and
    * fallback to object's legacy equals.
    * 
    * @param poKey the key
    * @return the key reference if found or null otherwise
    */
   private object<? extends com.goldencode.p2j.oo.lang._BaseObject_> _getKey(
            final object<? extends com.goldencode.p2j.oo.lang._BaseObject_> poKey)
   {
      if (map.containsKey(poKey)) {
         return poKey;
      }
      
      if (!map.isEmpty())
      {
         for (object<? extends com.goldencode.p2j.oo.lang._BaseObject_> key: map.keySet())
         {
            if (poKey.ref().legacyEquals(key).booleanValue())
            {
               return key;
            }
         }
      }
      
      return null;
   }

   @LegacySignature(returns = "OBJECT", type = Type.METHOD, name = "Put", qualified = "progress.lang.object", parameters = {
            @LegacyParameter(name = "poKey", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT"),
            @LegacyParameter(name = "poValue", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public object<? extends com.goldencode.p2j.oo.lang._BaseObject_> put(
            final object<? extends com.goldencode.p2j.oo.lang._BaseObject_> _poKey,
            final object<? extends com.goldencode.p2j.oo.lang._BaseObject_> _poValue)
   {
      object<? extends com.goldencode.p2j.oo.lang._BaseObject_> poKey = TypeFactory
               .initInput(_poKey);
      object<? extends com.goldencode.p2j.oo.lang._BaseObject_> poValue = TypeFactory
               .initInput(_poValue);
      object<? extends com.goldencode.p2j.oo.lang._BaseObject_> poRet = TypeFactory.object(_BaseObject_.class);
      
      return function(LegacyMap.class, this, "Put", object.class, new Block((Body) () ->
      {
         if (poKey.ref().equals(this))
            undoThrow(AppError.newInstance(new character("A Map cannot have itself as key.")));

         if (!poValue.isUnknown())
         {
            ObjectOps.increment(poValue.ref());
         }
         
         object<? extends com.goldencode.p2j.oo.lang._BaseObject_> key = _getKey(poKey);
         
         if (key != null) 
         {
            poRet.assign(map.put(key, poValue));
            if (!poRet.isUnknown())
            {
               ObjectOps.decrement(poRet.ref());
            }
         }
         else
         {
            map.put(poKey, poValue);
            ObjectOps.increment(poKey.ref());
            size++;
         }
         
         returnNormal(poRet);
      }));
   }

   @LegacySignature(type = Type.METHOD, name = "PutAll", parameters = {
            @LegacyParameter(name = "poMap", type = "OBJECT", qualified = "openedge.core.collections.imap", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public void putAll(final object<? extends com.goldencode.p2j.oo.core.collections.Imap> _poMap)
   {
      object<? extends com.goldencode.p2j.oo.core.collections.Imap> poMap = TypeFactory
               .initInput(_poMap);

      internalProcedure(LegacyMap.class, this, "PutAll", new Block((Body) () -> {
         Iiterator iterator = poMap.ref().getKeySet().ref().iterator().ref();

         while (iterator.hasNext().booleanValue())
         {
            object obj = iterator.next_();
            put(obj, poMap.ref().get(obj));
         }
      }));
   }

   @LegacySignature(returns = "OBJECT", type = Type.METHOD, name = "Remove", qualified = "progress.lang.object", parameters = {
            @LegacyParameter(name = "poKey", type = "OBJECT", qualified = "progress.lang.object", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public object<? extends com.goldencode.p2j.oo.lang._BaseObject_> remove(
            final object<? extends com.goldencode.p2j.oo.lang._BaseObject_> _poKey)
   {
      object<? extends com.goldencode.p2j.oo.lang._BaseObject_> poKey = TypeFactory
               .initInput(_poKey);
      object<? extends com.goldencode.p2j.oo.lang._BaseObject_> poRet = TypeFactory.object(_BaseObject_.class);
      
      return function(LegacyMap.class, this, "Remove", object.class, new Block((Body) () ->
      {
         if (!poKey.isValid().booleanValue())
            returnNormal(new object());

         object<? extends com.goldencode.p2j.oo.lang._BaseObject_> key = _getKey(poKey);
         
         if (key != null) 
         {
            poRet.assign(map.remove(key));
         
            ObjectOps.decrement(poRet.ref());
            ObjectOps.decrement(key.ref());
            
            size--;
         }
         
         returnNormal(poRet);
      }));
   }

   @LegacySignature(type = Type.METHOD, name = "RemoveAll", parameters = {
            @LegacyParameter(name = "poKeys", type = "OBJECT", qualified = "openedge.core.collections.icollection", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public void removeAll(
            final object<? extends com.goldencode.p2j.oo.core.collections.Icollection> _poKeys)
   {
      object<? extends com.goldencode.p2j.oo.core.collections.Icollection> poKeys = TypeFactory
               .initInput(_poKeys);

      internalProcedure(LegacyMap.class, this, "RemoveAll", new Block((Body) () ->
      {
         if (!poKeys.ref().isEmpty().booleanValue())
         {
            Iiterator iterator = poKeys.ref().iterator().ref();

            while (iterator.hasNext().booleanValue())
            {
               remove(iterator.next_());
            }
         }
      }));
   }

   @LegacySignature(type = Type.CONSTRUCTOR, parameters = {
            @LegacyParameter(name = "poMap", type = "OBJECT", qualified = "openedge.core.collections.imap", mode = "INPUT") })
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public void __core_collections_LegacyMap_constructor__(
            final object<? extends com.goldencode.p2j.oo.core.collections.Imap> _poMap)
   {
      object<? extends com.goldencode.p2j.oo.core.collections.Imap> poMap = TypeFactory
               .initInput(_poMap);

      internalProcedure(LegacyMap.class, this, "__core_collections_LegacyMap_constructor__",
               new Block((Body) () ->
               {
                  __lang_BaseObject_constructor__();
                  putAll(poMap);
               }));
   }

   @LegacySignature(type = Type.CONSTRUCTOR)
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public void __core_collections_LegacyMap_constructor__()
   {
      internalProcedure(LegacyMap.class, this, "__core_collections_LegacyMap_constructor__",
               new Block((Body) () ->
               {
                  __lang_BaseObject_constructor__();
               }));
   }

   @LegacySignature(type = Type.DESTRUCTOR)
   @LegacyResourceSupport(supportLvl = CVT_LVL_FULL | RT_LVL_FULL)
   public void __core_collections_LegacyMap_destructor__()
   {
      internalProcedure(LegacyMap.class, this, "__core_collections_LegacyMap_destructor__",
               new Block((Body) () ->
               {
                  this.clear_();
               }));
   }

   public Map<object, object> getMap()
   {
      return map;
   }
}