/*
 * Copyright (C) 2009 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.collect;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Maps.newTreeMap;
import static java.util.Collections.singletonMap;
import static java.util.Collections.unmodifiableSortedMap;

import com.google.common.annotations.Beta;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * GWT emulated version of {@link com.google.common.collect.ImmutableSortedMap}. It's a thin wrapper
 * around a {@link java.util.TreeMap}.
 *
 * @author Hayward Chan
 */
public final class ImmutableSortedMap<K, V> extends ForwardingImmutableMap<K, V>
    implements SortedMap<K, V> {

  @SuppressWarnings("unchecked")
  static final Comparator NATURAL_ORDER = Ordering.natural();

  // This reference is only used by GWT compiler to infer the keys and values
  // of the map that needs to be serialized.
  private Comparator<? super K> unusedComparatorForSerialization;
  private K unusedKeyForSerialization;
  private V unusedValueForSerialization;

  private final transient SortedMap<K, V> sortedDelegate;

  // The comparator used by this map.  It's the same as that of sortedDelegate,
  // except that when sortedDelegate's comparator is null, it points to a
  // non-null instance of Ordering.natural().
  // (cpovirk: Is sortedDelegate's comparator really ever null?)
  // The comparator will likely also differ because of our nullAccepting hack.
  // See the bottom of the file for more information about it.
  private final transient Comparator<? super K> comparator;

  ImmutableSortedMap(SortedMap<K, V> delegate, Comparator<? super K> comparator) {
    super(delegate);
    this.comparator = comparator;
    this.sortedDelegate = delegate;
  }

  @Beta
  public static <T, K, V> Collector<T, ?, ImmutableSortedMap<K, V>> toImmutableSortedMap(
      Comparator<? super K> comparator,
      Function<? super T, ? extends K> keyFunction,
      Function<? super T, ? extends V> valueFunction) {
    return CollectCollectors.toImmutableSortedMap(comparator, keyFunction, valueFunction);
  }

  @Beta
  public static <T, K, V> Collector<T, ?, ImmutableSortedMap<K, V>> toImmutableSortedMap(
      Comparator<? super K> comparator,
      Function<? super T, ? extends K> keyFunction,
      Function<? super T, ? extends V> valueFunction,
      BinaryOperator<V> mergeFunction) {
    checkNotNull(comparator);
    checkNotNull(keyFunction);
    checkNotNull(valueFunction);
    checkNotNull(mergeFunction);
    return Collectors.collectingAndThen(
        Collectors.toMap(
            keyFunction, valueFunction, mergeFunction, () -> new TreeMap<K, V>(comparator)),
        ImmutableSortedMap::copyOfSorted);
  }

  // Casting to any type is safe because the set will never hold any elements.
  @SuppressWarnings("unchecked")
  public static <K, V> ImmutableSortedMap<K, V> of() {
    return new Builder<K, V>(NATURAL_ORDER).build();
  }

  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(K k1, V v1) {
    return copyOf(singletonMap(k1, v1));
  }

  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
      K k1, V v1, K k2, V v2) {
    return new Builder<K, V>(Ordering.natural()).put(k1, v1).put(k2, v2).build();
  }

  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
      K k1, V v1, K k2, V v2, K k3, V v3) {
    return new Builder<K, V>(Ordering.natural()).put(k1, v1).put(k2, v2).put(k3, v3).build();
  }

  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
    return new Builder<K, V>(Ordering.natural())
        .put(k1, v1)
        .put(k2, v2)
        .put(k3, v3)
        .put(k4, v4)
        .build();
  }

  public static <K extends Comparable<? super K>, V> ImmutableSortedMap<K, V> of(
      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
    return new Builder<K, V>(Ordering.natural())
        .put(k1, v1)
        .put(k2, v2)
        .put(k3, v3)
        .put(k4, v4)
        .put(k5, v5)
        .build();
  }

  public static <K, V> ImmutableSortedMap<K, V> copyOf(Map<? extends K, ? extends V> map) {
    return copyOfInternal((Map) map, (Ordering<K>) Ordering.natural());
  }

  public static <K, V> ImmutableSortedMap<K, V> copyOf(
      Map<? extends K, ? extends V> map, Comparator<? super K> comparator) {
    return copyOfInternal(map, checkNotNull(comparator));
  }

  public static <K, V> ImmutableSortedMap<K, V> copyOf(
      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
    return new Builder<K, V>(NATURAL_ORDER).putAll(entries).build();
  }

  public static <K, V> ImmutableSortedMap<K, V> copyOf(
      Iterable<? extends Entry<? extends K, ? extends V>> entries,
      Comparator<? super K> comparator) {
    return new Builder<K, V>(comparator).putAll(entries).build();
  }

  public static <K, V> ImmutableSortedMap<K, V> copyOfSorted(SortedMap<K, ? extends V> map) {
    // If map has a null comparator, the keys should have a natural ordering,
    // even though K doesn't explicitly implement Comparable.
    @SuppressWarnings("unchecked")
    Comparator<? super K> comparator =
        (map.comparator() == null) ? NATURAL_ORDER : map.comparator();
    return copyOfInternal(map, comparator);
  }

  private static <K, V> ImmutableSortedMap<K, V> copyOfInternal(
      Map<? extends K, ? extends V> map, Comparator<? super K> comparator) {

    if (map instanceof ImmutableSortedMap) {
      // TODO: Prove that this cast is safe, even though
      // Collections.unmodifiableSortedMap requires the same key type.
      @SuppressWarnings("unchecked")
      ImmutableSortedMap<K, V> kvMap = (ImmutableSortedMap<K, V>) map;
      Comparator<?> comparator2 = kvMap.comparator();
      boolean sameComparator =
          (comparator2 == null) ? comparator == NATURAL_ORDER : comparator.equals(comparator2);
      if (sameComparator) {
        return kvMap;
      }
    }

    SortedMap<K, V> delegate = newModifiableDelegate(comparator);
    for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
      putEntryWithChecks(delegate, entry);
    }
    return newView(unmodifiableSortedMap(delegate), comparator);
  }

  private static <K, V> void putEntryWithChecks(
      SortedMap<K, V> map, Entry<? extends K, ? extends V> entry) {
    K key = checkNotNull(entry.getKey());
    V value = checkNotNull(entry.getValue());
    if (map.containsKey(key)) {
      // When a collision happens, the colliding entry is the first entry
      // of the tail map.
      Entry<K, V> previousEntry = map.tailMap(key).entrySet().iterator().next();
      throw new IllegalArgumentException(
          "Duplicate keys in mappings "
              + previousEntry.getKey()
              + "="
              + previousEntry.getValue()
              + " and "
              + key
              + "="
              + value);
    }
    map.put(key, value);
  }

  public static <K extends Comparable<?>, V> Builder<K, V> naturalOrder() {
    return new Builder<K, V>(Ordering.natural());
  }

  public static <K, V> Builder<K, V> orderedBy(Comparator<K> comparator) {
    return new Builder<K, V>(comparator);
  }

  public static <K extends Comparable<?>, V> Builder<K, V> reverseOrder() {
    return new Builder<K, V>(Ordering.natural().reverse());
  }

  public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> {
    private final Comparator<? super K> comparator;

    public Builder(Comparator<? super K> comparator) {
      this.comparator = checkNotNull(comparator);
    }

    @Override
    public Builder<K, V> put(K key, V value) {
      entries.add(entryOf(key, value));
      return this;
    }

    @Override
    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
      super.put(entry);
      return this;
    }

    @Override
    public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
      return putAll(map.entrySet());
    }

    @Override
    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
      for (Entry<? extends K, ? extends V> entry : entries) {
        put(entry);
      }
      return this;
    }

    Builder<K, V> combine(Builder<K, V> other) {
      super.combine(other);
      return this;
    }

    @Override
    public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
      throw new UnsupportedOperationException("Not available on ImmutableSortedMap.Builder");
    }

    @Override
    public ImmutableSortedMap<K, V> build() {
      SortedMap<K, V> delegate = newModifiableDelegate(comparator);
      for (Entry<? extends K, ? extends V> entry : entries) {
        putEntryWithChecks(delegate, entry);
      }
      return newView(unmodifiableSortedMap(delegate), comparator);
    }
  }

  private transient ImmutableSortedSet<K> keySet;

  @Override
  public ImmutableSortedSet<K> keySet() {
    ImmutableSortedSet<K> ks = keySet;
    return (ks == null) ? (keySet = createKeySet()) : ks;
  }

  @Override
  ImmutableSortedSet<K> createKeySet() {
    // the keySet() of the delegate is only a Set and TreeMap.navigatableKeySet
    // is not available in GWT yet.  To keep the code simple and code size more,
    // we make a copy here, instead of creating a view of it.
    //
    // TODO: revisit if it's unbearably slow or when GWT supports
    // TreeMap.navigatbleKeySet().
    return ImmutableSortedSet.copyOf(comparator, sortedDelegate.keySet());
  }

  public Comparator<? super K> comparator() {
    return comparator;
  }

  public K firstKey() {
    return sortedDelegate.firstKey();
  }

  public K lastKey() {
    return sortedDelegate.lastKey();
  }

  K higher(K k) {
    Iterator<K> iterator = keySet().tailSet(k).iterator();
    while (iterator.hasNext()) {
      K tmp = iterator.next();
      if (comparator().compare(k, tmp) < 0) {
        return tmp;
      }
    }
    return null;
  }

  public ImmutableSortedMap<K, V> headMap(K toKey) {
    checkNotNull(toKey);
    return newView(sortedDelegate.headMap(toKey));
  }

  ImmutableSortedMap<K, V> headMap(K toKey, boolean inclusive) {
    checkNotNull(toKey);
    if (inclusive) {
      K tmp = higher(toKey);
      if (tmp == null) {
        return this;
      }
      toKey = tmp;
    }
    return headMap(toKey);
  }

  public ImmutableSortedMap<K, V> subMap(K fromKey, K toKey) {
    checkNotNull(fromKey);
    checkNotNull(toKey);
    checkArgument(comparator.compare(fromKey, toKey) <= 0);
    return newView(sortedDelegate.subMap(fromKey, toKey));
  }

  ImmutableSortedMap<K, V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) {
    checkNotNull(fromKey);
    checkNotNull(toKey);
    checkArgument(comparator.compare(fromKey, toKey) <= 0);
    return tailMap(fromKey, fromInclusive).headMap(toKey, toInclusive);
  }

  public ImmutableSortedMap<K, V> tailMap(K fromKey) {
    checkNotNull(fromKey);
    return newView(sortedDelegate.tailMap(fromKey));
  }

  public ImmutableSortedMap<K, V> tailMap(K fromKey, boolean inclusive) {
    checkNotNull(fromKey);
    if (!inclusive) {
      fromKey = higher(fromKey);
      if (fromKey == null) {
        return new Builder<K, V>(this.comparator).build();
      }
    }
    return tailMap(fromKey);
  }

  private ImmutableSortedMap<K, V> newView(SortedMap<K, V> delegate) {
    return newView(delegate, comparator);
  }

  private static <K, V> ImmutableSortedMap<K, V> newView(
      SortedMap<K, V> delegate, Comparator<? super K> comparator) {
    return new ImmutableSortedMap<K, V>(delegate, comparator);
  }

  /*
   * We don't permit nulls, but we wrap every comparator with nullsFirst().
   * Why? We want for queries like containsKey(null) to return false, but the
   * GWT SortedMap implementation that we delegate to throws
   * NullPointerException if the comparator does. Since our construction
   * methods ensure that null is never present in the map, it's OK for the
   * comparator to look for it wherever it wants.
   *
   * Note that we do NOT touch the comparator returned by comparator(), which
   * should be identical to the one the user passed in. We touch only the
   * "secret" comparator used by the delegate implementation.
   */

  private static <K, V> SortedMap<K, V> newModifiableDelegate(Comparator<? super K> comparator) {
    return newTreeMap(nullAccepting(comparator));
  }

  private static <E> Comparator<E> nullAccepting(Comparator<E> comparator) {
    return Ordering.from(comparator).nullsFirst();
  }
}


