SystemRoleFactorySupport.java

  1. /*
  2.  * *************************************************************************************************************************************************************
  3.  *
  4.  * TheseFoolishThings: Miscellaneous utilities
  5.  * http://tidalwave.it/projects/thesefoolishthings
  6.  *
  7.  * Copyright (C) 2009 - 2025 by Tidalwave s.a.s. (http://tidalwave.it)
  8.  *
  9.  * *************************************************************************************************************************************************************
  10.  *
  11.  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
  12.  * You may obtain a copy of the License at
  13.  *
  14.  *     http://www.apache.org/licenses/LICENSE-2.0
  15.  *
  16.  * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  17.  * CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and limitations under the License.
  18.  *
  19.  * *************************************************************************************************************************************************************
  20.  *
  21.  * git clone https://bitbucket.org/tidalwave/thesefoolishthings-src
  22.  * git clone https://github.com/tidalwave-it/thesefoolishthings-src
  23.  *
  24.  * *************************************************************************************************************************************************************
  25.  */
  26. package it.tidalwave.role.spi;

  27. import java.lang.reflect.InvocationTargetException;
  28. import jakarta.annotation.Nonnull;
  29. import java.util.ArrayList;
  30. import java.util.Collection;
  31. import java.util.HashSet;
  32. import java.util.List;
  33. import java.util.Map;
  34. import java.util.Optional;
  35. import java.util.Set;
  36. import java.util.SortedSet;
  37. import java.util.TreeSet;
  38. import it.tidalwave.util.ContextManager;
  39. import it.tidalwave.util.annotation.VisibleForTesting;
  40. import it.tidalwave.role.impl.MultiMap;
  41. import it.tidalwave.role.impl.OwnerAndRole;
  42. import it.tidalwave.dci.annotation.DciRole;
  43. import lombok.extern.slf4j.Slf4j;
  44. import static java.util.Comparator.*;
  45. import static it.tidalwave.util.ShortNames.*;

  46. /***************************************************************************************************************************************************************
  47.  *
  48.  * A basic implementation of a {@link SystemRoleFactory}. This class must be specialized to:
  49.  *
  50.  * <ol>
  51.  * <li>discover roles (see {@link #scan(java.util.Collection)}</li>
  52.  * <li>associate roles to a datum (see {@link #findDatumTypesForRole(java.lang.Class)}</li>
  53.  * <li>associate roles to contexts (see {@link #findContextTypeForRole(java.lang.Class)}</li>
  54.  * <li>eventually retrieve beans to inject in created roles (see {@link #getBean(java.lang.Class)}</li>
  55.  * </ol>
  56.  *
  57.  * Specializations might use annotations or configuration files to accomplish these tasks.
  58.  *
  59.  * @author  Fabrizio Giudici
  60.  *
  61.  **************************************************************************************************************************************************************/
  62. @Slf4j
  63. public abstract class SystemRoleFactorySupport implements SystemRoleFactory
  64.   {
  65.     @VisibleForTesting final MultiMap<OwnerAndRole, Class<?>> roleMapByOwnerAndRole = new MultiMap<>();

  66.     // FIXME: use ConcurrentHashMap
  67.     @VisibleForTesting final Set<OwnerAndRole> alreadyScanned = new HashSet<>();

  68.     /***********************************************************************************************************************************************************
  69.      * {@inheritDoc}
  70.      **********************************************************************************************************************************************************/
  71.     @Override @Nonnull
  72.     public synchronized <T> List<T> findRoles (@Nonnull final Object datum, @Nonnull final Class<? extends T> roleType)
  73.       {
  74.         log.trace("findRoles({}, {})", shortId(datum), shortName(roleType));
  75.         final Class<?> datumType = findTypeOf(datum);
  76.         final List<T> roles = new ArrayList<>();
  77.         final var roleImplementationTypes = findRoleImplementationsFor(datumType, roleType);

  78.         outer:  for (final var roleImplementationType : roleImplementationTypes)
  79.           {
  80.             for (final var constructor : roleImplementationType.getDeclaredConstructors())
  81.               {
  82.                 log.trace(">>>> trying constructor {}", constructor);
  83.                 final var parameterTypes = constructor.getParameterTypes();
  84.                 Optional<?> context = Optional.empty();
  85.                 final var contextType = findContextTypeForRole(roleImplementationType);

  86.                 if (contextType.isPresent())
  87.                   {
  88.                     // With DI frameworks such as Spring it's better to avoid eager initializations of references
  89.                     final var contextManager = ContextManager.getInstance();
  90.                     log.trace(">>>> contexts: {}", shortIds(contextManager.getContexts()));
  91.                     context = contextManager.findContextOfType(contextType.get());

  92.                     if (context.isEmpty())
  93.                       {
  94.                         log.trace(">>>> role {} discarded, can't find context: {}",
  95.                                   shortName(roleImplementationType), shortName(contextType.get()));
  96.                         continue outer;
  97.                       }
  98.                   }

  99.                 try
  100.                   {
  101.                     final var params = getParameterValues(parameterTypes, datumType, datum, contextType, context);
  102.                     roles.add(roleType.cast(constructor.newInstance(params)));
  103.                     break;
  104.                   }
  105.                 catch (InstantiationException | IllegalAccessException
  106.                         | IllegalArgumentException | InvocationTargetException e)
  107.                   {
  108.                     log.error("Could not instantiate role of type " + roleImplementationType, e);
  109.                   }
  110.               }
  111.           }

  112.         if (log.isTraceEnabled())
  113.           {
  114.             log.trace(">>>> findRoles() returning: {}", shortIds(roles));
  115.           }

  116.         return roles;
  117.       }

  118.     /***********************************************************************************************************************************************************
  119.      * Prepare the constructor parameters out of the given expected types. Parameters will be eventually made of the
  120.      * given datum, context, and other objects returned by {@link #getBean(java.lang.Class)}.
  121.      *
  122.      * @param   parameterTypes      the expected types
  123.      * @param   datumClass          the type of the datum
  124.      * @param   datum               the datum
  125.      * @param   contextClass        the type of the context
  126.      * @param   context             the context
  127.      **********************************************************************************************************************************************************/
  128.     @Nonnull
  129.     private Object[] getParameterValues (@Nonnull final Class<?>[] parameterTypes,
  130.                                          @Nonnull final Class<?> datumClass,
  131.                                          @Nonnull final Object datum,
  132.                                          @Nonnull final Optional<Class<?>> contextClass,
  133.                                          @Nonnull final Optional<?> context)
  134.       {
  135.         final var values = new ArrayList<>();

  136.         for (final var parameterType : parameterTypes)
  137.           {
  138.             if (parameterType.isAssignableFrom(datumClass))
  139.               {
  140.                 values.add(datum);
  141.               }
  142.             else if (contextClass.isPresent() && parameterType.isAssignableFrom(contextClass.get()))
  143.               {
  144.                 values.add(context.orElse(null));
  145.               }
  146.             else // generic injection
  147.               {
  148.                 // FIXME: it's injecting null, but perhaps should it throw exception?
  149.                 values.add(getBean(parameterType).orElse(null));
  150.               }
  151.           }

  152.         log.trace(">>>> constructor parameters: {}", values);
  153.         return values.toArray();
  154.       }

  155.     /***********************************************************************************************************************************************************
  156.      * Finds the role implementations for the given owner type and role type. This method might discover new
  157.      * implementations that weren't found during the initial scan, since the initial scan can't go down in a
  158.      * hierarchy; that is, given a Base class or interface with some associated roles, it can't associate those roles
  159.      * to subclasses (or implementations) of Base. Now we can navigate up the hierarchy and complete the picture.
  160.      * Each new discovered role is added into the map, so the next time scanning will be faster.
  161.      *
  162.      * @param   datumType       the type of the datum
  163.      * @param   roleType        the type of the role to find
  164.      * @return                  the types of role implementations
  165.      **********************************************************************************************************************************************************/
  166.     @Nonnull
  167.     @VisibleForTesting synchronized <T> Set<Class<? extends T>> findRoleImplementationsFor (
  168.             @Nonnull final Class<?> datumType,
  169.             @Nonnull final Class<T> roleType)
  170.       {
  171.         final var datumAndRole = new OwnerAndRole(datumType, roleType);

  172.         if (!alreadyScanned.contains(datumAndRole))
  173.           {
  174.             alreadyScanned.add(datumAndRole);
  175.             final var before = new HashSet<>(roleMapByOwnerAndRole.getValues(datumAndRole));

  176.             for (final var superDatumAndRole : datumAndRole.getSuper())
  177.               {
  178.                 roleMapByOwnerAndRole.addAll(datumAndRole, roleMapByOwnerAndRole.getValues(superDatumAndRole));
  179.               }

  180.             final var after = new HashSet<>(roleMapByOwnerAndRole.getValues(datumAndRole));
  181.             logChanges(datumAndRole, before, after);
  182.           }

  183.         return (Set<Class<? extends T>>)(Set)roleMapByOwnerAndRole.getValues(datumAndRole);
  184.       }

  185.     /***********************************************************************************************************************************************************
  186.      * Scans all the given role implementation classes and build a map of roles by owner class.
  187.      *
  188.      * @param   roleImplementationTypes     the types of role implementations to scan
  189.      **********************************************************************************************************************************************************/
  190.     protected synchronized void scan (@Nonnull final Collection<Class<?>> roleImplementationTypes)
  191.       {
  192.         log.debug("scan({})", shortNames(roleImplementationTypes));

  193.         for (final var roleImplementationType : roleImplementationTypes)
  194.           {
  195.             for (final var datumType : findDatumTypesForRole(roleImplementationType))
  196.               {
  197.                 for (final var roleType : findAllImplementedInterfacesOf(roleImplementationType))
  198.                   {
  199.                     if (!"org.springframework.beans.factory.aspectj.ConfigurableObject".equals(roleType.getName()))
  200.                       {
  201.                         roleMapByOwnerAndRole.add(new OwnerAndRole(datumType, roleType), roleImplementationType);
  202.                       }
  203.                   }
  204.               }
  205.           }

  206.         logRoles();
  207.       }

  208.     /***********************************************************************************************************************************************************
  209.      * Finds all the interfaces implemented by a given class, including those eventually implemented by superclasses
  210.      * and interfaces that are indirectly implemented (e.g. C implements I1, I1 extends I2).
  211.      *
  212.      * @param  clazz    the class to inspect
  213.      * @return          the implemented interfaces
  214.      **********************************************************************************************************************************************************/
  215.     @Nonnull
  216.     @VisibleForTesting static SortedSet<Class<?>> findAllImplementedInterfacesOf (@Nonnull final Class<?> clazz)
  217.       {
  218.         final SortedSet<Class<?>> interfaces = new TreeSet<>(comparing(Class::getName));
  219.         interfaces.addAll(List.of(clazz.getInterfaces()));

  220.         for (final var interface_ : interfaces)
  221.           {
  222.             interfaces.addAll(findAllImplementedInterfacesOf(interface_));
  223.           }

  224.         if (clazz.getSuperclass() != null)
  225.           {
  226.             interfaces.addAll(findAllImplementedInterfacesOf(clazz.getSuperclass()));
  227.           }

  228.         return interfaces;
  229.       }

  230.     /***********************************************************************************************************************************************************
  231.      * Retrieves an extra bean.
  232.      *
  233.      * @param <T>           the static type of the bean
  234.      * @param beanType      the dynamic type of the bean
  235.      * @return              the bean
  236.      **********************************************************************************************************************************************************/
  237.     @Nonnull
  238.     protected <T> Optional<T> getBean (@Nonnull final Class<T> beanType)
  239.       {
  240.         return Optional.empty();
  241.       }

  242.     /***********************************************************************************************************************************************************
  243.      * Returns the type of the context associated to the given role implementation type.
  244.      *
  245.      * @param   roleImplementationType      the role type
  246.      * @return                              the context type
  247.      **********************************************************************************************************************************************************/
  248.     @Nonnull
  249.     protected Optional<Class<?>> findContextTypeForRole (@Nonnull final Class<?> roleImplementationType)
  250.       {
  251.         final var contextClass = roleImplementationType.getAnnotation(DciRole.class).context();
  252.         return (contextClass == DciRole.NoContext.class) ? Optional.empty() : Optional.of(contextClass);
  253.       }

  254.     /***********************************************************************************************************************************************************
  255.      * Returns the valid datum types for the given role implementation type.
  256.      *
  257.      * @param   roleImplementationType      the role type
  258.      * @return                              the datum types
  259.      **********************************************************************************************************************************************************/
  260.     @Nonnull
  261.     protected Class<?>[] findDatumTypesForRole (@Nonnull final Class<?> roleImplementationType)
  262.       {
  263.         return roleImplementationType.getAnnotation(DciRole.class).datumType();
  264.       }

  265.     /***********************************************************************************************************************************************************
  266.      **********************************************************************************************************************************************************/
  267.     private void logChanges (@Nonnull final OwnerAndRole ownerAndRole,
  268.                              @Nonnull final Set<Class<?>> before,
  269.                              @Nonnull final Set<Class<?>> after)
  270.       {
  271.         after.removeAll(before);

  272.         if (!after.isEmpty())
  273.           {
  274.             log.debug(">>>>>>> added implementations: {} -> {}", ownerAndRole, shortNames(after));

  275.             if (log.isTraceEnabled()) // yes, trace
  276.               {
  277.                 logRoles();
  278.               }
  279.           }
  280.       }

  281.     /***********************************************************************************************************************************************************
  282.      **********************************************************************************************************************************************************/
  283.     public void logRoles()
  284.       {
  285.         log.debug("Configured roles:");

  286.         final var entries = new ArrayList<>(roleMapByOwnerAndRole.entrySet());
  287.         entries.sort(comparing((Map.Entry<OwnerAndRole, Set<Class<?>>> e) -> e.getKey().getOwnerClass().getName())
  288.                                .thenComparing(e -> e.getKey().getRoleClass().getName()));

  289.         for (final var entry : entries)
  290.           {
  291.             log.debug(">>>> {}: {} -> {}",
  292.                       shortName(entry.getKey().getOwnerClass()),
  293.                       shortName(entry.getKey().getRoleClass()),
  294.                       shortNames(entry.getValue()));
  295.           }
  296.       }

  297.     /***********************************************************************************************************************************************************
  298.      * Returns the type of an object, taking care of mocks created by Mockito, for which the implemented interface is
  299.      * returned.
  300.      *
  301.      * @param  object   the object
  302.      * @return          the object type
  303.      **********************************************************************************************************************************************************/
  304.     @Nonnull
  305.     @VisibleForTesting static <T> Class<T> findTypeOf (@Nonnull final T object)
  306.       {
  307.         var ownerClass = object.getClass();

  308.         if (ownerClass.toString().contains("MockitoMock"))
  309.           {
  310.             ownerClass = ownerClass.getInterfaces()[0]; // 1st is the original class, 2nd is CGLIB proxy

  311.             if (log.isTraceEnabled())
  312.               {
  313.                 log.trace(">>>> owner is a mock {} implementing {}",
  314.                           shortName(ownerClass), shortNames(List.of(ownerClass.getInterfaces())));
  315.                 log.trace(">>>> owner class replaced with {}", shortName(ownerClass));
  316.               }
  317.           }

  318.         return (Class<T>)ownerClass;
  319.       }
  320.   }