ContextManager.java

  1. /*
  2.  * *********************************************************************************************************************
  3.  *
  4.  * TheseFoolishThings: Miscellaneous utilities
  5.  * http://tidalwave.it/projects/thesefoolishthings
  6.  *
  7.  * Copyright (C) 2009 - 2023 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
  12.  * the License. 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
  17.  * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the
  18.  * specific language governing permissions and limitations under the License.
  19.  *
  20.  * *********************************************************************************************************************
  21.  *
  22.  * git clone https://bitbucket.org/tidalwave/thesefoolishthings-src
  23.  * git clone https://github.com/tidalwave-it/thesefoolishthings-src
  24.  *
  25.  * *********************************************************************************************************************
  26.  */
  27. package it.tidalwave.role;

  28. import javax.annotation.Nonnull;
  29. import java.util.List;
  30. import java.util.Objects;
  31. import java.util.ServiceLoader;
  32. import java.util.function.Supplier;
  33. import it.tidalwave.util.NotFoundException;
  34. import it.tidalwave.util.Task;
  35. import it.tidalwave.util.LazySupplier;
  36. import it.tidalwave.role.spi.ContextManagerProvider;
  37. import lombok.AccessLevel;
  38. import lombok.NoArgsConstructor;
  39. import lombok.extern.slf4j.Slf4j;

  40. /***********************************************************************************************************************
  41.  *
  42.  * A facility to register and unregister global and local DCI contexts.
  43.  *
  44.  * @author  Fabrizio Giudici
  45.  *
  46.  **********************************************************************************************************************/
  47. public interface ContextManager
  48.   {
  49.     /*******************************************************************************************************************
  50.      *
  51.      * A locator for the {@link ContextManager} which uses the {@link ServiceLoader} facility to be independent of
  52.      * any DI framework.
  53.      *
  54.      * This locator caches the internal reference and this is ok for production use; during tests, since multiple
  55.      * contexts are typically created and destroyed for each test, you should call {@link #reset()} after each test
  56.      * has been completed.
  57.      *
  58.      ******************************************************************************************************************/
  59.     @Slf4j @NoArgsConstructor(access = AccessLevel.PRIVATE)
  60.     public static final class Locator
  61.       {
  62.         private static final LazySupplier<ContextManager> CONTEXT_MANAGER_REF =
  63.                 LazySupplier.of(Locator::findContextManager);

  64.         private static final LazySupplier<ContextManagerProvider> CONTEXT_MANAGER_PROVIDER_REF =
  65.                 LazySupplier.of(Locator::findContextManagerProvider);

  66.         /***************************************************************************************************************
  67.          *
  68.          **************************************************************************************************************/
  69.         @Nonnull
  70.         public static ContextManager find()
  71.           {
  72.             return CONTEXT_MANAGER_REF.get();
  73.           }

  74.         /***************************************************************************************************************
  75.          *
  76.          * <b>This method is for testing only.</b> Sets the global {@link ContextManagerProvider}. See note about
  77.          * {@link #reset()}.
  78.          *
  79.          * @param   provider    the provider
  80.          * @see     #reset()
  81.          *
  82.          **************************************************************************************************************/
  83.         public static void set (@Nonnull final ContextManagerProvider provider)
  84.           {
  85.             CONTEXT_MANAGER_REF.clear();
  86.             CONTEXT_MANAGER_PROVIDER_REF.set(provider);
  87.           }

  88.         /***************************************************************************************************************
  89.          *
  90.          * <b>This method is for testing only.</b> Resets the global {@link ContextManagerProvider}; it must be called
  91.          * at the test completion whenever {@link #set(ContextManagerProvider)} has been called, to avoid polluting the
  92.          * context of further tests.
  93.          *
  94.          * @see     #set(ContextManagerProvider)
  95.          *
  96.          **************************************************************************************************************/
  97.         public static void reset()
  98.           {
  99.             CONTEXT_MANAGER_REF.clear();
  100.             CONTEXT_MANAGER_PROVIDER_REF.clear();
  101.           }

  102.         /***************************************************************************************************************
  103.          *
  104.          **************************************************************************************************************/
  105.         @Nonnull
  106.         private static ContextManager findContextManager()
  107.           {
  108.             return Objects.requireNonNull(CONTEXT_MANAGER_PROVIDER_REF.get().getContextManager(),
  109.                                           "Cannot find ContextManager");
  110.           }

  111.         /***************************************************************************************************************
  112.          *
  113.          **************************************************************************************************************/
  114.         @SuppressWarnings("ConstantValue")
  115.         @Nonnull
  116.         private static ContextManagerProvider findContextManagerProvider()
  117.           {
  118.             final var classLoader = Thread.currentThread().getContextClassLoader();
  119.             final var i =
  120.                     ServiceLoader.load(ContextManagerProvider.class, classLoader).iterator();

  121.             if (!i.hasNext())
  122.               {
  123.                 throw new RuntimeException("No ServiceProvider for ContextManagerProvider");
  124.               }

  125.             final var contextManagerProvider = Objects.requireNonNull(i.next(),
  126.                                                                       "contextManagerProvider is null");
  127.             assert contextManagerProvider != null; // for SpotBugs
  128.             log.info("ContextManagerProvider instantiated from META-INF: {}", contextManagerProvider);
  129.             return contextManagerProvider;
  130.           }
  131.       }

  132.     @FunctionalInterface
  133.     public static interface RunnableWithException<E extends Throwable>
  134.       {
  135.         public void run()
  136.                 throws E;
  137.       }

  138.     @FunctionalInterface
  139.     public static interface SupplierWithException<T, E extends Throwable>
  140.       {
  141.         public T get()
  142.                 throws E;
  143.       }

  144.     /*******************************************************************************************************************
  145.      *
  146.      * Returns the list of current contexts, ordered by their priority.
  147.      *
  148.      * @return  the list of current contexts
  149.      *
  150.      ******************************************************************************************************************/
  151.     @Nonnull
  152.     public List<Object> getContexts();

  153.     /*******************************************************************************************************************
  154.      *
  155.      * Finds a current context instance of the given type.
  156.      *
  157.      * @param   <T>                the static context type
  158.      * @param   contextType        the dynamic context type
  159.      * @return                     the requested context
  160.      * @throws  NotFoundException  if no context of that type is found
  161.      *
  162.      ******************************************************************************************************************/
  163.     @Nonnull
  164.     public <T> T findContextOfType (@Nonnull Class<T> contextType)
  165.       throws NotFoundException;

  166.     /*******************************************************************************************************************
  167.      *
  168.      * Adds a global context.
  169.      *
  170.      * @param  context             the new context
  171.      *
  172.      ******************************************************************************************************************/
  173.     public void addGlobalContext (@Nonnull Object context);

  174.     /*******************************************************************************************************************
  175.      *
  176.      * Removes a global context.
  177.      *
  178.      * @param  context            the context
  179.      *
  180.      ******************************************************************************************************************/
  181.     public void removeGlobalContext (@Nonnull Object context);

  182.     /*******************************************************************************************************************
  183.      *
  184.      * Adds a local context.
  185.      *
  186.      * @param  context            the new context
  187.      *
  188.      ******************************************************************************************************************/
  189.     public void addLocalContext (@Nonnull Object context);

  190.     /*******************************************************************************************************************
  191.      *
  192.      * Removes a local context.
  193.      *
  194.      * @param  context            the context
  195.      *
  196.      ******************************************************************************************************************/
  197.     public void removeLocalContext (@Nonnull Object context);

  198.     /*******************************************************************************************************************
  199.      *
  200.      * Runs a {@link Task} associated with a new local context.
  201.      *
  202.      * @param  <V>                the type of the returned value
  203.      * @param  <T>                the type of the exception that can be thrown
  204.      * @param  context            the context
  205.      * @param  task               the task
  206.      * @return                    the value produced by the task
  207.      * @throws T                  the exception(s) thrown by the task
  208.      * @deprecated Use {@link #runWithContexts(Runnable, Object...)} or {@link #runWithContexts(Supplier, Object...)}
  209.      *
  210.      ******************************************************************************************************************/
  211.     @Deprecated
  212.     public default <V, T extends Throwable> V runWithContext (@Nonnull final Object context,
  213.                                                               @Nonnull final Task<V, T> task)
  214.       throws T
  215.       {
  216.         return runWithContexts(List.of(context), task);
  217.       }

  218.     /*******************************************************************************************************************
  219.      *
  220.      * Runs a {@link Task} associated with a new bunch of local contexts.
  221.      *
  222.      * @param  <V>                the type of the returned value
  223.      * @param  <T>                the type of the exception that can be thrown
  224.      * @param  contexts           the contexts
  225.      * @param  task               the task
  226.      * @return                    the value produced by the task
  227.      * @throws T                  the exception(s) thrown by the task
  228.      * @deprecated Use {@link #runWithContexts(Runnable, Object...)} or {@link #runWithContexts(Supplier, Object...)}
  229.      *
  230.      ******************************************************************************************************************/
  231.     @Deprecated
  232.     public default <V, T extends Throwable> V runWithContexts (@Nonnull final List<Object> contexts,
  233.                                                                @Nonnull final Task<V, T> task)
  234.       throws T
  235.       {
  236.         return runEWithContexts(task::run, contexts.toArray());
  237.       }

  238.     /*******************************************************************************************************************
  239.      *
  240.      * Runs a task associated with a new local context. This variant fits functional interfaces.
  241.      *
  242.      * @param  <V>                the type of the returned value of the task
  243.      * @param  context            the context
  244.      * @param  task               the task
  245.      * @return                    the value produced by the task
  246.      * @deprecated Use {@link #runWithContexts(Runnable, Object...)} or {@link #runWithContexts(Supplier, Object...)}
  247.      *
  248.      ******************************************************************************************************************/
  249.     @Deprecated
  250.     public default <V> V runWithContext (@Nonnull final Object context, @Nonnull final Supplier<V> task)
  251.       {
  252.         return runWithContexts(task, context);
  253.       }

  254.     /*******************************************************************************************************************
  255.      *
  256.      * Runs a task associated with a new bunch of local contexts. This variant fits functional interfaces.
  257.      *
  258.      * @param  <V>                the type of the returned value
  259.      * @param  contexts           the contexts
  260.      * @param  task               the task
  261.      * @return                    the value produced by the task
  262.      * @deprecated Use {@link #runWithContexts(Runnable, Object...)} or {@link #runWithContexts(Supplier, Object...)}
  263.      *
  264.      ******************************************************************************************************************/
  265.     @Deprecated
  266.     public default <V> V runWithContexts (@Nonnull final List<Object> contexts, @Nonnull final Supplier<V> task)
  267.       {
  268.         return runWithContexts(task, contexts.toArray());
  269.       }

  270.     /*******************************************************************************************************************
  271.      *
  272.      * Calls a runnable with some local contexts. This method fits functional interfaces.
  273.      *
  274.      * @param   runnable          the runnable
  275.      * @param   contexts          the contexts
  276.      * @since   3.2-ALPHA-12
  277.      *
  278.      ******************************************************************************************************************/
  279.     public default void runWithContexts (@Nonnull final Runnable runnable, @Nonnull final Object ... contexts)
  280.       {
  281.         final SupplierWithException<Void, RuntimeException> se = () ->{ runnable.run(); return null; };
  282.         runEWithContexts(se, contexts);
  283.       }

  284.     /*******************************************************************************************************************
  285.      *
  286.      * Calls a supplier with some local contexts. This method fits functional interfaces.
  287.      *
  288.      * @param   <T>               the type of the result
  289.      * @param   supplier          the supplier
  290.      * @param   contexts          the contexts
  291.      * @return                    the value returned by the supplier
  292.      * @since   3.2-ALPHA-12
  293.      *
  294.      ******************************************************************************************************************/
  295.     @Nonnull
  296.     public default <T> T runWithContexts (@Nonnull final Supplier<T> supplier, @Nonnull final Object ... contexts)
  297.       {
  298.         final SupplierWithException<T, RuntimeException> se = supplier::get;
  299.         return runEWithContexts(se, contexts);
  300.       }

  301.     /*******************************************************************************************************************
  302.      *
  303.      * Calls a runnable with some local contexts. This method fits functional interfaces.
  304.      *
  305.      * @param   <E>               the type of the thrown exception
  306.      * @param   runnable          the runnable to call
  307.      * @param   contexts          the contexts
  308.      * @throws  E                 the original exception thrown by task
  309.      * @since   3.2-ALPHA-12
  310.      *
  311.      ******************************************************************************************************************/
  312.     public default <E extends Throwable> void runEWithContexts (@Nonnull final RunnableWithException<E> runnable,
  313.                                                                 @Nonnull final Object ... contexts)
  314.       throws E
  315.       {
  316.         final SupplierWithException<Void, E> se = () ->{ runnable.run(); return null; };
  317.         runEWithContexts(se, contexts);
  318.       }

  319.     /*******************************************************************************************************************
  320.      *
  321.      * Calls a task with some local contexts. This method fits functional interfaces.
  322.      *
  323.      * @param   <T>               the type of the returned value
  324.      * @param   <E>               the type of the thrown exception
  325.      * @param   task              the task to call
  326.      * @param   contexts          the contexts
  327.      * @return                    the value returned by the supplier
  328.      * @throws  E                 the original exception thrown by task
  329.      * @since   3.2-ALPHA-12
  330.      *
  331.      ******************************************************************************************************************/
  332.     @Nonnull
  333.     public <T, E extends Throwable> T runEWithContexts (@Nonnull SupplierWithException<T, E> task,
  334.                                                         @Nonnull Object ... contexts)
  335.       throws E;

  336.     /*******************************************************************************************************************
  337.      *
  338.      * Creates a binder that makes it possible to bind a local context by means of a try-with-resources instead of a
  339.      * try/finally.
  340.      *
  341.      * <pre>
  342.      * try (final ContextManager.Binder binder = contextManager.binder(context))
  343.      *   {
  344.      *     ...
  345.      *   }
  346.      * </pre>
  347.      *
  348.      * @param   contexts          the contexts
  349.      * @return                    a binder that can be used in try-with-resources
  350.      * @since   3.2-ALPHA-12
  351.      *
  352.      ******************************************************************************************************************/
  353.     @Nonnull
  354.     public default Binder binder (@Nonnull final Object ... contexts)
  355.       {
  356.         return new Binder(this, contexts);
  357.       }

  358.     /*******************************************************************************************************************
  359.      *
  360.      * Used by
  361.      * @since   3.2-ALPHA-12
  362.      *
  363.      ******************************************************************************************************************/
  364.     public static class Binder implements AutoCloseable
  365.       {
  366.         @Nonnull
  367.         private final ContextManager contextManager;

  368.         @Nonnull
  369.         private final Object[] contexts;

  370.         private Binder (@Nonnull final ContextManager contextManager, @Nonnull final Object[] contexts)
  371.           {
  372.             this.contextManager = contextManager;
  373.             this.contexts = contexts;

  374.             for (final var context : contexts)
  375.               {
  376.                 this.contextManager.addLocalContext(context);
  377.               }
  378.           }

  379.         @Override
  380.         public void close()
  381.           {
  382.             for (final var context : contexts)
  383.               {
  384.                 this.contextManager.removeLocalContext(context);
  385.               }
  386.           }
  387.       }
  388.   }