/*
 * Copyright (C) 2016 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.graph;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.graph.Graphs.checkNonNegative;

import com.google.common.annotations.Beta;
import com.google.common.base.Optional;

/**
 * A builder for constructing instances of {@link MutableNetwork} or {@link ImmutableNetwork} with
 * user-defined properties.
 *
 *
A network built by this class will have the following properties by default:
 *
 *

 *
does not allow parallel edges
 *
does not allow self-loops
 *
orders {@link Network#nodes()} and {@link Network#edges()} in the order in which the
 *       elements were added
 *

 *
 *
Examples of use:
 *
 *
{@code
 * // Building a mutable network
 * MutableNetwork<String, Integer> network =
 *     NetworkBuilder.directed().allowsParallelEdges(true).build();
 * flightNetwork.addEdge("LAX", "ATL", 3025);
 * flightNetwork.addEdge("LAX", "ATL", 1598);
 * flightNetwork.addEdge("ATL", "LAX", 2450);
 *
 * // Building a immutable network
 * ImmutableNetwork<String, Integer> immutableNetwork =
 *     NetworkBuilder.directed()
 *         .allowsParallelEdges(true)
 *         .<String, Integer>immutable()
 *         .addEdge("LAX", "ATL", 3025)
 *         .addEdge("LAX", "ATL", 1598)
 *         .addEdge("ATL", "LAX", 2450)
 *         .build();
 * }

 *
 * @author James Sexton
 * @author Joshua O'Madadhain
 * @param <N> The most general node type this builder will support. This is normally {@code Object}
 *     unless it is constrained by using a method like {@link #nodeOrder}, or the builder is
 *     constructed based on an existing {@code Network} using {@link #from(Network)}.
 * @param <N> The most general edge type this builder will support. This is normally {@code Object}
 *     unless it is constrained by using a method like {@link #edgeOrder}, or the builder is
 *     constructed based on an existing {@code Network} using {@link #from(Network)}.
 * @since 20.0
 */
@Beta
public final class NetworkBuilder<N, E> extends AbstractGraphBuilder<N> {
  boolean allowsParallelEdges = false;
  ElementOrder<? super E> edgeOrder = ElementOrder.insertion();
  Optional<Integer> expectedEdgeCount = Optional.absent();

  /** Creates a new instance with the specified edge directionality. */
  private NetworkBuilder(boolean directed) {
    super(directed);
  }

  /** Returns a {@link NetworkBuilder} for building directed networks. */
  public static NetworkBuilder<Object, Object> directed() {
    return new NetworkBuilder<>(true);
  }

  /** Returns a {@link NetworkBuilder} for building undirected networks. */
  public static NetworkBuilder<Object, Object> undirected() {
    return new NetworkBuilder<>(false);
  }

  /**
   * Returns a {@link NetworkBuilder} initialized with all properties queryable from {@code
   * network}.
   *
   *
The "queryable" properties are those that are exposed through the {@link Network} interface,
   * such as {@link Network#isDirected()}. Other properties, such as {@link
   * #expectedNodeCount(int)}, are not set in the new builder.
   */
  public static <N, E> NetworkBuilder<N, E> from(Network<N, E> network) {
    return new NetworkBuilder<N, E>(network.isDirected())
        .allowsParallelEdges(network.allowsParallelEdges())
        .allowsSelfLoops(network.allowsSelfLoops())
        .nodeOrder(network.nodeOrder())
        .edgeOrder(network.edgeOrder());
  }

  /**
   * Returns an {@link ImmutableNetwork#Builder} with the properties of this {@link NetworkBuilder}.
   *
   *
The returned builder can be used for populating an {@link ImmutableNetwork}.
   *
   * @since NEXT
   */
  public <N1 extends N, E1 extends E> ImmutableNetwork.Builder<N1, E1> immutable() {
    NetworkBuilder<N1, E1> castBuilder = cast();
    return new ImmutableNetwork.Builder<>(castBuilder);
  }

  /**
   * Specifies whether the network will allow parallel edges. Attempting to add a parallel edge to a
   * network that does not allow them will throw an {@link UnsupportedOperationException}.
   */
  public NetworkBuilder<N, E> allowsParallelEdges(boolean allowsParallelEdges) {
    this.allowsParallelEdges = allowsParallelEdges;
    return this;
  }

  /**
   * Specifies whether the network will allow self-loops (edges that connect a node to itself).
   * Attempting to add a self-loop to a network that does not allow them will throw an {@link
   * UnsupportedOperationException}.
   */
  public NetworkBuilder<N, E> allowsSelfLoops(boolean allowsSelfLoops) {
    this.allowsSelfLoops = allowsSelfLoops;
    return this;
  }

  /**
   * Specifies the expected number of nodes in the network.
   *
   * @throws IllegalArgumentException if {@code expectedNodeCount} is negative
   */
  public NetworkBuilder<N, E> expectedNodeCount(int expectedNodeCount) {
    this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount));
    return this;
  }

  /**
   * Specifies the expected number of edges in the network.
   *
   * @throws IllegalArgumentException if {@code expectedEdgeCount} is negative
   */
  public NetworkBuilder<N, E> expectedEdgeCount(int expectedEdgeCount) {
    this.expectedEdgeCount = Optional.of(checkNonNegative(expectedEdgeCount));
    return this;
  }

  /** Specifies the order of iteration for the elements of {@link Network#nodes()}. */
  public <N1 extends N> NetworkBuilder<N1, E> nodeOrder(ElementOrder<N1> nodeOrder) {
    NetworkBuilder<N1, E> newBuilder = cast();
    newBuilder.nodeOrder = checkNotNull(nodeOrder);
    return newBuilder;
  }

  /** Specifies the order of iteration for the elements of {@link Network#edges()}. */
  public <E1 extends E> NetworkBuilder<N, E1> edgeOrder(ElementOrder<E1> edgeOrder) {
    NetworkBuilder<N, E1> newBuilder = cast();
    newBuilder.edgeOrder = checkNotNull(edgeOrder);
    return newBuilder;
  }

  /** Returns an empty {@link MutableNetwork} with the properties of this {@link NetworkBuilder}. */
  public <N1 extends N, E1 extends E> MutableNetwork<N1, E1> build() {
    return new ConfigurableMutableNetwork<>(this);
  }

  @SuppressWarnings("unchecked")
  private <N1 extends N, E1 extends E> NetworkBuilder<N1, E1> cast() {
    return (NetworkBuilder<N1, E1>) this;
  }
}


