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.util.impl.MultiMap;
  41. import it.tidalwave.util.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: {}", shortName(roleImplementationType), shortName(contextType.get()));
  95.                         continue outer;
  96.                       }
  97.                   }

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

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

  114.         return roles;
  115.       }

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

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

  149.         log.trace(">>>> constructor parameters: {}", values);
  150.         return values.toArray();
  151.       }

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

  165.         if (!alreadyScanned.contains(datumAndRole))
  166.           {
  167.             alreadyScanned.add(datumAndRole);
  168.             final var before = new HashSet<>(roleMapByOwnerAndRole.getValues(datumAndRole));

  169.             for (final var superDatumAndRole : datumAndRole.getSuper())
  170.               {
  171.                 roleMapByOwnerAndRole.addAll(datumAndRole, roleMapByOwnerAndRole.getValues(superDatumAndRole));
  172.               }

  173.             final var after = new HashSet<>(roleMapByOwnerAndRole.getValues(datumAndRole));
  174.             logChanges(datumAndRole, before, after);
  175.           }

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

  178.     /***********************************************************************************************************************************************************
  179.      * Scans all the given role implementation classes and builds a map of roles by owner class.
  180.      * @param   roleImplementationTypes     the types of role implementations to scan
  181.      **********************************************************************************************************************************************************/
  182.     protected synchronized void scan (@Nonnull final Collection<Class<?>> roleImplementationTypes)
  183.       {
  184.         log.debug("scan({})", shortNames(roleImplementationTypes));

  185.         for (final var roleImplementationType : roleImplementationTypes)
  186.           {
  187.             for (final var datumType : findDatumTypesForRole(roleImplementationType))
  188.               {
  189.                 for (final var roleType : findAllImplementedInterfacesOf(roleImplementationType))
  190.                   {
  191.                     if (!"org.springframework.beans.factory.aspectj.ConfigurableObject".equals(roleType.getName()))
  192.                       {
  193.                         roleMapByOwnerAndRole.add(new OwnerAndRole(datumType, roleType), roleImplementationType);
  194.                       }
  195.                   }
  196.               }
  197.           }

  198.         logRoles();
  199.       }

  200.     /***********************************************************************************************************************************************************
  201.      * Finds all the interfaces implemented by a given class, including those eventually implemented by superclasses and interfaces that are indirectly
  202.      * implemented (e.g. C implements I1, I1 extends I2).
  203.      * @param  clazz    the class to inspect
  204.      * @return          the implemented interfaces
  205.      **********************************************************************************************************************************************************/
  206.     @Nonnull
  207.     @VisibleForTesting static SortedSet<Class<?>> findAllImplementedInterfacesOf (@Nonnull final Class<?> clazz)
  208.       {
  209.         final SortedSet<Class<?>> interfaces = new TreeSet<>(comparing(Class::getName));
  210.         interfaces.addAll(List.of(clazz.getInterfaces()));

  211.         for (final var interface_ : interfaces)
  212.           {
  213.             interfaces.addAll(findAllImplementedInterfacesOf(interface_));
  214.           }

  215.         if (clazz.getSuperclass() != null)
  216.           {
  217.             interfaces.addAll(findAllImplementedInterfacesOf(clazz.getSuperclass()));
  218.           }

  219.         return interfaces;
  220.       }

  221.     /***********************************************************************************************************************************************************
  222.      * Retrieves an extra bean.
  223.      * @param <T>                           the static type of the bean
  224.      * @param beanType                      the dynamic type of the bean
  225.      * @return                              the bean
  226.      **********************************************************************************************************************************************************/
  227.     @Nonnull
  228.     protected <T> Optional<T> getBean (@Nonnull final Class<T> beanType)
  229.       {
  230.         return Optional.empty();
  231.       }

  232.     /***********************************************************************************************************************************************************
  233.      * Returns the type of the context associated to the given role implementation type.
  234.      * @param   roleImplementationType      the role type
  235.      * @return                              the context type
  236.      **********************************************************************************************************************************************************/
  237.     @Nonnull
  238.     protected Optional<Class<?>> findContextTypeForRole (@Nonnull final Class<?> roleImplementationType)
  239.       {
  240.         final var contextClass = roleImplementationType.getAnnotation(DciRole.class).context();
  241.         return (contextClass == DciRole.NoContext.class) ? Optional.empty() : Optional.of(contextClass);
  242.       }

  243.     /***********************************************************************************************************************************************************
  244.      * Returns the valid datum types for the given role implementation type.
  245.      * @param   roleImplementationType      the role type
  246.      * @return                              the datum types
  247.      **********************************************************************************************************************************************************/
  248.     @Nonnull
  249.     protected Class<?>[] findDatumTypesForRole (@Nonnull final Class<?> roleImplementationType)
  250.       {
  251.         return roleImplementationType.getAnnotation(DciRole.class).datumType();
  252.       }

  253.     /***********************************************************************************************************************************************************
  254.      *
  255.      **********************************************************************************************************************************************************/
  256.     private void logChanges (@Nonnull final OwnerAndRole ownerAndRole, @Nonnull final Set<Class<?>> before, @Nonnull final Set<Class<?>> after)
  257.       {
  258.         after.removeAll(before);

  259.         if (!after.isEmpty())
  260.           {
  261.             log.debug(">>>>>>> added implementations: {} -> {}", ownerAndRole, shortNames(after));

  262.             if (log.isTraceEnabled()) // yes, trace
  263.               {
  264.                 logRoles();
  265.               }
  266.           }
  267.       }

  268.     /***********************************************************************************************************************************************************
  269.      *
  270.      **********************************************************************************************************************************************************/
  271.     public void logRoles()
  272.       {
  273.         log.debug("Configured roles:");
  274.         final var entries = new ArrayList<>(roleMapByOwnerAndRole.entrySet());
  275.         entries.sort(comparing((Map.Entry<OwnerAndRole, Set<Class<?>>> e) -> e.getKey().getOwnerClass().getName())
  276.                                .thenComparing(e -> e.getKey().getRoleClass().getName()));

  277.         for (final var entry : entries)
  278.           {
  279.             log.debug(">>>> {}: {} -> {}", shortName(entry.getKey().getOwnerClass()), shortName(entry.getKey().getRoleClass()), shortNames(entry.getValue()));
  280.           }
  281.       }

  282.     /***********************************************************************************************************************************************************
  283.      * Returns the type of object, taking care of mocks created by Mockito, for which the implemented interface is returned.
  284.      * @param  object   the object
  285.      * @return          the object type
  286.      **********************************************************************************************************************************************************/
  287.     @Nonnull
  288.     @VisibleForTesting static <T> Class<T> findTypeOf (@Nonnull final T object)
  289.       {
  290.         var ownerClass = object.getClass();

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

  294.             if (log.isTraceEnabled())
  295.               {
  296.                 log.trace(">>>> owner is a mock {} implementing {}", shortName(ownerClass), shortNames(List.of(ownerClass.getInterfaces())));
  297.                 log.trace(">>>> owner class replaced with {}", shortName(ownerClass));
  298.               }
  299.           }

  300.         return (Class<T>)ownerClass;
  301.       }
  302.   }