DefaultContextManager.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.impl;

  27. import javax.annotation.Nonnull;
  28. import java.util.ArrayList;
  29. import java.util.Collections;
  30. import java.util.List;
  31. import java.util.Optional;
  32. import java.util.Stack;
  33. import it.tidalwave.util.ContextManager;
  34. import lombok.extern.slf4j.Slf4j;
  35. import static it.tidalwave.util.CollectionUtils.reversed;
  36. import static it.tidalwave.util.ShortNames.*;

  37. /***************************************************************************************************************************************************************
  38.  *
  39.  * @author  Fabrizio Giudici
  40.  *
  41.  **************************************************************************************************************************************************************/
  42. @Slf4j
  43. public class DefaultContextManager implements ContextManager
  44.   {
  45.     /** Useful for troubleshooting in cases when multiple instances are erroneously created. */
  46.     private static final boolean DUMP_STACK_AT_CREATION = Boolean.getBoolean(
  47.             DefaultContextManager.class.getName() + ".dumpStackAtCreation");

  48.     /** The list of global contexts, ordered by priority. */
  49.     private final List<Object> globalContexts = Collections.synchronizedList(new ArrayList<>());

  50.     /** The list of local contexts, ordered by priority. */
  51.     private final ThreadLocal<Stack<Object>> localContexts = new ThreadLocal<>()
  52.       {
  53.         @Override @Nonnull
  54.         protected Stack<Object> initialValue ()
  55.           {
  56.             return new Stack<>();
  57.           }
  58.       };

  59.     /***********************************************************************************************************************************************************
  60.      *
  61.      **********************************************************************************************************************************************************/
  62.     public DefaultContextManager()
  63.       {
  64.         if (DUMP_STACK_AT_CREATION)
  65.           {
  66.             try
  67.               {
  68.                 throw new RuntimeException();
  69.               }
  70.             catch (Exception e)
  71.               {
  72.                 log.trace(">>>> created context manager " + this, e);
  73.               }
  74.           }
  75.       }

  76.     /***********************************************************************************************************************************************************
  77.      * {@inheritDoc}
  78.      **********************************************************************************************************************************************************/
  79.     @Override @Nonnull
  80.     public List<Object> getContexts()
  81.       {
  82.         final var contexts = reversed(new ArrayList<>(localContexts.get()));
  83.         contexts.addAll(0, globalContexts);
  84.         return contexts;
  85.       }

  86.     /***********************************************************************************************************************************************************
  87.      * {@inheritDoc}
  88.      **********************************************************************************************************************************************************/
  89.     @Override @Nonnull @SuppressWarnings("BoundedWildcard")
  90.     public <T> Optional<T> findContextOfType (@Nonnull final Class<T> contextType)
  91.       {
  92.         for (final var context : getContexts())
  93.           {
  94.             if (contextType.isAssignableFrom(context.getClass()))
  95.               {
  96.                 return Optional.of(contextType.cast(context));
  97.               }
  98.           }

  99.         return Optional.empty();
  100.       }

  101.     /***********************************************************************************************************************************************************
  102.      * {@inheritDoc}
  103.      **********************************************************************************************************************************************************/
  104.     @Override
  105.     public void addGlobalContext (@Nonnull final Object context)
  106.       {
  107.         globalContexts.add(context);
  108.       }

  109.     /***********************************************************************************************************************************************************
  110.      * {@inheritDoc}
  111.      **********************************************************************************************************************************************************/
  112.     @Override
  113.     public void removeGlobalContext (@Nonnull final Object context)
  114.       {
  115.         globalContexts.remove(context);
  116.       }

  117.     /***********************************************************************************************************************************************************
  118.      * {@inheritDoc}
  119.      **********************************************************************************************************************************************************/
  120.     @Override
  121.     public void addLocalContext (@Nonnull final Object context)
  122.       {
  123.         localContexts.get().push(context);
  124.       }

  125.     /***********************************************************************************************************************************************************
  126.      * {@inheritDoc}
  127.      **********************************************************************************************************************************************************/
  128.     @Override
  129.     public void removeLocalContext (@Nonnull final Object context)
  130.       {
  131.         localContexts.get().remove(context);
  132.       }

  133.     /***********************************************************************************************************************************************************
  134.      * {@inheritDoc}
  135.      **********************************************************************************************************************************************************/
  136.     @Override @Nonnull
  137.     public <T, E extends Throwable> T runEWithContexts (@Nonnull final SupplierWithException<T, E> supplier,
  138.                                                         @Nonnull final Object ... contexts)
  139.             throws E
  140.       {
  141.         log.trace("runWithContexts({}, {})", shortId(supplier), shortIds(contexts));

  142.         try (final var unused = binder(contexts))
  143.           {
  144.             if (log.isTraceEnabled())
  145.               {
  146.                 log.trace(">>>> contexts now: {} - {}", shortIds(getContexts()), this);
  147.               }

  148.             final var result = supplier.get();
  149.             log.trace(">>>> runWithContexts({}, {}) completed", shortId(supplier), shortIds(contexts));
  150.             return result;
  151.           }
  152.       }
  153.   }