# LocalSyncher.java

    /*
    ** Module   : LocalSyncher.java
    ** Abstract : Synchronizes a foreign association based on changes made to the referencing DMO
    **
    ** Copyright (c) 2006-2020, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- --JPRM-- ---------------------------------Description----------------------------------
    ** 001 ECF 20061113   @31139 Created initial version. Automatically
    **                           synchronizes the keys of a foreign
    **                           association based on changes made to legacy
    **                           key properties in the referencing DMO.
    ** 002 ECF 20070629   @35299 Minor optimization. Replaced StringBuffer
    **                           with StringBuilder.
    ** 003 ECF 20071219   @36579 Interim fix for retrieveForeignDMO(). This
    **                           method previously was acquiring an exclusive
    **                           lock on the foreign DMO, but no more than a
    **                           share lock is necessary. Further modification
    **                           to this method is necessary to prevent the
    **                           introduction of unnecessary contention.
    ** 004 ECF 20071228   @31139 Fixed retrieveForeignDMO() again. Actually,
    **                           retrieving the the foreign DMO with no lock
    **                           is sufficient. However, the problem of the
    **                           foreign record being deleted before the end
    **                           of the current session's transaction is a
    **                           problem that will have to be solved
    **                           elsewhere. ForeignNuller will have to be
    **                           aware of the uncommitted change, so that it
    **                           can properly null out this orphaned foreign
    **                           key.
    ** 005 GES 20090421   @41825 Matched utility class package change.
    ** 006 ECF 20131028          Import change.
    ** 007 OM  20191101          Used new persistence API.
    ** 008 ECF 20200919          API change.
    ** 009 ES  20250407          Use timeout parameter in the call to Persistence.load.
    */

    /*
    ** 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.persist;

    import java.lang.reflect.*;
    import java.util.*;
    import com.goldencode.p2j.persist.lock.*;
    import com.goldencode.p2j.persist.orm.*;
    import com.goldencode.util.*;

    /**
     * Automatically synchronizes both ends of a foreign key association, based
     * upon changes made to the values of DMO properties which participate in a
     * legacy foreign key.  This class drives synchronization when it is
     * triggered by changes to the DMO at the referencing, or "local" end of the
     * association.  In P2J, the association is actually bidirectional;  however,
     * in the database schema, the end of the association which stores the
     * foreign key determines which end is the referencing end and which is the
     * referent end.
     *
     * @see  AssociationSyncher
     * @see  ForeignResolver
     * @see  RelationInfo
     * @see  RecordBuffer
     */
    final class LocalSyncher
    extends AssociationSyncher
    {
       /** Object which resolves legacy keys to a foreign DMO instance */
       private final ForeignResolver resolver;

       /** Method used to retrieve foreign DMO from a local DMO */
       private final Method foreignGetter;

       /**
        * Constructor.
        *
        * @param   buffer
        *          Record buffer containing the DMO whose property change(s)
        *          will trigger synchronization attempts.
        * @param   info
        *          Foreign relation descriptor object.
        */
       LocalSyncher(RecordBuffer buffer, RelationInfo info)
       {
          super(buffer, info, info.getForeignClass());

          resolver = new ForeignResolver(info, buffer, false);

          String ifaceName = info.getForeignInterfaceName();
          String method = null;
          try
          {
             // Store foreign record setter method.
             Class<?> localIface = info.getLocalInterface();
             method = "get" + ifaceName + "Record";
             foreignGetter = localIface.getDeclaredMethod(method);
          }
          catch (NoSuchMethodException exc)
          {
             throw new IllegalArgumentException(
               "Invalid DMO class:  missing foreign getter [" +
               info.getLocalInterfaceName() +
               "." +
               method +
               "]");
          }
       }

       /**
        * Retrieve the set of property names which represent the columns which
        * comprise the legacy key joining two records.  Changes to these
        * properties trigger synchronization of the two ends of a foreign key
        * association.  A set is returned because legacy keys are often
        * composites of multiple columns.
        *
        * @return  Set of property names comprising the legacy key.  Although
        *          they should generally be the same as those of the referent end
        *          of the association, this implementation returns the property
        *          names associated with the referencing end.
        */
       protected Set<String> getLegacyKeys()
       {
          return resolver.getInfo().getLocalProperties();
       }

       /**
        * The local end of an association has changed.  Find the old foreign DMO
        * it referenced.  If different than the new foreign DMO provided,
        * dereference the local DMO from the old foreign DMO.
        *
        * @param   newLocalDMOs
        *          Set of zero or more local DMOs which are about to be updated
        *          with the new association.
        * @param   newForeignDMO
        *          Foreign DMO which is about to be updated with the new
        *          association.
        *
        * @throws  IllegalAccessException
        *          if an access error occurs while invoking a method using
        *          reflection.
        * @throws  InvocationTargetException
        *          if a method invoked using reflection throws an exception.
        */
       protected void preSynch(Set newLocalDMOs, Record newForeignDMO)
       throws IllegalAccessException,
              InvocationTargetException
       {
          Record localDMO = buffer.getCurrentRecord();
          Record foreignDMO = (Record) foreignGetter.invoke(localDMO);
          if (foreignDMO == null || foreignDMO.equals(newForeignDMO))
          {
             return;
          }

          helper.remove(foreignDMO, localDMO);
       }

       /**
        * Retrieve the set of DMOs which comprise the local end of the foreign
        * association.  In this implemenation, this will contain only the current
        * record of the buffer whose changes triggered synchronization.  It is
        * assumed that record is already exclusively locked, otherwise there
        * could not have been a property change to trigger synchronization.
        *
        * @return  Set of newly resolved local DMOs.  The set may be empty, but
        *          it will not be <code>null</code>.
        *
        * @throws  PersistenceException
        *          if there are any errors retrieving DMOs from the database.
        */
       protected Set<Record> retrieveLocalDMOs()
       throws PersistenceException
       {
          Record dmo = buffer.getCurrentRecord();

          return dmo == null ? new EmptySet<>() : Collections.singleton(dmo);
       }

       /**
        * Retrieve the DMO, if any, at the foreign end of the association.  The
        * record is resolved using the new property values of the underlying
        * buffer's current record.
        *
        * @return  Newly resolved foreign DMO, or <code>null</code> if none was
        *          available.
        *
        * @throws  PersistenceException
        *          if there are any errors retrieving the DMO from the database.
        */
       protected Record retrieveForeignDMO()
       throws PersistenceException
       {
          Long id = resolver.resolveForeign(buffer);
          Record dmo = null;

          if (id != null)
          {
             Class<? extends Record> foreignClass = resolver.getInfo().getForeignClass();
             Persistence persistence = buffer.getPersistence();
             long timeout = persistence.getTimeOut();
             dmo = persistence.load(foreignClass, id, LockType.NONE, timeout, false);
          }

          return dmo;
       }
    }