/*
 * Copyright (C) 2010 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.common.util.concurrent;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import com.google.j2objc.annotations.Weak;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BooleanSupplier;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * A synchronization abstraction supporting waiting on arbitrary boolean conditions.
 *
 *
This class is intended as a replacement for {@link ReentrantLock}. Code using {@code Monitor}
 * is less error-prone and more readable than code using {@code ReentrantLock}, without significant
 * performance loss. {@code Monitor} even has the potential for performance gain by optimizing the
 * evaluation and signaling of conditions. Signaling is entirely implicit. By
 * eliminating explicit signaling, this class can guarantee that only one thread is awakened when a
 * condition becomes true (no "signaling storms" due to use of {@link
 * java.util.concurrent.locks.Condition#signalAll Condition.signalAll}) and that no signals are lost
 * (no "hangs" due to incorrect use of {@link java.util.concurrent.locks.Condition#signal
 * Condition.signal}).
 *
 *
A thread is said to occupy a monitor if it has entered the monitor but not yet
 * left. Only one thread may occupy a given monitor at any moment. A monitor is also
 * reentrant, so a thread may enter a monitor any number of times, and then must leave the same
 * number of times. The enter and leave operations have the same synchronization
 * semantics as the built-in Java language synchronization primitives.
 *
 *
A call to any of the enter methods with void return type should always be
 * followed immediately by a try/finally block to ensure that the current thread leaves the
 * monitor cleanly:
 *
 *
{@code
 * monitor.enter();
 * try {
 *   // do things while occupying the monitor
 * } finally {
 *   monitor.leave();
 * }
 * }

 *
 *
A call to any of the enter methods with boolean return type should always appear
 * as the condition of an if statement containing a try/finally block to ensure that
 * the current thread leaves the monitor cleanly:
 *
 *
{@code
 * if (monitor.tryEnter()) {
 *   try {
 *     // do things while occupying the monitor
 *   } finally {
 *     monitor.leave();
 *   }
 * } else {
 *   // do other things since the monitor was not available
 * }
 * }

 *
 *
Comparison with {@code synchronized} and {@code ReentrantLock}

 *
 *
The following examples show a simple threadsafe holder expressed using {@code synchronized},
 * {@link ReentrantLock}, and {@code Monitor}.
 *
 *
{@code synchronized}

 *
 *
This version is the fewest lines of code, largely because the synchronization mechanism used
 * is built into the language and runtime. But the programmer has to remember to avoid a couple of
 * common bugs: The {@code wait()} must be inside a {@code while} instead of an {@code if}, and
 * {@code notifyAll()} must be used instead of {@code notify()} because there are two different
 * logical conditions being awaited.
 *
 *
{@code
 * public class SafeBox<V> {
 *   private V value;
 *
 *   public synchronized V get() throws InterruptedException {
 *     while (value == null) {
 *       wait();
 *     }
 *     V result = value;
 *     value = null;
 *     notifyAll();
 *     return result;
 *   }
 *
 *   public synchronized void set(V newValue) throws InterruptedException {
 *     while (value != null) {
 *       wait();
 *     }
 *     value = newValue;
 *     notifyAll();
 *   }
 * }
 * }

 *
 *
{@code ReentrantLock}

 *
 *
This version is much more verbose than the {@code synchronized} version, and still suffers
 * from the need for the programmer to remember to use {@code while} instead of {@code if}. However,
 * one advantage is that we can introduce two separate {@code Condition} objects, which allows us to
 * use {@code signal()} instead of {@code signalAll()}, which may be a performance benefit.
 *
 *
{@code
 * public class SafeBox<V> {
 *   private V value;
 *   private final ReentrantLock lock = new ReentrantLock();
 *   private final Condition valuePresent = lock.newCondition();
 *   private final Condition valueAbsent = lock.newCondition();
 *
 *   public V get() throws InterruptedException {
 *     lock.lock();
 *     try {
 *       while (value == null) {
 *         valuePresent.await();
 *       }
 *       V result = value;
 *       value = null;
 *       valueAbsent.signal();
 *       return result;
 *     } finally {
 *       lock.unlock();
 *     }
 *   }
 *
 *   public void set(V newValue) throws InterruptedException {
 *     lock.lock();
 *     try {
 *       while (value != null) {
 *         valueAbsent.await();
 *       }
 *       value = newValue;
 *       valuePresent.signal();
 *     } finally {
 *       lock.unlock();
 *     }
 *   }
 * }
 * }

 *
 *
{@code Monitor}

 *
 *
This version adds some verbosity around the {@code Guard} objects, but removes that same
 * verbosity, and more, from the {@code get} and {@code set} methods. {@code Monitor} implements the
 * same efficient signaling as we had to hand-code in the {@code ReentrantLock} version above.
 * Finally, the programmer no longer has to hand-code the wait loop, and therefore doesn't have to
 * remember to use {@code while} instead of {@code if}.
 *
 *
{@code
 * public class SafeBox<V> {
 *   private V value;
 *   private final Monitor monitor = new Monitor();
 *   private final Monitor.Guard valuePresent = monitor.newGuard(() -> value != null);
 *   private final Monitor.Guard valueAbsent = monitor.newGuard(() -> value == null);
 *
 *   public V get() throws InterruptedException {
 *     monitor.enterWhen(valuePresent);
 *     try {
 *       V result = value;
 *       value = null;
 *       return result;
 *     } finally {
 *       monitor.leave();
 *     }
 *   }
 *
 *   public void set(V newValue) throws InterruptedException {
 *     monitor.enterWhen(valueAbsent);
 *     try {
 *       value = newValue;
 *     } finally {
 *       monitor.leave();
 *     }
 *   }
 * }
 * }

 *
 * @author Justin T. Sampson
 * @author Martin Buchholz
 * @since 10.0
 */
@Beta
@GwtIncompatible
@SuppressWarnings("GuardedBy") // TODO(b/35466881): Fix or suppress.
public final class Monitor {
  // TODO(user): Use raw LockSupport or AbstractQueuedSynchronizer instead of ReentrantLock.
  // TODO(user): "Port" jsr166 tests for ReentrantLock.
  //
  // TODO(user): Change API to make it impossible to use a Guard with the "wrong" monitor,
  //    by making the monitor implicit, and to eliminate other sources of IMSE.
  //    Imagine:
  //    guard.lock();
  //    try { /* monitor locked and guard satisfied here */ }
  //    finally { guard.unlock(); }
  // Here are Justin's design notes about this:
  //
  // This idea has come up from time to time, and I think one of my
  // earlier versions of Monitor even did something like this. I ended
  // up strongly favoring the current interface.
  //
  // I probably can't remember all the reasons (it's possible you
  // could find them in the code review archives), but here are a few:
  //
  // 1. What about leaving/unlocking? Are you going to do
  //    guard.enter() paired with monitor.leave()? That might get
  //    confusing. It's nice for the finally block to look as close as
  //    possible to the thing right before the try. You could have
  //    guard.leave(), but that's a little odd as well because the
  //    guard doesn't have anything to do with leaving. You can't
  //    really enforce that the guard you're leaving is the same one
  //    you entered with, and it doesn't actually matter.
  //
  // 2. Since you can enter the monitor without a guard at all, some
  //    places you'll have monitor.enter()/monitor.leave() and other
  //    places you'll have guard.enter()/guard.leave() even though
  //    it's the same lock being acquired underneath. Always using
  //    monitor.enterXXX()/monitor.leave() will make it really clear
  //    which lock is held at any point in the code.
  //
  // 3. I think "enterWhen(notEmpty)" reads better than "notEmpty.enter()".
  //
  // TODO(user): Implement ReentrantLock features:
  //    - toString() method
  //    - getOwner() method
  //    - getQueuedThreads() method
  //    - getWaitingThreads(Guard) method
  //    - implement Serializable
  //    - redo the API to be as close to identical to ReentrantLock as possible,
  //      since, after all, this class is also a reentrant mutual exclusion lock!?

  /*
   * One of the key challenges of this class is to prevent lost signals, while trying hard to
   * minimize unnecessary signals. One simple and correct algorithm is to signal some other waiter
   * with a satisfied guard (if one exists) whenever any thread occupying the monitor exits the
   * monitor, either by unlocking all of its held locks, or by starting to wait for a guard. This
   * includes exceptional exits, so all control paths involving signalling must be protected by a
   * finally block.
   *
   * Further optimizations of this algorithm become increasingly subtle. A wait that terminates
   * without the guard being satisfied (due to timeout, but not interrupt) can then immediately exit
   * the monitor without signalling. If it timed out without being signalled, it does not need to
   * "pass on" the signal to another thread. If it *was* signalled, then its guard must have been
   * satisfied at the time of signal, and has since been modified by some other thread to be
   * non-satisfied before reacquiring the lock, and that other thread takes over the responsibility
   * of signaling the next waiter.
   *
   * Unlike the underlying Condition, if we are not careful, an interrupt *can* cause a signal to be
   * lost, because the signal may be sent to a condition whose sole waiter has just been
   * interrupted.
   *
   * Imagine a monitor with multiple guards. A thread enters the monitor, satisfies all the guards,
   * and leaves, calling signalNextWaiter. With traditional locks and conditions, all the conditions
   * need to be signalled because it is not known which if any of them have waiters (and hasWaiters
   * can't be used reliably because of a check-then-act race). With our Monitor guards, we only
   * signal the first active guard that is satisfied. But the corresponding thread may have already
   * been interrupted and is waiting to reacquire the lock while still registered in activeGuards,
   * in which case the signal is a no-op, and the bigger-picture signal is lost unless interrupted
   * threads take special action by participating in the signal-passing game.
   */

  /*
   * Timeout handling is intricate, especially given our ambitious goals:
   * - Avoid underflow and overflow of timeout values when specified timeouts are close to
   *   Long.MIN_VALUE or Long.MAX_VALUE.
   * - Favor responding to interrupts over timeouts.
   * - System.nanoTime() is expensive enough that we want to call it the minimum required number of
   *   times, typically once before invoking a blocking method. This often requires keeping track of
   *   the first time in a method that nanoTime() has been invoked, for which the special value 0L
   *   is reserved to mean "uninitialized". If timeout is non-positive, then nanoTime need never be
   *   called.
   * - Keep behavior of fair and non-fair instances consistent.
   */

  /**
   * A boolean condition for which a thread may wait. A {@code Guard} is associated with a single
   * {@code Monitor}. The monitor may check the guard at arbitrary times from any thread occupying
   * the monitor, so code should not be written to rely on how often a guard might or might not be
   * checked.
   *
   *
If a {@code Guard} is passed into any method of a {@code Monitor} other than the one it is
   * associated with, an {@link IllegalMonitorStateException} is thrown.
   *
   * @since 10.0
   */
  @Beta
  public abstract static class Guard {

    @Weak final Monitor monitor;
    final Condition condition;

    @GuardedBy("monitor.lock")
    int waiterCount = 0;

    /** The next active guard */
    @GuardedBy("monitor.lock")
    @Nullable
    Guard next;

    protected Guard(Monitor monitor) {
      this.monitor = checkNotNull(monitor, "monitor");
      this.condition = monitor.lock.newCondition();
    }

    /**
     * Evaluates this guard's boolean condition. This method is always called with the associated
     * monitor already occupied. Implementations of this method must depend only on state protected
     * by the associated monitor, and must not modify that state.
     */
    public abstract boolean isSatisfied();
  }

  /** Whether this monitor is fair. */
  private final boolean fair;

  /** The lock underlying this monitor. */
  private final ReentrantLock lock;

  /**
   * The guards associated with this monitor that currently have waiters ({@code waiterCount > 0}).
   * A linked list threaded through the Guard.next field.
   */
  @GuardedBy("lock")
  private Guard activeGuards = null;

  /**
   * Creates a monitor with a non-fair (but fast) ordering policy. Equivalent to {@code
   * Monitor(false)}.
   */
  public Monitor() {
    this(false);
  }

  /**
   * Creates a monitor with the given ordering policy.
   *
   * @param fair whether this monitor should use a fair ordering policy rather than a non-fair (but
   *     fast) one
   */
  public Monitor(boolean fair) {
    this.fair = fair;
    this.lock = new ReentrantLock(fair);
  }

  /**
   * Creates a new {@linkplain Guard guard} for this monitor.
   *
   * @param isSatisfied the new guard's boolean condition (see {@link Guard#isSatisfied
   *     isSatisfied()})
   * @since 21.0
   */
  public Guard newGuard(final BooleanSupplier isSatisfied) {
    checkNotNull(isSatisfied, "isSatisfied");
    return new Guard(this) {
      @Override
      public boolean isSatisfied() {
        return isSatisfied.getAsBoolean();
      }
    };
  }

  /** Enters this monitor. Blocks indefinitely. */
  public void enter() {
    lock.lock();
  }

