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.Collections;
  30. import java.util.Iterator;
  31. import java.util.List;
  32. import java.util.Objects;
  33. import java.util.ServiceLoader;
  34. import java.util.function.Supplier;
  35. import it.tidalwave.util.NotFoundException;
  36. import it.tidalwave.util.Task;
  37. import it.tidalwave.util.LazySupplier;
  38. import it.tidalwave.role.spi.ContextManagerProvider;
  39. import lombok.AccessLevel;
  40. import lombok.NoArgsConstructor;
  41. import lombok.extern.slf4j.Slf4j;

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

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

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

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

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

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

  113.         /***************************************************************************************************************
  114.          *
  115.          **************************************************************************************************************/
  116.         @Nonnull
  117.         private static ContextManagerProvider findContextManagerProvider()
  118.           {
  119.             final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  120.             final Iterator<ContextManagerProvider> i =
  121.                     ServiceLoader.load(ContextManagerProvider.class, classLoader).iterator();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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