LinkResolveCounter.java

  1. /*
  2.  * #%L
  3.  * wcm.io
  4.  * %%
  5.  * Copyright (C) 2014 wcm.io
  6.  * %%
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  *      http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  * #L%
  19.  */
  20. package io.wcm.handler.link.type.helpers;

  21. import org.jetbrains.annotations.NotNull;

  22. /**
  23.  * Counts number of recursive link resolve requests to detect endless loops.
  24.  * Max. 5 hops are allowed in {@link #isMaximumReached()} method.
  25.  */
  26. public final class LinkResolveCounter {

  27.   private static final ThreadLocal<LinkResolveCounter> THREAD_LOCAL = ThreadLocal.withInitial(LinkResolveCounter::new);

  28.   /**
  29.    * Maximum number of "recursion hops" allowed for link resolving.
  30.    */
  31.   private static final int MAX_COUNT = 5;

  32.   private int count;

  33.   /**
  34.    * @return Counter value
  35.    */
  36.   public int getCount() {
  37.     return this.count;
  38.   }

  39.   /**
  40.    * Increase counter by 1.
  41.    */
  42.   public void increaseCount() {
  43.     this.count++;
  44.   }

  45.   /**
  46.    * Decrease counter by 1.
  47.    * If 0 is reached the counter instance is removed from the current thread.
  48.    */
  49.   public void decreaseCount() {
  50.     if (this.count == 0) {
  51.       throw new IllegalStateException("Cannot decrease, counter is already 0.");
  52.     }
  53.     this.count--;
  54.     if (this.count == 0) {
  55.       THREAD_LOCAL.remove();
  56.     }
  57.   }

  58.   /**
  59.    * @return true if maximum of allowed recursion steps is reached.
  60.    */
  61.   public boolean isMaximumReached() {
  62.     return (this.count > MAX_COUNT);
  63.   }

  64.   /**
  65.    * @return Counter for current request/thread.
  66.    *         If instance was not set in thread before it is newly created and attached to the current thread.
  67.    */
  68.   public static @NotNull LinkResolveCounter get() {
  69.     return THREAD_LOCAL.get();
  70.   }

  71. }