  /**
   * Enters this monitor. Blocks at most the given time.
   *
   * @return whether the monitor was entered
   */
  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
  public boolean enter(long time, TimeUnit unit) {
    final long timeoutNanos = toSafeNanos(time, unit);
    final ReentrantLock lock = this.lock;
    if (!fair && lock.tryLock()) {
      return true;
    }
    boolean interrupted = Thread.interrupted();
    try {
      final long startTime = System.nanoTime();
      for (long remainingNanos = timeoutNanos; ; ) {
        try {
          return lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS);
        } catch (InterruptedException interrupt) {
          interrupted = true;
          remainingNanos = remainingNanos(startTime, timeoutNanos);
        }
      }
    } finally {
      if (interrupted) {
        Thread.currentThread().interrupt();
      }
    }
  }

  /**
   * Enters this monitor. Blocks indefinitely, but may be interrupted.
   *
   * @throws InterruptedException if interrupted while waiting
   */
  public void enterInterruptibly() throws InterruptedException {
    lock.lockInterruptibly();
  }

  /**
   * Enters this monitor. Blocks at most the given time, and may be interrupted.
   *
   * @return whether the monitor was entered
   * @throws InterruptedException if interrupted while waiting
   */
  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
  public boolean enterInterruptibly(long time, TimeUnit unit) throws InterruptedException {
    return lock.tryLock(time, unit);
  }

  /**
   * Enters this monitor if it is possible to do so immediately. Does not block.
   *
   *
Note: This method disregards the fairness setting of this monitor.
   *
   * @return whether the monitor was entered
   */
  public boolean tryEnter() {
    return lock.tryLock();
  }

  /**
   * Enters this monitor when the guard is satisfied. Blocks indefinitely, but may be interrupted.
   *
   * @throws InterruptedException if interrupted while waiting
   */
  public void enterWhen(Guard guard) throws InterruptedException {
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    final ReentrantLock lock = this.lock;
    boolean signalBeforeWaiting = lock.isHeldByCurrentThread();
    lock.lockInterruptibly();

    boolean satisfied = false;
    try {
      if (!guard.isSatisfied()) {
        await(guard, signalBeforeWaiting);
      }
      satisfied = true;
    } finally {
      if (!satisfied) {
        leave();
      }
    }
  }

  /**
   * Enters this monitor when the guard is satisfied. Blocks at most the given time, including both
   * the time to acquire the lock and the time to wait for the guard to be satisfied, and may be
   * interrupted.
   *
   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
   * @throws InterruptedException if interrupted while waiting
   */
  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
  public boolean enterWhen(Guard guard, long time, TimeUnit unit) throws InterruptedException {
    final long timeoutNanos = toSafeNanos(time, unit);
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    final ReentrantLock lock = this.lock;
    boolean reentrant = lock.isHeldByCurrentThread();
    long startTime = 0L;

    locked:
    {
      if (!fair) {
        // Check interrupt status to get behavior consistent with fair case.
        if (Thread.interrupted()) {
          throw new InterruptedException();
        }
        if (lock.tryLock()) {
          break locked;
        }
      }
      startTime = initNanoTime(timeoutNanos);
      if (!lock.tryLock(time, unit)) {
        return false;
      }
    }

    boolean satisfied = false;
    boolean threw = true;
    try {
      satisfied =
          guard.isSatisfied()
              || awaitNanos(
                  guard,
                  (startTime == 0L) ? timeoutNanos : remainingNanos(startTime, timeoutNanos),
                  reentrant);
      threw = false;
      return satisfied;
    } finally {
      if (!satisfied) {
        try {
          // Don't need to signal if timed out, but do if interrupted
          if (threw && !reentrant) {
            signalNextWaiter();
          }
        } finally {
          lock.unlock();
        }
      }
    }
  }

  /** Enters this monitor when the guard is satisfied. Blocks indefinitely. */
  public void enterWhenUninterruptibly(Guard guard) {
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    final ReentrantLock lock = this.lock;
    boolean signalBeforeWaiting = lock.isHeldByCurrentThread();
    lock.lock();

    boolean satisfied = false;
    try {
      if (!guard.isSatisfied()) {
        awaitUninterruptibly(guard, signalBeforeWaiting);
      }
      satisfied = true;
    } finally {
      if (!satisfied) {
        leave();
      }
    }
  }

  /**
   * Enters this monitor when the guard is satisfied. Blocks at most the given time, including both
   * the time to acquire the lock and the time to wait for the guard to be satisfied.
   *
   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
   */
  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
  public boolean enterWhenUninterruptibly(Guard guard, long time, TimeUnit unit) {
    final long timeoutNanos = toSafeNanos(time, unit);
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    final ReentrantLock lock = this.lock;
    long startTime = 0L;
    boolean signalBeforeWaiting = lock.isHeldByCurrentThread();
    boolean interrupted = Thread.interrupted();
    try {
      if (fair || !lock.tryLock()) {
        startTime = initNanoTime(timeoutNanos);
        for (long remainingNanos = timeoutNanos; ; ) {
          try {
            if (lock.tryLock(remainingNanos, TimeUnit.NANOSECONDS)) {
              break;
            } else {
              return false;
            }
          } catch (InterruptedException interrupt) {
            interrupted = true;
            remainingNanos = remainingNanos(startTime, timeoutNanos);
          }
        }
      }

      boolean satisfied = false;
      try {
        while (true) {
          try {
            if (guard.isSatisfied()) {
              satisfied = true;
            } else {
              final long remainingNanos;
              if (startTime == 0L) {
                startTime = initNanoTime(timeoutNanos);
                remainingNanos = timeoutNanos;
              } else {
                remainingNanos = remainingNanos(startTime, timeoutNanos);
              }
              satisfied = awaitNanos(guard, remainingNanos, signalBeforeWaiting);
            }
            return satisfied;
          } catch (InterruptedException interrupt) {
            interrupted = true;
            signalBeforeWaiting = false;
          }
        }
      } finally {
        if (!satisfied) {
          lock.unlock(); // No need to signal if timed out
        }
      }
    } finally {
      if (interrupted) {
        Thread.currentThread().interrupt();
      }
    }
  }

  /**
   * Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but does
   * not wait for the guard to be satisfied.
   *
   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
   */
  public boolean enterIf(Guard guard) {
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    final ReentrantLock lock = this.lock;
    lock.lock();

    boolean satisfied = false;
    try {
      return satisfied = guard.isSatisfied();
    } finally {
      if (!satisfied) {
        lock.unlock();
      }
    }
  }

  /**
   * Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the
   * lock, but does not wait for the guard to be satisfied.
   *
   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
   */
  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
  public boolean enterIf(Guard guard, long time, TimeUnit unit) {
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    if (!enter(time, unit)) {
      return false;
    }

    boolean satisfied = false;
    try {
      return satisfied = guard.isSatisfied();
    } finally {
      if (!satisfied) {
        lock.unlock();
      }
    }
  }

  /**
   * Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but does
   * not wait for the guard to be satisfied, and may be interrupted.
   *
   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
   * @throws InterruptedException if interrupted while waiting
   */
  public boolean enterIfInterruptibly(Guard guard) throws InterruptedException {
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();

    boolean satisfied = false;
    try {
      return satisfied = guard.isSatisfied();
    } finally {
      if (!satisfied) {
        lock.unlock();
      }
    }
  }

  /**
   * Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the
   * lock, but does not wait for the guard to be satisfied, and may be interrupted.
   *
   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
   */
  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
  public boolean enterIfInterruptibly(Guard guard, long time, TimeUnit unit)
      throws InterruptedException {
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    final ReentrantLock lock = this.lock;
    if (!lock.tryLock(time, unit)) {
      return false;
    }

    boolean satisfied = false;
    try {
      return satisfied = guard.isSatisfied();
    } finally {
      if (!satisfied) {
        lock.unlock();
      }
    }
  }

  /**
   * Enters this monitor if it is possible to do so immediately and the guard is satisfied. Does not
   * block acquiring the lock and does not wait for the guard to be satisfied.
   *
   *
Note: This method disregards the fairness setting of this monitor.
   *
   * @return whether the monitor was entered, which guarantees that the guard is now satisfied
   */
  public boolean tryEnterIf(Guard guard) {
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    final ReentrantLock lock = this.lock;
    if (!lock.tryLock()) {
      return false;
    }

    boolean satisfied = false;
    try {
      return satisfied = guard.isSatisfied();
    } finally {
      if (!satisfied) {
        lock.unlock();
      }
    }
  }

  /**
   * Waits for the guard to be satisfied. Waits indefinitely, but may be interrupted. May be called
   * only by a thread currently occupying this monitor.
   *
   * @throws InterruptedException if interrupted while waiting
   */
  public void waitFor(Guard guard) throws InterruptedException {
    if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) {
      throw new IllegalMonitorStateException();
    }
    if (!guard.isSatisfied()) {
      await(guard, true);
    }
  }

  /**
   * Waits for the guard to be satisfied. Waits at most the given time, and may be interrupted. May
   * be called only by a thread currently occupying this monitor.
   *
   * @return whether the guard is now satisfied
   * @throws InterruptedException if interrupted while waiting
   */
  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
  public boolean waitFor(Guard guard, long time, TimeUnit unit) throws InterruptedException {
    final long timeoutNanos = toSafeNanos(time, unit);
    if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) {
      throw new IllegalMonitorStateException();
    }
    if (guard.isSatisfied()) {
      return true;
    }
    if (Thread.interrupted()) {
      throw new InterruptedException();
    }
    return awaitNanos(guard, timeoutNanos, true);
  }

  /**
   * Waits for the guard to be satisfied. Waits indefinitely. May be called only by a thread
   * currently occupying this monitor.
   */
  public void waitForUninterruptibly(Guard guard) {
    if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) {
      throw new IllegalMonitorStateException();
    }
    if (!guard.isSatisfied()) {
      awaitUninterruptibly(guard, true);
    }
  }

  /**
   * Waits for the guard to be satisfied. Waits at most the given time. May be called only by a
   * thread currently occupying this monitor.
   *
   * @return whether the guard is now satisfied
   */
  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
  public boolean waitForUninterruptibly(Guard guard, long time, TimeUnit unit) {
    final long timeoutNanos = toSafeNanos(time, unit);
    if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) {
      throw new IllegalMonitorStateException();
    }
    if (guard.isSatisfied()) {
      return true;
    }
    boolean signalBeforeWaiting = true;
    final long startTime = initNanoTime(timeoutNanos);
    boolean interrupted = Thread.interrupted();
    try {
      for (long remainingNanos = timeoutNanos; ; ) {
        try {
          return awaitNanos(guard, remainingNanos, signalBeforeWaiting);
        } catch (InterruptedException interrupt) {
          interrupted = true;
          if (guard.isSatisfied()) {
            return true;
          }
          signalBeforeWaiting = false;
          remainingNanos = remainingNanos(startTime, timeoutNanos);
        }
      }
    } finally {
      if (interrupted) {
        Thread.currentThread().interrupt();
      }
    }
  }

  /** Leaves this monitor. May be called only by a thread currently occupying this monitor. */
  public void leave() {
    final ReentrantLock lock = this.lock;
    try {
      // No need to signal if we will still be holding the lock when we return
      if (lock.getHoldCount() == 1) {
        signalNextWaiter();
      }
    } finally {
      lock.unlock(); // Will throw IllegalMonitorStateException if not held
    }
  }

  /** Returns whether this monitor is using a fair ordering policy. */
  public boolean isFair() {
    return fair;
  }

  /**
   * Returns whether this monitor is occupied by any thread. This method is designed for use in
   * monitoring of the system state, not for synchronization control.
   */
  public boolean isOccupied() {
    return lock.isLocked();
  }

  /**
   * Returns whether the current thread is occupying this monitor (has entered more times than it
   * has left).
   */
  public boolean isOccupiedByCurrentThread() {
    return lock.isHeldByCurrentThread();
  }

  /**
   * Returns the number of times the current thread has entered this monitor in excess of the number
   * of times it has left. Returns 0 if the current thread is not occupying this monitor.
   */
  public int getOccupiedDepth() {
    return lock.getHoldCount();
  }

  /**
   * Returns an estimate of the number of threads waiting to enter this monitor. The value is only
   * an estimate because the number of threads may change dynamically while this method traverses
   * internal data structures. This method is designed for use in monitoring of the system state,
   * not for synchronization control.
   */
  public int getQueueLength() {
    return lock.getQueueLength();
  }

  /**
   * Returns whether any threads are waiting to enter this monitor. Note that because cancellations
   * may occur at any time, a {@code true} return does not guarantee that any other thread will ever
   * enter this monitor. This method is designed primarily for use in monitoring of the system
   * state.
   */
  public boolean hasQueuedThreads() {
    return lock.hasQueuedThreads();
  }

  /**
   * Queries whether the given thread is waiting to enter this monitor. Note that because
   * cancellations may occur at any time, a {@code true} return does not guarantee that this thread
   * will ever enter this monitor. This method is designed primarily for use in monitoring of the
   * system state.
   */
  public boolean hasQueuedThread(Thread thread) {
    return lock.hasQueuedThread(thread);
  }

  /**
   * Queries whether any threads are waiting for the given guard to become satisfied. Note that
   * because timeouts and interrupts may occur at any time, a {@code true} return does not guarantee
   * that the guard becoming satisfied in the future will awaken any threads. This method is
   * designed primarily for use in monitoring of the system state.
   */
  public boolean hasWaiters(Guard guard) {
    return getWaitQueueLength(guard) > 0;
  }

  /**
   * Returns an estimate of the number of threads waiting for the given guard to become satisfied.
   * Note that because timeouts and interrupts may occur at any time, the estimate serves only as an
   * upper bound on the actual number of waiters. This method is designed for use in monitoring of
   * the system state, not for synchronization control.
   */
  public int getWaitQueueLength(Guard guard) {
    if (guard.monitor != this) {
      throw new IllegalMonitorStateException();
    }
    lock.lock();
    try {
      return guard.waiterCount;
    } finally {
      lock.unlock();
    }
  }

  /**
   * Returns unit.toNanos(time), additionally ensuring the returned value is not at risk of
   * overflowing or underflowing, by bounding the value between 0 and (Long.MAX_VALUE / 4) * 3.
   * Actually waiting for more than 219 years is not supported!
   */
  private static long toSafeNanos(long time, TimeUnit unit) {
    long timeoutNanos = unit.toNanos(time);
    return (timeoutNanos <= 0L)
        ? 0L
        : (timeoutNanos > (Long.MAX_VALUE / 4) * 3) ? (Long.MAX_VALUE / 4) * 3 : timeoutNanos;
  }

  /**
   * Returns System.nanoTime() unless the timeout has already elapsed. Returns 0L if and only if the
   * timeout has already elapsed.
   */
  private static long initNanoTime(long timeoutNanos) {
    if (timeoutNanos <= 0L) {
      return 0L;
    } else {
      long startTime = System.nanoTime();
      return (startTime == 0L) ? 1L : startTime;
    }
  }

  /**
   * Returns the remaining nanos until the given timeout, or 0L if the timeout has already elapsed.
   * Caller must have previously sanitized timeoutNanos using toSafeNanos.
   */
  private static long remainingNanos(long startTime, long timeoutNanos) {
    // assert timeoutNanos == 0L || startTime != 0L;

    // TODO : NOT CORRECT, BUT TESTS PASS ANYWAYS!
    // if (true) return timeoutNanos;
    // ONLY 2 TESTS FAIL IF WE DO:
    // if (true) return 0;

    return (timeoutNanos <= 0L) ? 0L : timeoutNanos - (System.nanoTime() - startTime);
  }

  /**
   * Signals some other thread waiting on a satisfied guard, if one exists.
   *
   *
We manage calls to this method carefully, to signal only when necessary, but never losing a
   * signal, which is the classic problem of this kind of concurrency construct. We must signal if
   * the current thread is about to relinquish the lock and may have changed the state protected by
   * the monitor, thereby causing some guard to be satisfied.
   *
   *
In addition, any thread that has been signalled when its guard was satisfied acquires the
   * responsibility of signalling the next thread when it again relinquishes the lock. Unlike a
   * normal Condition, there is no guarantee that an interrupted thread has not been signalled,
   * since the concurrency control must manage multiple Conditions. So this method must generally be
   * called when waits are interrupted.
   *
   *
On the other hand, if a signalled thread wakes up to discover that its guard is still not
   * satisfied, it does *not* need to call this method before returning to wait. This can only
   * happen due to spurious wakeup (ignorable) or another thread acquiring the lock before the
   * current thread can and returning the guard to the unsatisfied state. In the latter case the
   * other thread (last thread modifying the state protected by the monitor) takes over the
   * responsibility of signalling the next waiter.
   *
   *
This method must not be called from within a beginWaitingFor/endWaitingFor block, or else
   * the current thread's guard might be mistakenly signalled, leading to a lost signal.
   */
  @GuardedBy("lock")
  private void signalNextWaiter() {
    for (Guard guard = activeGuards; guard != null; guard = guard.next) {
      if (isSatisfied(guard)) {
        guard.condition.signal();
        break;
      }
    }
  }

  /**
   * Exactly like signalNextWaiter, but caller guarantees that guardToSkip need not be considered,
   * because caller has previously checked that guardToSkip.isSatisfied() returned false. An
   * optimization for the case that guardToSkip.isSatisfied() may be expensive.
   *
   *
We decided against using this method, since in practice, isSatisfied() is likely to be very
   * cheap (typically one field read). Resurrect this method if you find that not to be true.
   */
  //   @GuardedBy("lock")
  //   private void signalNextWaiterSkipping(Guard guardToSkip) {
  //     for (Guard guard = activeGuards; guard != null; guard = guard.next) {
  //       if (guard != guardToSkip && isSatisfied(guard)) {
  //         guard.condition.signal();
  //         break;
  //       }
  //     }
  //   }

  /**
   * Exactly like guard.isSatisfied(), but in addition signals all waiting threads in the (hopefully
   * unlikely) event that isSatisfied() throws.
   */
  @GuardedBy("lock")
  private boolean isSatisfied(Guard guard) {
    try {
      return guard.isSatisfied();
    } catch (Throwable throwable) {
      signalAllWaiters();
      throw throwable;
    }
  }

  /** Signals all threads waiting on guards. */
  @GuardedBy("lock")
  private void signalAllWaiters() {
    for (Guard guard = activeGuards; guard != null; guard = guard.next) {
      guard.condition.signalAll();
    }
  }

  /** Records that the current thread is about to wait on the specified guard. */
  @GuardedBy("lock")
  private void beginWaitingFor(Guard guard) {
    int waiters = guard.waiterCount++;
    if (waiters == 0) {
      // push guard onto activeGuards
      guard.next = activeGuards;
      activeGuards = guard;
    }
  }

  /** Records that the current thread is no longer waiting on the specified guard. */
  @GuardedBy("lock")
  private void endWaitingFor(Guard guard) {
    int waiters = --guard.waiterCount;
    if (waiters == 0) {
      // unlink guard from activeGuards
      for (Guard p = activeGuards, pred = null; ; pred = p, p = p.next) {
        if (p == guard) {
          if (pred == null) {
            activeGuards = p.next;
          } else {
            pred.next = p.next;
          }
          p.next = null; // help GC
          break;
        }
      }
    }
  }

  /*
   * Methods that loop waiting on a guard's condition until the guard is satisfied, while recording
   * this fact so that other threads know to check our guard and signal us. It's caller's
   * responsibility to ensure that the guard is *not* currently satisfied.
   */

  @GuardedBy("lock")
  private void await(Guard guard, boolean signalBeforeWaiting) throws InterruptedException {
    if (signalBeforeWaiting) {
      signalNextWaiter();
    }
    beginWaitingFor(guard);
    try {
      do {
        guard.condition.await();
      } while (!guard.isSatisfied());
    } finally {
      endWaitingFor(guard);
    }
  }

  @GuardedBy("lock")
  private void awaitUninterruptibly(Guard guard, boolean signalBeforeWaiting) {
    if (signalBeforeWaiting) {
      signalNextWaiter();
    }
    beginWaitingFor(guard);
    try {
      do {
        guard.condition.awaitUninterruptibly();
      } while (!guard.isSatisfied());
    } finally {
      endWaitingFor(guard);
    }
  }

  /** Caller should check before calling that guard is not satisfied. */
  @GuardedBy("lock")
  private boolean awaitNanos(Guard guard, long nanos, boolean signalBeforeWaiting)
      throws InterruptedException {
    boolean firstTime = true;
    try {
      do {
        if (nanos <= 0L) {
          return false;
        }
        if (firstTime) {
          if (signalBeforeWaiting) {
            signalNextWaiter();
          }
          beginWaitingFor(guard);
          firstTime = false;
        }
        nanos = guard.condition.awaitNanos(nanos);
      } while (!guard.isSatisfied());
      return true;
    } finally {
      if (!firstTime) {
        endWaitingFor(guard);
      }
    }
  }
}


