ContextManager.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.util;

  27. import javax.annotation.Nonnull;
  28. import java.util.List;
  29. import java.util.Optional;
  30. import java.util.ServiceLoader;
  31. import java.util.function.Supplier;
  32. import it.tidalwave.role.spi.ContextManagerProvider;
  33. import static it.tidalwave.role.impl.ServiceLoaderLocator.lazySupplierOf;

  34. /***************************************************************************************************************************************************************
  35.  *
  36.  * A facility to register and unregister global and local DCI contexts.
  37.  *
  38.  * @author  Fabrizio Giudici
  39.  *
  40.  **************************************************************************************************************************************************************/
  41. public interface ContextManager
  42.   {
  43.     /***********************************************************************************************************************************************************
  44.      * A locator for the {@link ContextManager} which uses the {@link ServiceLoader} facility to be independent of
  45.      * any DI framework.
  46.      *
  47.      * This locator caches the internal reference and this is ok for production use; during tests, since multiple
  48.      * contexts are typically created and destroyed for each test, you should call {@link #reset()} after each test
  49.      * has been completed.
  50.      **********************************************************************************************************************************************************/
  51.     static class Inner
  52.       {
  53.         private static final LazySupplier<ContextManager> CONTEXT_MANAGER_REF =
  54.                 LazySupplier.of(() -> Inner.CONTEXT_MANAGER_PROVIDER_REF.get().getContextManager());

  55.         private static final LazySupplier<ContextManagerProvider> CONTEXT_MANAGER_PROVIDER_REF =
  56.                 lazySupplierOf(ContextManagerProvider.class);
  57.       }

  58.     /***********************************************************************************************************************************************************
  59.      * Returns a singleton instance.
  60.      *
  61.      * @return  the singleton instance
  62.      **********************************************************************************************************************************************************/
  63.     @Nonnull
  64.     public static ContextManager getInstance()
  65.       {
  66.         return Inner.CONTEXT_MANAGER_REF.get();
  67.       }

  68.     /***********************************************************************************************************************************************************
  69.      * <b>This method is for testing only.</b> Sets the global {@link ContextManagerProvider}. See note about
  70.      * {@link #reset()}.
  71.      *
  72.      * @param   provider    the provider
  73.      * @see     #reset()
  74.      **********************************************************************************************************************************************************/
  75.     public static void set (@Nonnull final ContextManagerProvider provider)
  76.       {
  77.         Inner.CONTEXT_MANAGER_REF.clear();
  78.         Inner.CONTEXT_MANAGER_PROVIDER_REF.set(provider);
  79.       }

  80.     /***********************************************************************************************************************************************************
  81.      * <b>This method is for testing only.</b> Resets the global {@link ContextManagerProvider}; it must be called
  82.      * at the test completion whenever {@link #set(ContextManagerProvider)} has been called, to avoid polluting the
  83.      * context of further tests.
  84.      *
  85.      * @see     #set(ContextManagerProvider)
  86.      **********************************************************************************************************************************************************/
  87.     public static void reset()
  88.       {
  89.         Inner.CONTEXT_MANAGER_REF.clear();
  90.         Inner.CONTEXT_MANAGER_PROVIDER_REF.clear();
  91.       }

  92.     @FunctionalInterface
  93.     public static interface RunnableWithException<E extends Throwable>
  94.       {
  95.         public void run()
  96.                 throws E;
  97.       }

  98.     @FunctionalInterface
  99.     public static interface SupplierWithException<T, E extends Throwable>
  100.       {
  101.         public T get()
  102.                 throws E;
  103.       }

  104.     /***********************************************************************************************************************************************************
  105.      * Returns the list of current contexts, ordered by their priority.
  106.      *
  107.      * @return  the list of current contexts
  108.      **********************************************************************************************************************************************************/
  109.     @Nonnull
  110.     public List<Object> getContexts();

  111.     /***********************************************************************************************************************************************************
  112.      * Finds a current context instance of the given type.
  113.      *
  114.      * @param   <T>                the static context type
  115.      * @param   contextType        the dynamic context type
  116.      * @return                     the requested context
  117.      **********************************************************************************************************************************************************/
  118.     @Nonnull
  119.     public <T> Optional<T> findContextOfType (@Nonnull Class<T> contextType);

  120.     /***********************************************************************************************************************************************************
  121.      * Adds a global context.
  122.      *
  123.      * @param  context             the new context
  124.      **********************************************************************************************************************************************************/
  125.     public void addGlobalContext (@Nonnull Object context);

  126.     /***********************************************************************************************************************************************************
  127.      * Removes a global context.
  128.      *
  129.      * @param  context            the context
  130.      **********************************************************************************************************************************************************/
  131.     public void removeGlobalContext (@Nonnull Object context);

  132.     /***********************************************************************************************************************************************************
  133.      * Adds a local context.
  134.      *
  135.      * @param  context            the new context
  136.      **********************************************************************************************************************************************************/
  137.     public void addLocalContext (@Nonnull Object context);

  138.     /***********************************************************************************************************************************************************
  139.      * Removes a local context.
  140.      *
  141.      * @param  context            the context
  142.      **********************************************************************************************************************************************************/
  143.     public void removeLocalContext (@Nonnull Object context);

  144.     /***********************************************************************************************************************************************************
  145.      * Runs a {@link Task} associated with a new local context.
  146.      *
  147.      * @param  <V>                the type of the returned value
  148.      * @param  <T>                the type of the exception that can be thrown
  149.      * @param  context            the context
  150.      * @param  task               the task
  151.      * @return                    the value produced by the task
  152.      * @throws T                  the exception(s) thrown by the task
  153.      * @deprecated Use {@link #runWithContexts(Runnable, Object...)} or {@link #runWithContexts(Supplier, Object...)}
  154.      **********************************************************************************************************************************************************/
  155.     @Deprecated
  156.     public default <V, T extends Throwable> V runWithContext (@Nonnull final Object context,
  157.                                                               @Nonnull final Task<V, T> task)
  158.       throws T
  159.       {
  160.         return runWithContexts(List.of(context), task);
  161.       }

  162.     /***********************************************************************************************************************************************************
  163.      * Runs a {@link Task} associated with a new bunch of local contexts.
  164.      *
  165.      * @param  <V>                the type of the returned value
  166.      * @param  <T>                the type of the exception that can be thrown
  167.      * @param  contexts           the contexts
  168.      * @param  task               the task
  169.      * @return                    the value produced by the task
  170.      * @throws T                  the exception(s) thrown by the task
  171.      * @deprecated Use {@link #runWithContexts(Runnable, Object...)} or {@link #runWithContexts(Supplier, Object...)}
  172.      **********************************************************************************************************************************************************/
  173.     @Deprecated
  174.     public default <V, T extends Throwable> V runWithContexts (@Nonnull final List<Object> contexts,
  175.                                                                @Nonnull final Task<V, T> task)
  176.       throws T
  177.       {
  178.         return runEWithContexts(task::run, contexts.toArray());
  179.       }

  180.     /***********************************************************************************************************************************************************
  181.      * Runs a task associated with a new local context. This variant fits functional interfaces.
  182.      *
  183.      * @param  <V>                the type of the returned value of the task
  184.      * @param  context            the context
  185.      * @param  task               the task
  186.      * @return                    the value produced by the task
  187.      * @deprecated Use {@link #runWithContexts(Runnable, Object...)} or {@link #runWithContexts(Supplier, Object...)}
  188.      **********************************************************************************************************************************************************/
  189.     @Deprecated
  190.     public default <V> V runWithContext (@Nonnull final Object context, @Nonnull final Supplier<V> task)
  191.       {
  192.         return runWithContexts(task, context);
  193.       }

  194.     /***********************************************************************************************************************************************************
  195.      * Runs a task associated with a new bunch of local contexts. This variant fits functional interfaces.
  196.      *
  197.      * @param  <V>                the type of the returned value
  198.      * @param  contexts           the contexts
  199.      * @param  task               the task
  200.      * @return                    the value produced by the task
  201.      * @deprecated Use {@link #runWithContexts(Runnable, Object...)} or {@link #runWithContexts(Supplier, Object...)}
  202.      **********************************************************************************************************************************************************/
  203.     @Deprecated
  204.     public default <V> V runWithContexts (@Nonnull final List<Object> contexts, @Nonnull final Supplier<V> task)
  205.       {
  206.         return runWithContexts(task, contexts.toArray());
  207.       }

  208.     /***********************************************************************************************************************************************************
  209.      * Calls a runnable with some local contexts. This method fits functional interfaces.
  210.      *
  211.      * @param   runnable          the runnable
  212.      * @param   contexts          the contexts
  213.      * @since   3.2-ALPHA-12
  214.      **********************************************************************************************************************************************************/
  215.     public default void runWithContexts (@Nonnull final Runnable runnable, @Nonnull final Object ... contexts)
  216.       {
  217.         final SupplierWithException<Void, RuntimeException> se = () ->{ runnable.run(); return null; };
  218.         runEWithContexts(se, contexts);
  219.       }

  220.     /***********************************************************************************************************************************************************
  221.      * Calls a supplier with some local contexts. This method fits functional interfaces.
  222.      *
  223.      * @param   <T>               the type of the result
  224.      * @param   supplier          the supplier
  225.      * @param   contexts          the contexts
  226.      * @return                    the value returned by the supplier
  227.      * @since   3.2-ALPHA-12
  228.      **********************************************************************************************************************************************************/
  229.     @Nonnull
  230.     public default <T> T runWithContexts (@Nonnull final Supplier<T> supplier, @Nonnull final Object ... contexts)
  231.       {
  232.         final SupplierWithException<T, RuntimeException> se = supplier::get;
  233.         return runEWithContexts(se, contexts);
  234.       }

  235.     /***********************************************************************************************************************************************************
  236.      * Calls a runnable with some local contexts. This method fits functional interfaces.
  237.      *
  238.      * @param   <E>               the type of the thrown exception
  239.      * @param   runnable          the runnable to call
  240.      * @param   contexts          the contexts
  241.      * @throws  E                 the original exception thrown by task
  242.      * @since   3.2-ALPHA-12
  243.      **********************************************************************************************************************************************************/
  244.     public default <E extends Throwable> void runEWithContexts (@Nonnull final RunnableWithException<E> runnable,
  245.                                                                 @Nonnull final Object ... contexts)
  246.       throws E
  247.       {
  248.         final SupplierWithException<Void, E> se = () ->{ runnable.run(); return null; };
  249.         runEWithContexts(se, contexts);
  250.       }

  251.     /***********************************************************************************************************************************************************
  252.      * Calls a task with some local contexts. This method fits functional interfaces.
  253.      *
  254.      * @param   <T>               the type of the returned value
  255.      * @param   <E>               the type of the thrown exception
  256.      * @param   task              the task to call
  257.      * @param   contexts          the contexts
  258.      * @return                    the value returned by the supplier
  259.      * @throws  E                 the original exception thrown by task
  260.      * @since   3.2-ALPHA-12
  261.      **********************************************************************************************************************************************************/
  262.     @Nonnull
  263.     public <T, E extends Throwable> T runEWithContexts (@Nonnull SupplierWithException<T, E> task,
  264.                                                         @Nonnull Object ... contexts)
  265.       throws E;

  266.     /***********************************************************************************************************************************************************
  267.      * Creates a binder that makes it possible to bind a local context by means of a try-with-resources instead of a
  268.      * try/finally.
  269.      *
  270.      * <pre>
  271.      * try (final ContextManager.Binder binder = contextManager.binder(context))
  272.      *   {
  273.      *     ...
  274.      *   }
  275.      * </pre>
  276.      *
  277.      * @param   contexts          the contexts
  278.      * @return                    a binder that can be used in try-with-resources
  279.      * @since   3.2-ALPHA-12
  280.      **********************************************************************************************************************************************************/
  281.     @Nonnull
  282.     public default Binder binder (@Nonnull final Object ... contexts)
  283.       {
  284.         return new Binder(this, contexts);
  285.       }

  286.     /***********************************************************************************************************************************************************
  287.      * Used by
  288.      * @since   3.2-ALPHA-12
  289.      **********************************************************************************************************************************************************/
  290.     public static class Binder implements AutoCloseable
  291.       {
  292.         @Nonnull
  293.         private final ContextManager contextManager;

  294.         @Nonnull
  295.         private final Object[] contexts;

  296.         private Binder (@Nonnull final ContextManager contextManager, @Nonnull final Object[] contexts)
  297.           {
  298.             this.contextManager = contextManager;
  299.             this.contexts = contexts;

  300.             for (final var context : contexts)
  301.               {
  302.                 this.contextManager.addLocalContext(context);
  303.               }
  304.           }

  305.         @Override
  306.         public void close()
  307.           {
  308.             for (final var context : contexts)
  309.               {
  310.                 this.contextManager.removeLocalContext(context);
  311.               }
  312.           }
  313.       }
  314.   }