The following issues were found

guava-tests/test/com/google/common/reflect/TypeParameterTest.java
13 issues
JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 32

               */
public class TypeParameterTest extends TestCase {

  public <T> void testCaptureTypeParameter() throws Exception {
    TypeVariable<?> variable = new TypeParameter<T>() {}.typeVariable;
    TypeVariable<?> expected =
        TypeParameterTest.class.getDeclaredMethod("testCaptureTypeParameter")
            .getTypeParameters()[0];
    assertEquals(expected, variable);

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 35

                public <T> void testCaptureTypeParameter() throws Exception {
    TypeVariable<?> variable = new TypeParameter<T>() {}.typeVariable;
    TypeVariable<?> expected =
        TypeParameterTest.class.getDeclaredMethod("testCaptureTypeParameter")
            .getTypeParameters()[0];
    assertEquals(expected, variable);
  }

  public void testConcreteTypeRejected() {

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 35

                public <T> void testCaptureTypeParameter() throws Exception {
    TypeVariable<?> variable = new TypeParameter<T>() {}.typeVariable;
    TypeVariable<?> expected =
        TypeParameterTest.class.getDeclaredMethod("testCaptureTypeParameter")
            .getTypeParameters()[0];
    assertEquals(expected, variable);
  }

  public void testConcreteTypeRejected() {

            

Reported by PMD.

JUnit assertions should include a message
Design

Line: 37

                  TypeVariable<?> expected =
        TypeParameterTest.class.getDeclaredMethod("testCaptureTypeParameter")
            .getTypeParameters()[0];
    assertEquals(expected, variable);
  }

  public void testConcreteTypeRejected() {
    try {
      new TypeParameter<String>() {};

            

Reported by PMD.

JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 40

                  assertEquals(expected, variable);
  }

  public void testConcreteTypeRejected() {
    try {
      new TypeParameter<String>() {};
      fail();
    } catch (IllegalArgumentException expected) {
    }

            

Reported by PMD.

JUnit assertions should include a message
Design

Line: 43

                public void testConcreteTypeRejected() {
    try {
      new TypeParameter<String>() {};
      fail();
    } catch (IllegalArgumentException expected) {
    }
  }

  public <A, B> void testEquals() throws Exception {

            

Reported by PMD.

In JUnit4, use the @Test(expected) annotation to denote tests that should throw exceptions
Design

Line: 43

                public void testConcreteTypeRejected() {
    try {
      new TypeParameter<String>() {};
      fail();
    } catch (IllegalArgumentException expected) {
    }
  }

  public <A, B> void testEquals() throws Exception {

            

Reported by PMD.

JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 48

                  }
  }

  public <A, B> void testEquals() throws Exception {
    Method method = TypeParameterTest.class.getDeclaredMethod("testEquals");
    new EqualsTester()
        .addEqualityGroup(new TypeParameter<A>() {}, new TypeParameter<A>() {})
        .addEqualityGroup(new TypeParameter<B>() {})
        .testEquals();

            

Reported by PMD.

JUnit tests should include assert() or fail()
Design

Line: 48

                  }
  }

  public <A, B> void testEquals() throws Exception {
    Method method = TypeParameterTest.class.getDeclaredMethod("testEquals");
    new EqualsTester()
        .addEqualityGroup(new TypeParameter<A>() {}, new TypeParameter<A>() {})
        .addEqualityGroup(new TypeParameter<B>() {})
        .testEquals();

            

Reported by PMD.

Avoid unused local variables such as 'method'.
Design

Line: 49

                }

  public <A, B> void testEquals() throws Exception {
    Method method = TypeParameterTest.class.getDeclaredMethod("testEquals");
    new EqualsTester()
        .addEqualityGroup(new TypeParameter<A>() {}, new TypeParameter<A>() {})
        .addEqualityGroup(new TypeParameter<B>() {})
        .testEquals();
  }

            

Reported by PMD.

guava/src/com/google/common/collect/TopKSelector.java
13 issues
This class has too many methods, consider refactoring it.
Design

Line: 59

              @GwtCompatible
@ElementTypesAreNonnullByDefault
final class TopKSelector<
    T extends @Nullable Object> {

  /**
   * Returns a {@code TopKSelector} that collects the lowest {@code k} elements added to it,
   * relative to the natural ordering of the elements, and returns them via {@link #topK} in
   * ascending order.

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 102

                 */
  public static <T extends @Nullable Object> TopKSelector<T> greatest(
      int k, Comparator<? super T> comparator) {
    return new TopKSelector<T>(Ordering.from(comparator).reverse(), k);
  }

  private final int k;
  private final Comparator<? super T> comparator;


            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 105

                  return new TopKSelector<T>(Ordering.from(comparator).reverse(), k);
  }

  private final int k;
  private final Comparator<? super T> comparator;

  /*
   * We are currently considering the elements in buffer in the range [0, bufferSize) as candidates
   * for the top k elements. Whenever the buffer is filled, we quickselect the top k elements to the

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 106

                }

  private final int k;
  private final Comparator<? super T> comparator;

  /*
   * We are currently considering the elements in buffer in the range [0, bufferSize) as candidates
   * for the top k elements. Whenever the buffer is filled, we quickselect the top k elements to the
   * range [0, k) and ignore the remaining elements.

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 113

                 * for the top k elements. Whenever the buffer is filled, we quickselect the top k elements to the
   * range [0, k) and ignore the remaining elements.
   */
  private final @Nullable T[] buffer;
  private int bufferSize;

  /**
   * The largest of the lowest k elements we've seen so far relative to this comparator. If
   * bufferSize ≥ k, then we can ignore any elements greater than this value.

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 114

                 * range [0, k) and ignore the remaining elements.
   */
  private final @Nullable T[] buffer;
  private int bufferSize;

  /**
   * The largest of the lowest k elements we've seen so far relative to this comparator. If
   * bufferSize ≥ k, then we can ignore any elements greater than this value.
   */

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 120

                 * The largest of the lowest k elements we've seen so far relative to this comparator. If
   * bufferSize ≥ k, then we can ignore any elements greater than this value.
   */
  @CheckForNull private T threshold;

  private TopKSelector(Comparator<? super T> comparator, int k) {
    this.comparator = checkNotNull(comparator, "comparator");
    this.k = k;
    checkArgument(k >= 0, "k (%s) must be >= 0", k);

            

Reported by PMD.

Assigning an Object to null is a code smell. Consider refactoring.
Error

Line: 129

                  checkArgument(k <= Integer.MAX_VALUE / 2, "k (%s) must be <= Integer.MAX_VALUE / 2", k);
    this.buffer = (T[]) new Object[IntMath.checkedMultiply(k, 2)];
    this.bufferSize = 0;
    this.threshold = null;
  }

  /**
   * Adds {@code elem} as a candidate for the top {@code k} elements. This operation takes amortized
   * O(1) time.

            

Reported by PMD.

Found 'DD'-anomaly for variable 'minThresholdPosition' (lines '167'-'182').
Error

Line: 167

                  int left = 0;
    int right = 2 * k - 1;

    int minThresholdPosition = 0;
    // The leftmost position at which the greatest of the k lower elements
    // -- the new value of threshold -- might be found.

    int iterations = 0;
    int maxIterations = IntMath.log2(right - left, RoundingMode.CEILING) * 3;

            

Reported by PMD.

Found 'DD'-anomaly for variable 'iterations' (lines '171'-'186').
Error

Line: 171

                  // The leftmost position at which the greatest of the k lower elements
    // -- the new value of threshold -- might be found.

    int iterations = 0;
    int maxIterations = IntMath.log2(right - left, RoundingMode.CEILING) * 3;
    while (left < right) {
      int pivotIndex = (left + right + 1) >>> 1;

      int pivotNewIndex = partition(left, right, pivotIndex);

            

Reported by PMD.

guava/src/com/google/common/collect/FilteredKeyMultimap.java
13 issues
This class has too many methods, consider refactoring it.
Design

Line: 44

              @GwtCompatible
@ElementTypesAreNonnullByDefault
class FilteredKeyMultimap<K extends @Nullable Object, V extends @Nullable Object>
    extends AbstractMultimap<K, V> implements FilteredMultimap<K, V> {
  final Multimap<K, V> unfiltered;
  final Predicate<? super K> keyPredicate;

  FilteredKeyMultimap(Multimap<K, V> unfiltered, Predicate<? super K> keyPredicate) {
    this.unfiltered = checkNotNull(unfiltered);

            

Reported by PMD.

Field unfiltered has the same name as a method
Error

Line: 45

              @ElementTypesAreNonnullByDefault
class FilteredKeyMultimap<K extends @Nullable Object, V extends @Nullable Object>
    extends AbstractMultimap<K, V> implements FilteredMultimap<K, V> {
  final Multimap<K, V> unfiltered;
  final Predicate<? super K> keyPredicate;

  FilteredKeyMultimap(Multimap<K, V> unfiltered, Predicate<? super K> keyPredicate) {
    this.unfiltered = checkNotNull(unfiltered);
    this.keyPredicate = checkNotNull(keyPredicate);

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 45

              @ElementTypesAreNonnullByDefault
class FilteredKeyMultimap<K extends @Nullable Object, V extends @Nullable Object>
    extends AbstractMultimap<K, V> implements FilteredMultimap<K, V> {
  final Multimap<K, V> unfiltered;
  final Predicate<? super K> keyPredicate;

  FilteredKeyMultimap(Multimap<K, V> unfiltered, Predicate<? super K> keyPredicate) {
    this.unfiltered = checkNotNull(unfiltered);
    this.keyPredicate = checkNotNull(keyPredicate);

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 46

              class FilteredKeyMultimap<K extends @Nullable Object, V extends @Nullable Object>
    extends AbstractMultimap<K, V> implements FilteredMultimap<K, V> {
  final Multimap<K, V> unfiltered;
  final Predicate<? super K> keyPredicate;

  FilteredKeyMultimap(Multimap<K, V> unfiltered, Predicate<? super K> keyPredicate) {
    this.unfiltered = checkNotNull(unfiltered);
    this.keyPredicate = checkNotNull(keyPredicate);
  }

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 66

                @Override
  public int size() {
    int size = 0;
    for (Collection<V> collection : asMap().values()) {
      size += collection.size();
    }
    return size;
  }


            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 97

              
  @Override
  public void clear() {
    keySet().clear();
  }

  @Override
  Set<K> createKeySet() {
    return Sets.filter(unfiltered.keySet(), keyPredicate);

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 118

              
  static class AddRejectingSet<K extends @Nullable Object, V extends @Nullable Object>
      extends ForwardingSet<V> {
    @ParametricNullness final K key;

    AddRejectingSet(@ParametricNullness K key) {
      this.key = key;
    }


            

Reported by PMD.

The String literal 'Key does not satisfy predicate: ' appears 4 times in this file; the first occurrence is on line 126
Error

Line: 126

              
    @Override
    public boolean add(@ParametricNullness V element) {
      throw new IllegalArgumentException("Key does not satisfy predicate: " + key);
    }

    @Override
    public boolean addAll(Collection<? extends V> collection) {
      checkNotNull(collection);

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 143

              
  static class AddRejectingList<K extends @Nullable Object, V extends @Nullable Object>
      extends ForwardingList<V> {
    @ParametricNullness final K key;

    AddRejectingList(@ParametricNullness K key) {
      this.key = key;
    }


            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 203

                  public boolean remove(@CheckForNull Object o) {
      if (o instanceof Entry) {
        Entry<?, ?> entry = (Entry<?, ?>) o;
        if (unfiltered.containsKey(entry.getKey())
            // if this holds, then we know entry.getKey() is a K
            && keyPredicate.apply((K) entry.getKey())) {
          return unfiltered.remove(entry.getKey(), entry.getValue());
        }
      }

            

Reported by PMD.

guava/src/com/google/common/collect/CollectCollectors.java
13 issues
All methods are static. Consider using a utility class instead. Alternatively, you could add a private constructor or make the class abstract to silence this warning.
Design

Line: 43

              /** Collectors utilities for {@code common.collect} internals. */
@GwtCompatible
@ElementTypesAreNonnullByDefault
final class CollectCollectors {

  private static final Collector<Object, ?, ImmutableList<Object>> TO_IMMUTABLE_LIST =
      Collector.of(
          ImmutableList::builder,
          ImmutableList.Builder::add,

            

Reported by PMD.

This class has too many methods, consider refactoring it.
Design

Line: 43

              /** Collectors utilities for {@code common.collect} internals. */
@GwtCompatible
@ElementTypesAreNonnullByDefault
final class CollectCollectors {

  private static final Collector<Object, ?, ImmutableList<Object>> TO_IMMUTABLE_LIST =
      Collector.of(
          ImmutableList::builder,
          ImmutableList.Builder::add,

            

Reported by PMD.

The String literal 'rawtypes' appears 5 times in this file; the first occurrence is on line 70
Error

Line: 70

              
  // Lists

  @SuppressWarnings({"rawtypes", "unchecked"})
  static <E> Collector<E, ?, ImmutableList<E>> toImmutableList() {
    return (Collector) TO_IMMUTABLE_LIST;
  }

  // Sets

            

Reported by PMD.

The String literal 'unchecked' appears 5 times in this file; the first occurrence is on line 70
Error

Line: 70

              
  // Lists

  @SuppressWarnings({"rawtypes", "unchecked"})
  static <E> Collector<E, ?, ImmutableList<E>> toImmutableList() {
    return (Collector) TO_IMMUTABLE_LIST;
  }

  // Sets

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 108

                              EnumSetAccumulator::toImmutableSet,
                Collector.Characteristics.UNORDERED);

    @CheckForNull private EnumSet<E> set;

    void add(E e) {
      if (set == null) {
        set = EnumSet.of(e);
      } else {

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 306

                }

  private static class EnumMapAccumulator<K extends Enum<K>, V> {
    private final BinaryOperator<V> mergeFunction;
    @CheckForNull private EnumMap<K, V> map = null;

    EnumMapAccumulator(BinaryOperator<V> mergeFunction) {
      this.mergeFunction = mergeFunction;
    }

            

Reported by PMD.

Avoid using redundant field initializer for 'map'
Performance

Line: 307

              
  private static class EnumMapAccumulator<K extends Enum<K>, V> {
    private final BinaryOperator<V> mergeFunction;
    @CheckForNull private EnumMap<K, V> map = null;

    EnumMapAccumulator(BinaryOperator<V> mergeFunction) {
      this.mergeFunction = mergeFunction;
    }


            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 307

              
  private static class EnumMapAccumulator<K extends Enum<K>, V> {
    private final BinaryOperator<V> mergeFunction;
    @CheckForNull private EnumMap<K, V> map = null;

    EnumMapAccumulator(BinaryOperator<V> mergeFunction) {
      this.mergeFunction = mergeFunction;
    }


            

Reported by PMD.

Potential violation of Law of Demeter (static property access)
Design

Line: 326

                    } else if (other.map == null) {
        return this;
      } else {
        other.map.forEach(this::put);
        return this;
      }
    }

    ImmutableMap<K, V> toImmutableMap() {

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 375

                      flatteningToMultimap(
            input -> checkNotNull(keyFunction.apply(input)),
            input -> valuesFunction.apply(input).peek(Preconditions::checkNotNull),
            MultimapBuilder.linkedHashKeys().arrayListValues()::<K, V>build),
        ImmutableListMultimap::copyOf);
  }

  static <T extends @Nullable Object, K, V>
      Collector<T, ?, ImmutableSetMultimap<K, V>> toImmutableSetMultimap(

            

Reported by PMD.

guava/src/com/google/common/collect/ForwardingList.java
13 issues
This class has too many methods, consider refactoring it.
Design

Line: 57

              @GwtCompatible
@ElementTypesAreNonnullByDefault
public abstract class ForwardingList<E extends @Nullable Object> extends ForwardingCollection<E>
    implements List<E> {
  // TODO(lowasser): identify places where thread safety is actually lost

  /** Constructor for use by subclasses. */
  protected ForwardingList() {}


            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 68

              
  @Override
  public void add(int index, @ParametricNullness E element) {
    delegate().add(index, element);
  }

  @CanIgnoreReturnValue
  @Override
  public boolean addAll(int index, Collection<? extends E> elements) {

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 74

                @CanIgnoreReturnValue
  @Override
  public boolean addAll(int index, Collection<? extends E> elements) {
    return delegate().addAll(index, elements);
  }

  @Override
  @ParametricNullness
  public E get(int index) {

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 80

                @Override
  @ParametricNullness
  public E get(int index) {
    return delegate().get(index);
  }

  @Override
  public int indexOf(@CheckForNull Object element) {
    return delegate().indexOf(element);

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 85

              
  @Override
  public int indexOf(@CheckForNull Object element) {
    return delegate().indexOf(element);
  }

  @Override
  public int lastIndexOf(@CheckForNull Object element) {
    return delegate().lastIndexOf(element);

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 90

              
  @Override
  public int lastIndexOf(@CheckForNull Object element) {
    return delegate().lastIndexOf(element);
  }

  @Override
  public ListIterator<E> listIterator() {
    return delegate().listIterator();

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 95

              
  @Override
  public ListIterator<E> listIterator() {
    return delegate().listIterator();
  }

  @Override
  public ListIterator<E> listIterator(int index) {
    return delegate().listIterator(index);

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 100

              
  @Override
  public ListIterator<E> listIterator(int index) {
    return delegate().listIterator(index);
  }

  @CanIgnoreReturnValue
  @Override
  @ParametricNullness

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 107

                @Override
  @ParametricNullness
  public E remove(int index) {
    return delegate().remove(index);
  }

  @CanIgnoreReturnValue
  @Override
  @ParametricNullness

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 114

                @Override
  @ParametricNullness
  public E set(int index, @ParametricNullness E element) {
    return delegate().set(index, element);
  }

  @Override
  public List<E> subList(int fromIndex, int toIndex) {
    return delegate().subList(fromIndex, toIndex);

            

Reported by PMD.

guava-tests/test/com/google/common/hash/AbstractNonStreamingHashFunctionTest.java
13 issues
JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 34

                 * Constructs two trivial HashFunctions (output := input), one streaming and one non-streaming,
   * and checks that their results are identical, no matter which newHasher version we used.
   */
  public void testExhaustive() {
    List<Hasher> hashers =
        ImmutableList.of(
            new StreamingVersion().newHasher(),
            new StreamingVersion().newHasher(52),
            new NonStreamingVersion().newHasher(),

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 43

                          new NonStreamingVersion().newHasher(123));
    Random random = new Random(0);
    for (int i = 0; i < 200; i++) {
      RandomHasherAction.pickAtRandom(random).performAction(random, hashers);
    }
    HashCode[] codes = new HashCode[hashers.size()];
    for (int i = 0; i < hashers.size(); i++) {
      codes[i] = hashers.get(i).hash();
    }

            

Reported by PMD.

Potential violation of Law of Demeter (method chain calls)
Design

Line: 47

                  }
    HashCode[] codes = new HashCode[hashers.size()];
    for (int i = 0; i < hashers.size(); i++) {
      codes[i] = hashers.get(i).hash();
    }
    for (int i = 1; i < codes.length; i++) {
      assertEquals(codes[i - 1], codes[i]);
    }
  }

            

Reported by PMD.

JUnit assertions should include a message
Design

Line: 50

                    codes[i] = hashers.get(i).hash();
    }
    for (int i = 1; i < codes.length; i++) {
      assertEquals(codes[i - 1], codes[i]);
    }
  }

  public void testPutStringWithLowSurrogate() {
    // we pad because the dummy hash function we use to test this, merely copies the input into

            

Reported by PMD.

JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 54

                  }
  }

  public void testPutStringWithLowSurrogate() {
    // we pad because the dummy hash function we use to test this, merely copies the input into
    // the output, so the input must be at least 32 bits, since the output has to be that long
    assertPutString(new char[] {'p', HashTestUtils.randomLowSurrogate(new Random())});
  }


            

Reported by PMD.

JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 60

                  assertPutString(new char[] {'p', HashTestUtils.randomLowSurrogate(new Random())});
  }

  public void testPutStringWithHighSurrogate() {
    // we pad because the dummy hash function we use to test this, merely copies the input into
    // the output, so the input must be at least 32 bits, since the output has to be that long
    assertPutString(new char[] {'p', HashTestUtils.randomHighSurrogate(new Random())});
  }


            

Reported by PMD.

JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 66

                  assertPutString(new char[] {'p', HashTestUtils.randomHighSurrogate(new Random())});
  }

  public void testPutStringWithLowHighSurrogate() {
    assertPutString(
        new char[] {
          HashTestUtils.randomLowSurrogate(new Random()),
          HashTestUtils.randomHighSurrogate(new Random())
        });

            

Reported by PMD.

JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 74

                      });
  }

  public void testPutStringWithHighLowSurrogate() {
    assertPutString(
        new char[] {
          HashTestUtils.randomHighSurrogate(new Random()),
          HashTestUtils.randomLowSurrogate(new Random())
        });

            

Reported by PMD.

JUnit assertions should include a message
Design

Line: 91

                    h1.putChar(s.charAt(i));
    }
    h2.putUnencodedChars(s);
    assertEquals(h1.hash(), h2.hash());
  }

  static class StreamingVersion extends AbstractHashFunction {
    @Override
    public int bits() {

            

Reported by PMD.

Consider using varargs for methods or constructors which take an array the last parameter.
Design

Line: 82

                      });
  }

  private static void assertPutString(char[] chars) {
    Hasher h1 = new NonStreamingVersion().newHasher();
    Hasher h2 = new NonStreamingVersion().newHasher();
    String s = new String(chars);
    // this is the correct implementation of the spec
    for (int i = 0; i < s.length(); i++) {

            

Reported by PMD.

guava-tests/test/com/google/common/io/LineBufferTest.java
13 issues
JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 38

              @AndroidIncompatible // occasionally very slow
public class LineBufferTest extends IoTestCase {

  public void testProcess() throws IOException {
    bufferHelper("");
    bufferHelper("\n", "\n");
    bufferHelper("\r\n", "\r\n");
    bufferHelper("\n\r", "\n", "\r");
    bufferHelper("\r", "\r");

            

Reported by PMD.

The String literal '\r\n' appears 4 times in this file; the first occurrence is on line 41
Error

Line: 41

                public void testProcess() throws IOException {
    bufferHelper("");
    bufferHelper("\n", "\n");
    bufferHelper("\r\n", "\r\n");
    bufferHelper("\n\r", "\n", "\r");
    bufferHelper("\r", "\r");
    bufferHelper("\n\n", "\n", "\n");
    bufferHelper("\r\n\r\n", "\r\n", "\r\n");
    bufferHelper("\r\r", "\r", "\r");

            

Reported by PMD.

Avoid reassigning the loop control variable 'chunk'
Design

Line: 72

                          });

    for (int chunk : CHUNK_SIZES) {
      chunk = Math.max(1, Math.min(chunk, input.length()));
      assertEquals(expectProcess, bufferHelper(input, chunk));
      assertEquals(expectRead, readUsingJava(input, chunk));
      assertEquals(expectRead, readUsingReader(input, chunk, true));
      assertEquals(expectRead, readUsingReader(input, chunk, false));
    }

            

Reported by PMD.

Ensure that resources like this BufferedReader object are closed after use
Error

Line: 101

                }

  private static List<String> readUsingJava(String input, int chunk) throws IOException {
    BufferedReader r = new BufferedReader(getChunkedReader(input, chunk));
    List<String> lines = Lists.newArrayList();
    String line;
    while ((line = r.readLine()) != null) {
      lines.add(line);
    }

            

Reported by PMD.

Avoid assignments in operands
Error

Line: 104

                  BufferedReader r = new BufferedReader(getChunkedReader(input, chunk));
    List<String> lines = Lists.newArrayList();
    String line;
    while ((line = r.readLine()) != null) {
      lines.add(line);
    }
    r.close();
    return lines;
  }

            

Reported by PMD.

Avoid assignments in operands
Error

Line: 118

                  LineReader r = new LineReader(readable);
    List<String> lines = Lists.newArrayList();
    String line;
    while ((line = r.readLine()) != null) {
      lines.add(line);
    }
    return lines;
  }


            

Reported by PMD.

Ensure that resources like this Reader object are closed after use
Error

Line: 126

              
  // Returns a Readable that is *not* a Reader.
  private static Readable getChunkedReadable(String input, int chunk) {
    final Reader reader = getChunkedReader(input, chunk);
    return new Readable() {
      @Override
      public int read(CharBuffer cbuf) throws IOException {
        return reader.read(cbuf);
      }

            

Reported by PMD.

Found 'DU'-anomaly for variable 'expectRead' (lines '61'-'78').
Error

Line: 61

                private static void bufferHelper(String input, String... expect) throws IOException {

    List<String> expectProcess = Arrays.asList(expect);
    List<String> expectRead =
        Lists.transform(
            expectProcess,
            new Function<String, String>() {
              @Override
              public String apply(String value) {

            

Reported by PMD.

Found 'DU'-anomaly for variable 'expectRead' (lines '61'-'78').
Error

Line: 61

                private static void bufferHelper(String input, String... expect) throws IOException {

    List<String> expectProcess = Arrays.asList(expect);
    List<String> expectRead =
        Lists.transform(
            expectProcess,
            new Function<String, String>() {
              @Override
              public String apply(String value) {

            

Reported by PMD.

Found 'DU'-anomaly for variable 'line' (lines '104'-'109').
Error

Line: 104

                  BufferedReader r = new BufferedReader(getChunkedReader(input, chunk));
    List<String> lines = Lists.newArrayList();
    String line;
    while ((line = r.readLine()) != null) {
      lines.add(line);
    }
    r.close();
    return lines;
  }

            

Reported by PMD.

guava-tests/benchmark/com/google/common/util/concurrent/MoreExecutorsDirectExecutorBenchmark.java
13 issues
Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 56

                  abstract Executor executor();
  }

  @Param Impl impl;
  Executor executor;

  static final class CountingRunnable implements Runnable {
    AtomicInteger integer = new AtomicInteger();


            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 57

                }

  @Param Impl impl;
  Executor executor;

  static final class CountingRunnable implements Runnable {
    AtomicInteger integer = new AtomicInteger();

    @Override

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 60

                Executor executor;

  static final class CountingRunnable implements Runnable {
    AtomicInteger integer = new AtomicInteger();

    @Override
    public void run() {
      integer.incrementAndGet();
    }

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 68

                  }
  }

  CountingRunnable countingRunnable = new CountingRunnable();

  Set<Thread> threads = new HashSet<>();

  @BeforeExperiment
  void before() {

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 70

              
  CountingRunnable countingRunnable = new CountingRunnable();

  Set<Thread> threads = new HashSet<>();

  @BeforeExperiment
  void before() {
    executor = impl.executor();
    for (int i = 0; i < 4; i++) {

            

Reported by PMD.

Avoid instantiating new objects inside loops
Performance

Line: 77

                  executor = impl.executor();
    for (int i = 0; i < 4; i++) {
      Thread thread =
          new Thread() {
            @Override
            public void run() {
              CountingRunnable localRunnable = new CountingRunnable();
              while (!isInterrupted()) {
                executor.execute(localRunnable);

            

Reported by PMD.

Avoid instantiating new objects inside loops
Performance

Line: 80

                        new Thread() {
            @Override
            public void run() {
              CountingRunnable localRunnable = new CountingRunnable();
              while (!isInterrupted()) {
                executor.execute(localRunnable);
              }
              countingRunnable.integer.addAndGet(localRunnable.integer.get());
            }

            

Reported by PMD.

Potential violation of Law of Demeter (static property access)
Design

Line: 84

                            while (!isInterrupted()) {
                executor.execute(localRunnable);
              }
              countingRunnable.integer.addAndGet(localRunnable.integer.get());
            }
          };
      threads.add(thread);
    }
  }

            

Reported by PMD.

Potential violation of Law of Demeter (static property access)
Design

Line: 84

                            while (!isInterrupted()) {
                executor.execute(localRunnable);
              }
              countingRunnable.integer.addAndGet(localRunnable.integer.get());
            }
          };
      threads.add(thread);
    }
  }

            

Reported by PMD.

Potential violation of Law of Demeter (static property access)
Design

Line: 111

                  for (int i = 0; i < reps; i++) {
      executor.execute(countingRunnable);
    }
    return countingRunnable.integer.get();
  }

  @Benchmark
  int timeContendedExecute(int reps) {
    final Executor executor = this.executor;

            

Reported by PMD.

guava-tests/test/com/google/common/io/AppendableWriterTest.java
13 issues
Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 33

              
  /** Helper class for testing behavior with Flushable and Closeable targets. */
  private static class SpyAppendable implements Appendable, Flushable, Closeable {
    boolean flushed;
    boolean closed;
    StringBuilder result = new StringBuilder();

    @Override
    public Appendable append(CharSequence csq) {

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 34

                /** Helper class for testing behavior with Flushable and Closeable targets. */
  private static class SpyAppendable implements Appendable, Flushable, Closeable {
    boolean flushed;
    boolean closed;
    StringBuilder result = new StringBuilder();

    @Override
    public Appendable append(CharSequence csq) {
      result.append(csq);

            

Reported by PMD.

StringBuffers can grow quite a lot, and so may become a source of memory leak (if the owning class has a long life time).
Design

Line: 35

                private static class SpyAppendable implements Appendable, Flushable, Closeable {
    boolean flushed;
    boolean closed;
    StringBuilder result = new StringBuilder();

    @Override
    public Appendable append(CharSequence csq) {
      result.append(csq);
      return this;

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 35

                private static class SpyAppendable implements Appendable, Flushable, Closeable {
    boolean flushed;
    boolean closed;
    StringBuilder result = new StringBuilder();

    @Override
    public Appendable append(CharSequence csq) {
      result.append(csq);
      return this;

            

Reported by PMD.

JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 66

                  }
  }

  public void testWriteMethods() throws IOException {
    StringBuilder builder = new StringBuilder();
    Writer writer = new AppendableWriter(builder);

    writer.write("Hello".toCharArray());
    writer.write(',');

            

Reported by PMD.

Ensure that resources like this AppendableWriter object are closed after use
Error

Line: 68

              
  public void testWriteMethods() throws IOException {
    StringBuilder builder = new StringBuilder();
    Writer writer = new AppendableWriter(builder);

    writer.write("Hello".toCharArray());
    writer.write(',');
    writer.write(0xBEEF0020); // only lower 16 bits are important
    writer.write("Wo");

            

Reported by PMD.

JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 80

                  assertEquals("Hello, World!", builder.toString());
  }

  public void testAppendMethods() throws IOException {
    StringBuilder builder = new StringBuilder();
    Writer writer = new AppendableWriter(builder);

    writer.append("Hello,");
    writer.append(' ');

            

Reported by PMD.

Ensure that resources like this AppendableWriter object are closed after use
Error

Line: 82

              
  public void testAppendMethods() throws IOException {
    StringBuilder builder = new StringBuilder();
    Writer writer = new AppendableWriter(builder);

    writer.append("Hello,");
    writer.append(' ');
    writer.append("The World Wide Web", 4, 9);
    writer.append("!");

            

Reported by PMD.

JUnit 4 tests that execute tests should use the @Test annotation, JUnit 5 tests should use @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest
Design

Line: 92

                  assertEquals("Hello, World!", builder.toString());
  }

  public void testCloseFlush() throws IOException {
    SpyAppendable spy = new SpyAppendable();
    Writer writer = new AppendableWriter(spy);

    writer.write("Hello");
    assertFalse(spy.flushed);

            

Reported by PMD.

Unit tests should not contain more than 1 assert(s).
Design

Line: 92

                  assertEquals("Hello, World!", builder.toString());
  }

  public void testCloseFlush() throws IOException {
    SpyAppendable spy = new SpyAppendable();
    Writer writer = new AppendableWriter(spy);

    writer.write("Hello");
    assertFalse(spy.flushed);

            

Reported by PMD.

guava-tests/benchmark/com/google/common/primitives/UnsignedBytesBenchmark.java
13 issues
Avoid throwing raw exception types.
Design

Line: 65

                void longEqualJava(int reps) {
    for (int i = 0; i < reps; ++i) {
      if (javaImpl.compare(ba1, ba2) != 0) {
        throw new Error(); // deoptimization
      }
    }
  }

  @Benchmark

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 74

                void longEqualUnsafe(int reps) {
    for (int i = 0; i < reps; ++i) {
      if (unsafeImpl.compare(ba1, ba2) != 0) {
        throw new Error(); // deoptimization
      }
    }
  }

  @Benchmark

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 83

                void diffLastJava(int reps) {
    for (int i = 0; i < reps; ++i) {
      if (javaImpl.compare(ba3, ba4) == 0) {
        throw new Error(); // deoptimization
      }
    }
  }

  @Benchmark

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 92

                void diffLastUnsafe(int reps) {
    for (int i = 0; i < reps; ++i) {
      if (unsafeImpl.compare(ba3, ba4) == 0) {
        throw new Error(); // deoptimization
      }
    }
  }

  /*

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 33

               */
public class UnsignedBytesBenchmark {

  private byte[] ba1;
  private byte[] ba2;
  private byte[] ba3;
  private byte[] ba4;
  private Comparator<byte[]> javaImpl;
  private Comparator<byte[]> unsafeImpl;

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 34

              public class UnsignedBytesBenchmark {

  private byte[] ba1;
  private byte[] ba2;
  private byte[] ba3;
  private byte[] ba4;
  private Comparator<byte[]> javaImpl;
  private Comparator<byte[]> unsafeImpl;


            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 35

              
  private byte[] ba1;
  private byte[] ba2;
  private byte[] ba3;
  private byte[] ba4;
  private Comparator<byte[]> javaImpl;
  private Comparator<byte[]> unsafeImpl;

  // 4, 8, 64, 1K, 1M, 1M (unaligned), 64M, 64M (unaligned)

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 36

                private byte[] ba1;
  private byte[] ba2;
  private byte[] ba3;
  private byte[] ba4;
  private Comparator<byte[]> javaImpl;
  private Comparator<byte[]> unsafeImpl;

  // 4, 8, 64, 1K, 1M, 1M (unaligned), 64M, 64M (unaligned)
  // @Param({"4", "8", "64", "1024", "1048576", "1048577", "6710884", "6710883"})

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 37

                private byte[] ba2;
  private byte[] ba3;
  private byte[] ba4;
  private Comparator<byte[]> javaImpl;
  private Comparator<byte[]> unsafeImpl;

  // 4, 8, 64, 1K, 1M, 1M (unaligned), 64M, 64M (unaligned)
  // @Param({"4", "8", "64", "1024", "1048576", "1048577", "6710884", "6710883"})
  @Param({"4", "8", "64", "1024"})

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 38

                private byte[] ba3;
  private byte[] ba4;
  private Comparator<byte[]> javaImpl;
  private Comparator<byte[]> unsafeImpl;

  // 4, 8, 64, 1K, 1M, 1M (unaligned), 64M, 64M (unaligned)
  // @Param({"4", "8", "64", "1024", "1048576", "1048577", "6710884", "6710883"})
  @Param({"4", "8", "64", "1024"})
  private int length;

            

Reported by PMD.