/*
 * Copyright (C) 2007 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.collect;

import com.google.common.annotations.GwtCompatible;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.NavigableSet;
import java.util.SortedSet;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * Basic implementation of the {@link SortedSetMultimap} interface. It's a wrapper around {@link
 * AbstractMapBasedMultimap} that converts the returned collections into sorted sets. The {@link
 * #createCollection} method must return a {@code SortedSet}.
 *
 * @author Jared Levy
 */
@GwtCompatible
abstract class AbstractSortedSetMultimap<K, V> extends AbstractSetMultimap<K, V>
    implements SortedSetMultimap<K, V> {
  /**
   * Creates a new multimap that uses the provided map.
   *
   * @param map place to store the mapping from each key to its corresponding values
   */
  protected AbstractSortedSetMultimap(Map<K, Collection<V>> map) {
    super(map);
  }

  @Override
  abstract SortedSet<V> createCollection();

  @Override
  SortedSet<V> createUnmodifiableEmptyCollection() {
    return unmodifiableCollectionSubclass(createCollection());
  }

  @Override
  <E> SortedSet<E> unmodifiableCollectionSubclass(Collection<E> collection) {
    if (collection instanceof NavigableSet) {
      return Sets.unmodifiableNavigableSet((NavigableSet<E>) collection);
    } else {
      return Collections.unmodifiableSortedSet((SortedSet<E>) collection);
    }
  }

  @Override
  Collection<V> wrapCollection(K key, Collection<V> collection) {
    if (collection instanceof NavigableSet) {
      return new WrappedNavigableSet(key, (NavigableSet<V>) collection, null);
    } else {
      return new WrappedSortedSet(key, (SortedSet<V>) collection, null);
    }
  }

  // Following Javadoc copied from Multimap and SortedSetMultimap.

  /**
   * Returns a collection view of all values associated with a key. If no mappings in the multimap
   * have the provided key, an empty collection is returned.
   *
   *
Changes to the returned collection will update the underlying multimap, and vice versa.
   *
   *
Because a {@code SortedSetMultimap} has unique sorted values for a given key, this method
   * returns a {@link SortedSet}, instead of the {@link Collection} specified in the {@link
   * Multimap} interface.
   */
  @Override
  public SortedSet<V> get(@NullableDecl K key) {
    return (SortedSet<V>) super.get(key);
  }

  /**
   * Removes all values associated with a given key. The returned collection is immutable.
   *
   *
Because a {@code SortedSetMultimap} has unique sorted values for a given key, this method
   * returns a {@link SortedSet}, instead of the {@link Collection} specified in the {@link
   * Multimap} interface.
   */
  @CanIgnoreReturnValue
  @Override
  public SortedSet<V> removeAll(@NullableDecl Object key) {
    return (SortedSet<V>) super.removeAll(key);
  }

  /**
   * Stores a collection of values with the same key, replacing any existing values for that key.
   * The returned collection is immutable.
   *
   *
Because a {@code SortedSetMultimap} has unique sorted values for a given key, this method
   * returns a {@link SortedSet}, instead of the {@link Collection} specified in the {@link
   * Multimap} interface.
   *
   *
Any duplicates in {@code values} will be stored in the multimap once.
   */
  @CanIgnoreReturnValue
  @Override
  public SortedSet<V> replaceValues(@NullableDecl K key, Iterable<? extends V> values) {
    return (SortedSet<V>) super.replaceValues(key, values);
  }

  /**
   * Returns a map view that associates each key with the corresponding values in the multimap.
   * Changes to the returned map, such as element removal, will update the underlying multimap. The
   * map does not support {@code setValue} on its entries, {@code put}, or {@code putAll}.
   *
   *
When passed a key that is present in the map, {@code asMap().get(Object)} has the same
   * behavior as {@link #get}, returning a live collection. When passed a key that is not present,
   * however, {@code asMap().get(Object)} returns {@code null} instead of an empty collection.
   *
   *
Though the method signature doesn't say so explicitly, the returned map has {@link
   * SortedSet} values.
   */
  @Override
  public Map<K, Collection<V>> asMap() {
    return super.asMap();
  }

  /**
   * {@inheritDoc}
   *
   *
Consequently, the values do not follow their natural ordering or the ordering of the value
   * comparator.
   */
  @Override
  public Collection<V> values() {
    return super.values();
  }

  private static final long serialVersionUID = 430848587173315748L;
}


