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

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

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

  58.         private static final LazySupplier<ContextManagerProvider> CONTEXT_MANAGER_PROVIDER_REF =
  59.                 lazySupplierOf(ContextManagerProvider.class);
  60.       }

  61.     /*******************************************************************************************************************
  62.      *
  63.      ******************************************************************************************************************/
  64.     @Nonnull
  65.     public static ContextManager getInstance()
  66.       {
  67.         return Inner.CONTEXT_MANAGER_REF.get();
  68.       }

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

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

  97.     @FunctionalInterface
  98.     public static interface RunnableWithException<E extends Throwable>
  99.       {
  100.         public void run()
  101.                 throws E;
  102.       }

  103.     @FunctionalInterface
  104.     public static interface SupplierWithException<T, E extends Throwable>
  105.       {
  106.         public T get()
  107.                 throws E;
  108.       }

  109.     /*******************************************************************************************************************
  110.      *
  111.      * Returns the list of current contexts, ordered by their priority.
  112.      *
  113.      * @return  the list of current contexts
  114.      *
  115.      ******************************************************************************************************************/
  116.     @Nonnull
  117.     public List<Object> getContexts();

  118.     /*******************************************************************************************************************
  119.      *
  120.      * Finds a current context instance of the given type.
  121.      *
  122.      * @param   <T>                the static context type
  123.      * @param   contextType        the dynamic context type
  124.      * @return                     the requested context
  125.      *
  126.      ******************************************************************************************************************/
  127.     @Nonnull
  128.     public <T> Optional<T> findContextOfType (@Nonnull Class<T> contextType);

  129.     /*******************************************************************************************************************
  130.      *
  131.      * Adds a global context.
  132.      *
  133.      * @param  context             the new context
  134.      *
  135.      ******************************************************************************************************************/
  136.     public void addGlobalContext (@Nonnull Object context);

  137.     /*******************************************************************************************************************
  138.      *
  139.      * Removes a global context.
  140.      *
  141.      * @param  context            the context
  142.      *
  143.      ******************************************************************************************************************/
  144.     public void removeGlobalContext (@Nonnull Object context);

  145.     /*******************************************************************************************************************
  146.      *
  147.      * Adds a local context.
  148.      *
  149.      * @param  context            the new context
  150.      *
  151.      ******************************************************************************************************************/
  152.     public void addLocalContext (@Nonnull Object context);

  153.     /*******************************************************************************************************************
  154.      *
  155.      * Removes a local context.
  156.      *
  157.      * @param  context            the context
  158.      *
  159.      ******************************************************************************************************************/
  160.     public void removeLocalContext (@Nonnull Object context);

  161.     /*******************************************************************************************************************
  162.      *
  163.      * Runs a {@link Task} associated with a new local context.
  164.      *
  165.      * @param  <V>                the type of the returned value
  166.      * @param  <T>                the type of the exception that can be thrown
  167.      * @param  context            the context
  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.      ******************************************************************************************************************/
  174.     @Deprecated
  175.     public default <V, T extends Throwable> V runWithContext (@Nonnull final Object context,
  176.                                                               @Nonnull final Task<V, T> task)
  177.       throws T
  178.       {
  179.         return runWithContexts(List.of(context), task);
  180.       }

  181.     /*******************************************************************************************************************
  182.      *
  183.      * Runs a {@link Task} associated with a new bunch of local contexts.
  184.      *
  185.      * @param  <V>                the type of the returned value
  186.      * @param  <T>                the type of the exception that can be thrown
  187.      * @param  contexts           the contexts
  188.      * @param  task               the task
  189.      * @return                    the value produced by the task
  190.      * @throws T                  the exception(s) thrown by the task
  191.      * @deprecated Use {@link #runWithContexts(Runnable, Object...)} or {@link #runWithContexts(Supplier, Object...)}
  192.      *
  193.      ******************************************************************************************************************/
  194.     @Deprecated
  195.     public default <V, T extends Throwable> V runWithContexts (@Nonnull final List<Object> contexts,
  196.                                                                @Nonnull final Task<V, T> task)
  197.       throws T
  198.       {
  199.         return runEWithContexts(task::run, contexts.toArray());
  200.       }

  201.     /*******************************************************************************************************************
  202.      *
  203.      * Runs a task associated with a new local context. This variant fits functional interfaces.
  204.      *
  205.      * @param  <V>                the type of the returned value of the task
  206.      * @param  context            the context
  207.      * @param  task               the task
  208.      * @return                    the value produced by the task
  209.      * @deprecated Use {@link #runWithContexts(Runnable, Object...)} or {@link #runWithContexts(Supplier, Object...)}
  210.      *
  211.      ******************************************************************************************************************/
  212.     @Deprecated
  213.     public default <V> V runWithContext (@Nonnull final Object context, @Nonnull final Supplier<V> task)
  214.       {
  215.         return runWithContexts(task, context);
  216.       }

  217.     /*******************************************************************************************************************
  218.      *
  219.      * Runs a task associated with a new bunch of local contexts. This variant fits functional interfaces.
  220.      *
  221.      * @param  <V>                the type of the returned value
  222.      * @param  contexts           the contexts
  223.      * @param  task               the task
  224.      * @return                    the value produced by the task
  225.      * @deprecated Use {@link #runWithContexts(Runnable, Object...)} or {@link #runWithContexts(Supplier, Object...)}
  226.      *
  227.      ******************************************************************************************************************/
  228.     @Deprecated
  229.     public default <V> V runWithContexts (@Nonnull final List<Object> contexts, @Nonnull final Supplier<V> task)
  230.       {
  231.         return runWithContexts(task, contexts.toArray());
  232.       }

  233.     /*******************************************************************************************************************
  234.      *
  235.      * Calls a runnable with some local contexts. This method fits functional interfaces.
  236.      *
  237.      * @param   runnable          the runnable
  238.      * @param   contexts          the contexts
  239.      * @since   3.2-ALPHA-12
  240.      *
  241.      ******************************************************************************************************************/
  242.     public default void runWithContexts (@Nonnull final Runnable runnable, @Nonnull final Object ... contexts)
  243.       {
  244.         final SupplierWithException<Void, RuntimeException> se = () ->{ runnable.run(); return null; };
  245.         runEWithContexts(se, contexts);
  246.       }

  247.     /*******************************************************************************************************************
  248.      *
  249.      * Calls a supplier with some local contexts. This method fits functional interfaces.
  250.      *
  251.      * @param   <T>               the type of the result
  252.      * @param   supplier          the supplier
  253.      * @param   contexts          the contexts
  254.      * @return                    the value returned by the supplier
  255.      * @since   3.2-ALPHA-12
  256.      *
  257.      ******************************************************************************************************************/
  258.     @Nonnull
  259.     public default <T> T runWithContexts (@Nonnull final Supplier<T> supplier, @Nonnull final Object ... contexts)
  260.       {
  261.         final SupplierWithException<T, RuntimeException> se = supplier::get;
  262.         return runEWithContexts(se, contexts);
  263.       }

  264.     /*******************************************************************************************************************
  265.      *
  266.      * Calls a runnable with some local contexts. This method fits functional interfaces.
  267.      *
  268.      * @param   <E>               the type of the thrown exception
  269.      * @param   runnable          the runnable to call
  270.      * @param   contexts          the contexts
  271.      * @throws  E                 the original exception thrown by task
  272.      * @since   3.2-ALPHA-12
  273.      *
  274.      ******************************************************************************************************************/
  275.     public default <E extends Throwable> void runEWithContexts (@Nonnull final RunnableWithException<E> runnable,
  276.                                                                 @Nonnull final Object ... contexts)
  277.       throws E
  278.       {
  279.         final SupplierWithException<Void, E> se = () ->{ runnable.run(); return null; };
  280.         runEWithContexts(se, contexts);
  281.       }

  282.     /*******************************************************************************************************************
  283.      *
  284.      * Calls a task with some local contexts. This method fits functional interfaces.
  285.      *
  286.      * @param   <T>               the type of the returned value
  287.      * @param   <E>               the type of the thrown exception
  288.      * @param   task              the task to call
  289.      * @param   contexts          the contexts
  290.      * @return                    the value returned by the supplier
  291.      * @throws  E                 the original exception thrown by task
  292.      * @since   3.2-ALPHA-12
  293.      *
  294.      ******************************************************************************************************************/
  295.     @Nonnull
  296.     public <T, E extends Throwable> T runEWithContexts (@Nonnull SupplierWithException<T, E> task,
  297.                                                         @Nonnull Object ... contexts)
  298.       throws E;

  299.     /*******************************************************************************************************************
  300.      *
  301.      * Creates a binder that makes it possible to bind a local context by means of a try-with-resources instead of a
  302.      * try/finally.
  303.      *
  304.      * <pre>
  305.      * try (final ContextManager.Binder binder = contextManager.binder(context))
  306.      *   {
  307.      *     ...
  308.      *   }
  309.      * </pre>
  310.      *
  311.      * @param   contexts          the contexts
  312.      * @return                    a binder that can be used in try-with-resources
  313.      * @since   3.2-ALPHA-12
  314.      *
  315.      ******************************************************************************************************************/
  316.     @Nonnull
  317.     public default Binder binder (@Nonnull final Object ... contexts)
  318.       {
  319.         return new Binder(this, contexts);
  320.       }

  321.     /*******************************************************************************************************************
  322.      *
  323.      * Used by
  324.      * @since   3.2-ALPHA-12
  325.      *
  326.      ******************************************************************************************************************/
  327.     public static class Binder implements AutoCloseable
  328.       {
  329.         @Nonnull
  330.         private final ContextManager contextManager;

  331.         @Nonnull
  332.         private final Object[] contexts;

  333.         private Binder (@Nonnull final ContextManager contextManager, @Nonnull final Object[] contexts)
  334.           {
  335.             this.contextManager = contextManager;
  336.             this.contexts = contexts;

  337.             for (final var context : contexts)
  338.               {
  339.                 this.contextManager.addLocalContext(context);
  340.               }
  341.           }

  342.         @Override
  343.         public void close()
  344.           {
  345.             for (final var context : contexts)
  346.               {
  347.                 this.contextManager.removeLocalContext(context);
  348.               }
  349.           }
  350.       }
  351.   }