/*
 * Copyright 2017-2019 CodingApi .
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.codingapi.txlcn.tc.txmsg;

import com.codingapi.txlcn.txmsg.exception.RpcException;
import com.codingapi.txlcn.tc.config.TxClientConfig;
import com.codingapi.txlcn.tc.support.listener.RpcEnvStatusListener;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Description:
 * Date: 1/27/19
 *
 * @author ujued
 */
@Component
@Slf4j
public class AutoTMClusterEngine implements RpcEnvStatusListener {

    private AtomicInteger tryConnectCount = new AtomicInteger(0);

    private final TxClientConfig txClientConfig;

    private final ReliableMessenger reliableMessenger;

    @Autowired
    public AutoTMClusterEngine(TxClientConfig txClientConfig, ReliableMessenger reliableMessenger) {
        this.txClientConfig = txClientConfig;
        this.reliableMessenger = reliableMessenger;
    }

    @Override
    public void onConnected(String remoteKey) {

    }

    @Override
    public void onInitialized(String remoteKey) {
        if (prepareToResearchTMCluster()) {
            TMSearcher.echoTmClusterSize();
        }
    }

    @Override
    public void onConnectFail(String remoteKey) {
        try {
            reliableMessenger.reportInvalidTM(Sets.newHashSet(remoteKey));
        } catch (RpcException e) {
            log.error("{} on reportInvalidTM.", e.getMessage());
        }
        if (prepareToResearchTMCluster()) {
            TMSearcher.echoTmClusterSize();
        }
    }

    /**
     * 准备搜索TM
     *
     * @return true 搜索结束
     */
    private boolean prepareToResearchTMCluster() {
        int count = tryConnectCount.incrementAndGet();
        int size = txClientConfig.getManagerAddress().size();
        if (count == size) {
            TMSearcher.search();
            return false;
        } else if (count > size) {
            return !TMSearcher.searchedOne();
        }
        return true;
    }
}


/*
 * Copyright 2017-2019 CodingApi .
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.codingapi.txlcn.tm.support.restapi;

import com.alibaba.fastjson.JSONObject;
import com.codingapi.txlcn.common.exception.FastStorageException;
import com.codingapi.txlcn.common.exception.TransactionStateException;
import com.codingapi.txlcn.common.exception.TxManagerException;
import com.codingapi.txlcn.tm.cluster.TMProperties;
import com.codingapi.txlcn.tm.core.storage.FastStorage;
import com.codingapi.txlcn.tm.support.restapi.vo.*;
import com.codingapi.txlcn.tm.support.service.AdminService;
import com.codingapi.txlcn.tm.support.service.TxExceptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Description:
 * Date: 2018/12/28
 *
 * @author ujued
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    private final AdminService adminService;

    private final TxExceptionService txExceptionService;

    @Autowired
    public AdminController(AdminService adminService, TxExceptionService txExceptionService, FastStorage fastStorage) {
        this.adminService = adminService;
        this.txExceptionService = txExceptionService;
        this.fastStorage = fastStorage;
    }

    @PostMapping("/login")
    public Token login(@RequestParam("password") String password) throws TxManagerException {
        return new Token(adminService.login(password));
    }

    /**
     * 获取补偿信息
     *
     * @param page      页码
     * @param limit     记录数
     * @param extState  extState
     * @param registrar registrar
     * @return ExceptionList
     */
    @GetMapping({"/exceptions/{page}", "/exceptions", "/exceptions/{page}/{limit}"})
    public ExceptionList exceptionList(
            @RequestParam(value = "page", required = false) @PathVariable(value = "page", required = false) Integer page,
            @RequestParam(value = "limit", required = false) @PathVariable(value = "limit", required = false) Integer limit,
            @RequestParam(value = "extState", required = false) Integer extState,
            @RequestParam(value = "registrar", required = false) Integer registrar) {
        return txExceptionService.exceptionList(page, limit, extState, null, registrar);
    }

    /**
     * 删除异常信息
     *
     * @param deleteExceptions 异常信息标示
     * @return 操作结果
     * @throws TxManagerException TxManagerException
     */
    @PostMapping("/exceptions")
    public boolean deleteExceptions(@RequestBody DeleteExceptions deleteExceptions) throws TxManagerException {
        txExceptionService.deleteExceptions(deleteExceptions.getId());
        return true;
    }

    /**
     * 获取某个事务组某个节点具体补偿信息
     *
     * @param groupId groupId
     * @param unitId  unitId
     * @return transaction info
     * @throws TxManagerException TxManagerException
     */
    @GetMapping("/log/transaction-info")
    public JSONObject transactionInfo(
            @RequestParam("groupId") String groupId,
            @RequestParam("unitId") String unitId) throws TxManagerException {
        try {
            return txExceptionService.getTransactionInfo(groupId, unitId);
        } catch (TransactionStateException e) {
            throw new TxManagerException(e);
        }
    }

    /**
     * 日志信息
     *
     * @param page      页码
     * @param limit     记录数
     * @param groupId   groupId
     * @param tag       tag
     * @param lTime     lTime
     * @param rTime     rtime
     * @param timeOrder timeOrder
     * @return TxLogList
     * @throws TxManagerException TxManagerException
     */
    @GetMapping({"/logs/{page}", "/logs/{page}/{limit}", "/logs"})
    public TxLogList txLogList(
            @RequestParam(value = "page", required = false) @PathVariable(value = "page", required = false) Integer page,
            @RequestParam(value = "limit", required = false) @PathVariable(value = "limit", required = false) Integer limit,
            @RequestParam(value = "groupId", required = false) String groupId,
            @RequestParam(value = "tag", required = false) String tag,
            @RequestParam(value = "ld", required = false) String lTime,
            @RequestParam(value = "rd", required = false) String rTime,
            @RequestParam(value = "timeOrder", required = false) Integer timeOrder) throws TxManagerException {
        return adminService.txLogList(page, limit, groupId, tag, lTime, rTime, timeOrder);
    }

    @GetMapping({"/app-mods/{page}", "/app-mods/{page}/{limit}", "/app-mods"})
    public ListAppMods listAppMods(
            @PathVariable(value = "page", required = false) @RequestParam(value = "page", required = false) Integer page,
            @PathVariable(value = "limit", required = false) @RequestParam(value = "limit", required = false) Integer limit) {
        return adminService.listAppMods(page, limit);
    }

    /**
     * 删除日志
     *
     * @param deleteLogsReq deleteLogsReq
     * @return bool
     * @throws TxManagerException TxManagerException
     */
    @DeleteMapping("/logs")
    public boolean deleteLogs(@RequestBody DeleteLogsReq deleteLogsReq) throws TxManagerException {
        adminService.deleteLogs(deleteLogsReq);
        return true;
    }

    /**
     * 删除异常事务信息
     *
     * @param groupId groupId
     * @param unitId  unitId
     * @param modId   modId
     * @return result always true if non exception
     * @throws TxManagerException TxManagerException
     */
    @DeleteMapping("/transaction-info")
    public boolean deleteTransactionInfo(
            @RequestParam("groupId") String groupId,
            @RequestParam("unitId") String unitId,
            @RequestParam("modId") String modId) throws TxManagerException {
        txExceptionService.deleteTransactionInfo(groupId, unitId, modId);
        return true;
    }

    /**
     * 获取TxManager信息
     *
     * @return TxManagerInfo
     */
    @GetMapping("/tx-manager")
    public TxManagerInfo getTxManagerInfo() {
        return adminService.getTxManagerInfo();
    }

    private final FastStorage fastStorage;

    @GetMapping("/tm-cluster")
    public List<TMProperties> tmList() throws FastStorageException {
        return fastStorage.findTMProperties();
    }
}


/*
 * Copyright 2017-2019 CodingApi .
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.codingapi.txlcn.tc.txmsg;

import com.codingapi.txlcn.common.exception.LcnBusinessException;
import com.codingapi.txlcn.tc.config.TxClientConfig;
import com.codingapi.txlcn.txmsg.MessageConstants;
import com.codingapi.txlcn.txmsg.RpcClient;
import com.codingapi.txlcn.txmsg.dto.MessageDto;
import com.codingapi.txlcn.txmsg.exception.RpcException;
import com.codingapi.txlcn.txmsg.params.JoinGroupParams;
import com.codingapi.txlcn.txmsg.params.NotifyGroupParams;
import com.codingapi.txlcn.txmsg.util.MessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * Description:
 * Date: 19-1-22 下午5:12
 *
 * @author ujued
 */
@Component
@Slf4j
public class LoopMessenger implements ReliableMessenger {

    private final RpcClient rpcClient;

    private final TxClientConfig clientConfig;

    @Autowired
    public LoopMessenger(RpcClient rpcClient, TxClientConfig clientConfig) {
        this.rpcClient = rpcClient;
        this.clientConfig = clientConfig;
    }

    @Override
    public boolean acquireLocks(String groupId, Set<String> lockIdSet, int type) throws RpcException {
        MessageDto messageDto = request(MessageCreator.acquireLocks(groupId, lockIdSet, type));
        return MessageUtils.statusOk(messageDto);
    }

    @Override
    public void releaseLocks(Set<String> lockIdList) throws RpcException {
        MessageDto messageDto = request(MessageCreator.releaseLocks(lockIdList));
        if (!MessageUtils.statusOk(messageDto)) {
            throw new RpcException("release locks fail.");
        }
    }

    @Override
    public int notifyGroup(String groupId, int transactionState) throws RpcException, LcnBusinessException {
        NotifyGroupParams notifyGroupParams = new NotifyGroupParams();
        notifyGroupParams.setGroupId(groupId);
        notifyGroupParams.setState(transactionState);
        MessageDto messageDto = request0(MessageCreator.notifyGroup(notifyGroupParams),
                clientConfig.getTmRpcTimeout() * clientConfig.getChainLevel());
        // 成功清理发起方事务
        if (!MessageUtils.statusOk(messageDto)) {
            throw new LcnBusinessException(messageDto.loadBean(Throwable.class));
        }
        return messageDto.loadBean(Integer.class);
    }

    @Override
    public void joinGroup(String groupId, String unitId, String unitType, int transactionState) throws RpcException, LcnBusinessException {
        JoinGroupParams joinGroupParams = new JoinGroupParams();
        joinGroupParams.setGroupId(groupId);
        joinGroupParams.setUnitId(unitId);
        joinGroupParams.setUnitType(unitType);
        joinGroupParams.setTransactionState(transactionState);
        MessageDto messageDto = request(MessageCreator.joinGroup(joinGroupParams));
        if (!MessageUtils.statusOk(messageDto)) {
            throw new LcnBusinessException(messageDto.loadBean(Throwable.class));
        }
    }

    @Override
    public void createGroup(String groupId) throws RpcException, LcnBusinessException {
        // TxManager创建事务组
        MessageDto messageDto = request(MessageCreator.createGroup(groupId));
        if (!MessageUtils.statusOk(messageDto)) {
            throw new LcnBusinessException(messageDto.loadBean(Throwable.class));
        }
    }

    @Override
    public int askTransactionState(String groupId, String unitId) throws RpcException {
        MessageDto messageDto = request(MessageCreator.askTransactionState(groupId, unitId));
        if (MessageUtils.statusOk(messageDto)) {
            return messageDto.loadBean(Integer.class);
        }
        return -1;
    }

    @Override
    public void reportInvalidTM(HashSet<String> invalidTMSet) throws RpcException {
        MessageDto messageDto = new MessageDto();
        messageDto.setAction(MessageConstants.ACTION_CLEAN_INVALID_TM);
        messageDto.setData(invalidTMSet);
        messageDto = request(messageDto);
        if (!MessageUtils.statusOk(messageDto)) {
            throw new RpcException(messageDto.loadBean(Throwable.class));
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public HashSet<String> queryTMCluster() throws RpcException {
        MessageDto messageDto = new MessageDto();
        messageDto.setAction(MessageConstants.ACTION_QUERY_TM_CLUSTER);
        messageDto = request(messageDto);
        if (MessageUtils.statusOk(messageDto)) {
            return messageDto.loadBean(HashSet.class);
        }
        throw new RpcException(messageDto.loadBean(Throwable.class));
    }

    @Override
    public MessageDto request(MessageDto messageDto) throws RpcException {
        return request0(messageDto, -1);
    }

    private MessageDto request0(MessageDto messageDto, long timeout) throws RpcException {
        return request(messageDto, timeout, "request fail");
    }

    @Override
    public int clusterSize() {
        return rpcClient.loadAllRemoteKey().size();
    }

    /**
     * 强通讯
     *
     * @param messageDto            通讯数据
     * @param whenNonManagerMessage 异常提示
     * @return MessageDto
     * @throws RpcException RpcException
     */
    private MessageDto request(MessageDto messageDto, long timeout, String whenNonManagerMessage) throws RpcException {
        for (int i = 0; i < rpcClient.loadAllRemoteKey().size() + 1; i++) {
            try {
                String remoteKey = rpcClient.loadRemoteKey();
                MessageDto result = rpcClient.request(remoteKey, messageDto, timeout);
                log.debug("request action: {}. TM[{}]", messageDto.getAction(), remoteKey);
                return result;
            } catch (RpcException e) {
                if (e.getCode() == RpcException.NON_TX_MANAGER) {
                    throw new RpcException(e.getCode(), whenNonManagerMessage + ". non tx-manager is alive.");
                }
            }
        }
        throw new RpcException(RpcException.NON_TX_MANAGER, whenNonManagerMessage + ". non tx-manager is alive.");
    }
}


/*
 * Copyright 2017-2019 CodingApi .
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.codingapi.txlcn.common.util.id;

/**
 * Description:
 * Date: 19-1-30 下午8:10
 *
 * @author Twitter
 * @author 无始之名
 */
public class SnowFlakeGenerator {

    public static class Factory {
        /**
         * 机器标识占用的位数
         */
        private final static int DEFAULT_MACHINE_BIT_NUM = 5;

        /**
         * 数据中心占用的位数
         */
        private final static int DEFAULT_IDC_BIT_NUM = 5;

        private int machineBitNum;
        private int idcBitNum;

        public Factory() {
            this.idcBitNum = DEFAULT_IDC_BIT_NUM;
            this.machineBitNum = DEFAULT_MACHINE_BIT_NUM;
        }

        public Factory(int machineBitNum, int idcBitNum) {
            this.idcBitNum = idcBitNum;
            this.machineBitNum = machineBitNum;
        }

        public SnowFlakeGenerator create(long idcId, long machineId) {
            return new SnowFlakeGenerator(this.idcBitNum, this.machineBitNum, idcId, machineId);
        }
    }

    /**
     * 起始的时间戳 UTC+8:00 2019-01-01 0:0:0 000
     */
    private final static long START_STAMP = 1546272000000L;

    /**
     * 可分配的位数
     */
    private final static int REMAIN_BIT_NUM = 22;

    /**
     * idc编号
     */
    private long idcId;

    /**
     * 机器编号
     */
    private long machineId;

    /**
     * 当前序列号
     */
    private long sequence = 0L;

    /**
     * 上次最新时间戳
     */
    private long lastStamp = -1L;

    /**
     * idc偏移量：一次计算出，避免重复计算
     */
    private int idcBitLeftOffset;

    /**
     * 机器id偏移量：一次计算出，避免重复计算
     */
    private int machineBitLeftOffset;

    /**
     * 时间戳偏移量：一次计算出，避免重复计算
     */
    private int timestampBitLeftOffset;

    /**
     * 最大序列值：一次计算出，避免重复计算
     */
    private int maxSequenceValue;

    private SnowFlakeGenerator(int idcBitNum, int machineBitNum, long idcId, long machineId) {
        int sequenceBitNum = REMAIN_BIT_NUM - idcBitNum - machineBitNum;

        if (idcBitNum < 0 || machineBitNum <= 0 || sequenceBitNum <= 0) {
            throw new IllegalArgumentException("Error bit number");
        }

        this.maxSequenceValue = ~(-1 << sequenceBitNum);

        machineBitLeftOffset = sequenceBitNum;
        idcBitLeftOffset = machineBitNum + sequenceBitNum;
        timestampBitLeftOffset = idcBitNum + machineBitNum + sequenceBitNum;

        this.idcId = idcId;
        this.machineId = machineId;
    }

    /**
     * 产生下一个ID
     * @return id
     */
    public synchronized long nextId() {
        long currentStamp = getTimeMill();
        if (currentStamp < lastStamp) {
            throw new RuntimeException("Clock moved backwards.");
        }

        if (currentStamp == lastStamp) {
            sequence = (sequence + 1) & this.maxSequenceValue;
            if (sequence == 0L) {
                lastStamp = tilNextMillis();
            }
        } else {
            sequence = 0L;
        }

        lastStamp = currentStamp;

        return (currentStamp - START_STAMP) <<
                timestampBitLeftOffset | idcId << idcBitLeftOffset | machineId << machineBitLeftOffset | sequence;
    }

    private long getTimeMill() {
        return System.currentTimeMillis();
    }

    private long tilNextMillis() {
        long timestamp = getTimeMill();
        while (timestamp <= lastStamp) {
            timestamp = getTimeMill();
        }
        return timestamp;
    }

}


package com.codingapi.txlcn.tracing;

import com.codingapi.txlcn.common.util.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.Optional;

/**
 * Description: DTX Tracing 工具
 * Date: 19-2-11 下午1:02
 *
 * @author ujued
 */
@Slf4j
public class Tracings {

    /**
     * 私有构造器
     */
    private Tracings() {
    }

    /**
     * 传输Tracing信息
     *
     * @param tracingSetter Tracing信息设置器
     */
    public static void transmit(TracingSetter tracingSetter) {
        if (TracingContext.tracing().hasGroup()) {
            log.debug("tracing transmit group:{}", TracingContext.tracing().groupId());
            tracingSetter.set(TracingConstants.HEADER_KEY_GROUP_ID, TracingContext.tracing().groupId());
            tracingSetter.set(TracingConstants.HEADER_KEY_APP_MAP,
                    Base64Utils.encodeToString(TracingContext.tracing().appMapString().getBytes(StandardCharsets.UTF_8)));
        }
    }

    /**
     * 获取传输的Tracing信息
     *
     * @param tracingGetter Tracing信息获取器
     */
    public static void apply(TracingGetter tracingGetter) {
        String groupId = Optional.ofNullable(tracingGetter.get(TracingConstants.HEADER_KEY_GROUP_ID)).orElse("");
        String appList = Optional.ofNullable(tracingGetter.get(TracingConstants.HEADER_KEY_APP_MAP)).orElse("");
        TracingContext.init(Maps.newHashMap(TracingConstants.GROUP_ID, groupId, TracingConstants.APP_MAP,
                StringUtils.isEmpty(appList) ? appList : new String(Base64Utils.decodeFromString(appList), StandardCharsets.UTF_8)));
        if (TracingContext.tracing().hasGroup()) {
            log.debug("tracing apply group:{}, app map:{}", groupId, appList);
        }
    }

    /**
     * Tracing信息设置器
     */
    public interface TracingSetter {
        /**
         * 设置tracing属性
         *
         * @param key   key
         * @param value value
         */
        void set(String key, String value);
    }

    /**
     * Tracing信息获取器
     */
    public interface TracingGetter {
        /**
         * 获取tracing属性
         *
         * @param key key
         * @return tracing value
         */
        String get(String key);
    }
}


/*
 * Copyright 2017-2019 CodingApi .
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.codingapi.txlcn.tc.txmsg;

import com.codingapi.txlcn.common.util.Transactions;
import com.codingapi.txlcn.txmsg.MessageConstants;
import com.codingapi.txlcn.txmsg.dto.MessageDto;
import com.codingapi.txlcn.txmsg.params.*;

import java.io.Serializable;
import java.util.Set;

/**
 * @author lorne
 */
public class MessageCreator {

    /**
     * 创建事务组
     *
     * @param groupId groupId
     * @return MessageDto
     */
    public static MessageDto createGroup(String groupId) {
        MessageDto msg = new MessageDto();
        msg.setGroupId(groupId);
        msg.setAction(MessageConstants.ACTION_CREATE_GROUP);
        return msg;
    }

    /**
     * 加入事务组
     *
     * @param joinGroupParams joinGroupParams
     * @return MessageDto
     */
    public static MessageDto joinGroup(JoinGroupParams joinGroupParams) {
        MessageDto msg = new MessageDto();
        msg.setGroupId(joinGroupParams.getGroupId());
        msg.setAction(MessageConstants.ACTION_JOIN_GROUP);
        msg.setData(joinGroupParams);
        return msg;
    }

    /**
     * 关闭事务组
     *
     * @param notifyGroupParams notifyGroupParams
     * @return MessageDto
     */
    public static MessageDto notifyGroup(NotifyGroupParams notifyGroupParams) {
        MessageDto msg = new MessageDto();
        msg.setGroupId(notifyGroupParams.getGroupId());
        msg.setAction(MessageConstants.ACTION_NOTIFY_GROUP);
        msg.setData(notifyGroupParams);
        return msg;
    }

    /**
     * 申请锁消息
     * @param groupId groupId
     * @param locks    locks
     * @param lockType lockType
     * @return message
     */
    public static MessageDto acquireLocks(String groupId, Set<String> locks, int lockType) {
        DTXLockParams dtxLockParams = new DTXLockParams();
        dtxLockParams.setGroupId(groupId);
        dtxLockParams.setContextId(Transactions.APPLICATION_ID_WHEN_RUNNING);
        dtxLockParams.setLocks(locks);
        dtxLockParams.setLockType(lockType);
        MessageDto messageDto = new MessageDto();
        messageDto.setAction(MessageConstants.ACTION_ACQUIRE_DTX_LOCK);
        messageDto.setData(dtxLockParams);
        return messageDto;
    }

    /**
     * 释放锁消息
     *
     * @param locks locks
     * @return message
     */
    public static MessageDto releaseLocks(Set<String> locks) {
        DTXLockParams dtxLockParams = new DTXLockParams();
        dtxLockParams.setContextId(Transactions.APPLICATION_ID_WHEN_RUNNING);
        dtxLockParams.setLocks(locks);
        MessageDto messageDto = new MessageDto();
        messageDto.setAction(MessageConstants.ACTION_RELEASE_DTX_LOCK);
        messageDto.setData(dtxLockParams);
        return messageDto;
    }

    /**
     * 通知事务单元成功
     *
     * @param message message
     * @param action  action
     * @return MessageDto
     */
    public static MessageDto notifyUnitOkResponse(Serializable message, String action) {
        MessageDto messageDto = new MessageDto();
        messageDto.setAction(action);
        messageDto.setState(MessageConstants.STATE_OK);
        messageDto.setData(message);
        return messageDto;
    }

    /**
     * 通知事务单元失败
     *
     * @param message message
     * @param action  action
     * @return MessageDto
     */
    public static MessageDto notifyUnitFailResponse(Serializable message, String action) {
        MessageDto messageDto = new MessageDto();
        messageDto.setState(MessageConstants.STATE_EXCEPTION);
        messageDto.setAction(action);
        messageDto.setData(message);
        return messageDto;
    }

    /**
     * 询问事务状态指令
     *
     * @param groupId groupId
     * @param unitId  unitId
     * @return MessageDto
     */
    public static MessageDto askTransactionState(String groupId, String unitId) {
        MessageDto messageDto = new MessageDto();
        messageDto.setGroupId(groupId);
        messageDto.setAction(MessageConstants.ACTION_ASK_TRANSACTION_STATE);
        messageDto.setData(new AskTransactionStateParams(groupId, unitId));
        return messageDto;
    }

    /**
     * 写异常信息指令
     *
     * @param txExceptionParams txExceptionParams
     * @return MessageDto
     */
    public static MessageDto writeTxException(TxExceptionParams txExceptionParams) {
        MessageDto messageDto = new MessageDto();
        messageDto.setAction(MessageConstants.ACTION_WRITE_EXCEPTION);
        messageDto.setGroupId(txExceptionParams.getGroupId());
        messageDto.setData(txExceptionParams);
        return messageDto;
    }

    /**
     * 初始化客户端请求
     *
     * @param appName   appName
     * @param labelName labelName
     * @return MessageDto
     */
    public static MessageDto initClient(String appName, String labelName) {
        InitClientParams initClientParams = new InitClientParams();
        initClientParams.setAppName(appName);
        initClientParams.setLabelName(labelName);
        MessageDto messageDto = new MessageDto();
        messageDto.setData(initClientParams);
        messageDto.setAction(MessageConstants.ACTION_INIT_CLIENT);
        return messageDto;
    }
}


package com.codingapi.txlcn.common.util.id;

import lombok.extern.slf4j.Slf4j;

/**
 * Description:
 * Date: 19-1-31 上午11:32
 *
 * @author ujued
 */
@Slf4j
public abstract class IdGenInit {

    /**
     * 原版雪花算法，生成一个long类型的ID
     *
     * @param machineLen 机器位长度
     * @param machineId  机器ID
     */
    public static void applySnowFlakeIdGen(int machineLen, long machineId) {
        SnowFlakeGenerator.Factory factory = new SnowFlakeGenerator.Factory(machineLen, 0);
        SnowFlakeGenerator snowFlakeGenerator = factory.create(0, machineId);
        RandomUtils.init(() -> String.valueOf(snowFlakeGenerator.nextId()));
    }

    /**
     * 默认ID生成。和雪花组成一样，加长了机器位，生成了更长的ID
     *
     * @param seqLen    序列位长度
     * @param machineId 机器ID
     */
    public static void applyDefaultIdGen(int seqLen, long machineId) {
        RandomUtils.init(new DefaultIdGen(seqLen, machineId));
    }
}


/**
 * P6Spy
 *
 * Copyright (C) 2002 - 2018 P6Spy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.codingapi.txlcn.tc.support.p6spy.common;

import java.util.HashMap;
import java.util.Map;

/**
 * Stores information about the callable statement and bind variables.
 *
 * @author Quinton McCombs
 * @since 09/2013
 */
public class CallableStatementInformation extends PreparedStatementInformation {
  private final Map<String, Value> namedParameterValues = new HashMap<String, Value>();

  public CallableStatementInformation(ConnectionInformation connectionInformation, String query) {
    super(connectionInformation, query);
  }

  /**
   * Generates the query for the callable statement with all parameter placeholders
   * replaced with the actual parameter values
   *
   * @return the SQL
   */
  @Override
  public String getSqlWithValues() {

    if( namedParameterValues.size() == 0 ) {
      return super.getSqlWithValues();
    }

    /*
      If named parameters were used, it is no longer possible to simply replace the placeholders in the
      original statement with the values of the bind variables.  The only way it could be done is if the names
      could be resolved by to the ordinal positions which is not possible on all databases.

      New log format:  <original statement> name:value, name:value

      Example: {? = call test_proc(?,?)} param1:value1, param2:value2, param3:value3

      In the event that ordinal and named parameters are both used, the original position will be used as the name.
      Example:  {? = call test_proc(?,?)} 1:value1, 3:value3, param2:value2
    */

    final StringBuilder result = new StringBuilder();
    final String statementQuery = getStatementQuery();

    // first append the original statement
    result.append(statementQuery);
    result.append(" ");

    StringBuilder parameters = new StringBuilder();

    // add parameters set with ordinal positions
    for( Map.Entry<Integer, Value> entry : getParameterValues().entrySet() ) {
      appendParameter(parameters, entry.getKey().toString(), entry.getValue());
    }

    // add named parameters
    for( Map.Entry<String, Value> entry : namedParameterValues.entrySet() ) {
      appendParameter(parameters, entry.getKey(), entry.getValue());
    }

    result.append(parameters);

    return result.toString();
  }

  private void appendParameter(StringBuilder parameters, String name, Value value) {
    if( parameters.length() > 0 ) {
      parameters.append(", ");
    }

    parameters.append(name);
    parameters.append(":");
    parameters.append(value != null ? value.toString() : new Value().toString());
  }

  /**
   * Records the value of a parameter.
   *
   * @param name the name of the parameter
   * @param value the value of the parameter
   */
  public void setParameterValue(final String name, final Object value) {
    namedParameterValues.put(name, new Value(value));
  }
}