The following issues were found

java/util/src/test/java/com/google/protobuf/util/FieldMaskUtilTest.java
104 issues
This class has too many methods, consider refactoring it.
Design

Line: 46

              
/** Unit tests for {@link FieldMaskUtil}. */
@RunWith(JUnit4.class)
public class FieldMaskUtilTest {
  @Test
  public void testIsValid() throws Exception {
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "nonexist")).isFalse();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_int32")).isTrue();

            

Reported by PMD.

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

Line: 48

              @RunWith(JUnit4.class)
public class FieldMaskUtilTest {
  @Test
  public void testIsValid() throws Exception {
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "nonexist")).isFalse();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_nested_message"))

            

Reported by PMD.

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

Line: 49

              public class FieldMaskUtilTest {
  @Test
  public void testIsValid() throws Exception {
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "nonexist")).isFalse();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_nested_message"))
        .isTrue();

            

Reported by PMD.

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

Line: 49

              public class FieldMaskUtilTest {
  @Test
  public void testIsValid() throws Exception {
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "nonexist")).isFalse();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_nested_message"))
        .isTrue();

            

Reported by PMD.

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

Line: 50

                @Test
  public void testIsValid() throws Exception {
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "nonexist")).isFalse();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_nested_message"))
        .isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_nested_message"))

            

Reported by PMD.

The String literal 'nonexist' appears 4 times in this file; the first occurrence is on line 50
Error

Line: 50

                @Test
  public void testIsValid() throws Exception {
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "nonexist")).isFalse();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_nested_message"))
        .isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_nested_message"))

            

Reported by PMD.

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

Line: 51

                public void testIsValid() throws Exception {
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "nonexist")).isFalse();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_nested_message"))
        .isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_nested_message"))
        .isTrue();

            

Reported by PMD.

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

Line: 52

                  assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "nonexist")).isFalse();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_nested_message"))
        .isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_nested_message"))
        .isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.nonexist")).isFalse();

            

Reported by PMD.

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

Line: 53

                  assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "nonexist")).isFalse();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_nested_message"))
        .isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_nested_message"))
        .isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.nonexist")).isFalse();


            

Reported by PMD.

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

Line: 55

                  assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_int32")).isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.optional_nested_message"))
        .isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.repeated_nested_message"))
        .isTrue();
    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, "payload.nonexist")).isFalse();

    assertThat(FieldMaskUtil.isValid(NestedTestAllTypes.class, FieldMaskUtil.fromString("payload")))
        .isTrue();

            

Reported by PMD.

python/google/protobuf/service_reflection.py
104 issues
No value for argument 'dictionary' in method call
Error

Line: 106 Column: 5

                      dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
        describing this protocol service type.
    """
    super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary)
    # Don't do anything if this class doesn't have a descriptor. This happens
    # when a service stub is subclassed.
    if GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary:
      return


            

Reported by Pylint.

Unused argument 'bases'
Error

Line: 64 Column: 27

              
  _DESCRIPTOR_KEY = 'DESCRIPTOR'

  def __init__(cls, name, bases, dictionary):
    """Creates a message service class.

    Args:
      name: Name of the class (ignored, but required by the metaclass
        protocol).

            

Reported by Pylint.

__init__ method from base class 'type' is not called
Error

Line: 64 Column: 3

              
  _DESCRIPTOR_KEY = 'DESCRIPTOR'

  def __init__(cls, name, bases, dictionary):
    """Creates a message service class.

    Args:
      name: Name of the class (ignored, but required by the metaclass
        protocol).

            

Reported by Pylint.

Unused argument 'name'
Error

Line: 64 Column: 21

              
  _DESCRIPTOR_KEY = 'DESCRIPTOR'

  def __init__(cls, name, bases, dictionary):
    """Creates a message service class.

    Args:
      name: Name of the class (ignored, but required by the metaclass
        protocol).

            

Reported by Pylint.

Attribute 'cls' defined outside __init__
Error

Line: 150 Column: 5

                                      rpc_controller, request, callback):
      return self._CallMethod(srvc, method_descriptor,
                       rpc_controller, request, callback)
    self.cls = cls
    cls.CallMethod = _WrapCallMethod
    cls.GetDescriptor = staticmethod(lambda: self.descriptor)
    cls.GetDescriptor.__doc__ = "Returns the service descriptor."
    cls.GetRequestClass = self._GetRequestClass
    cls.GetResponseClass = self._GetResponseClass

            

Reported by Pylint.

Access to a protected member _concrete_class of a client class
Error

Line: 190 Column: 12

                  if method_descriptor.containing_service != self.descriptor:
      raise RuntimeError(
          'GetRequestClass() given method descriptor for wrong service type.')
    return method_descriptor.input_type._concrete_class

  def _GetResponseClass(self, method_descriptor):
    """Returns the class of the response protocol message.

    Args:

            

Reported by Pylint.

Access to a protected member _concrete_class of a client class
Error

Line: 206 Column: 12

                  if method_descriptor.containing_service != self.descriptor:
      raise RuntimeError(
          'GetResponseClass() given method descriptor for wrong service type.')
    return method_descriptor.output_type._concrete_class

  def _GenerateNonImplementedMethod(self, method):
    """Generates and returns a method that can be set for a service methods.

    Args:

            

Reported by Pylint.

Attribute 'cls' defined outside __init__
Error

Line: 263 Column: 5

              
    def _ServiceStubInit(stub, rpc_channel):
      stub.rpc_channel = rpc_channel
    self.cls = cls
    cls.__init__ = _ServiceStubInit
    for method in self.descriptor.methods:
      setattr(cls, method.name, self._GenerateStubMethod(method))

  def _GenerateStubMethod(self, method):

            

Reported by Pylint.

Access to a protected member _concrete_class of a client class
Error

Line: 287 Column: 9

                  """
    return stub.rpc_channel.CallMethod(
        method_descriptor, rpc_controller, request,
        method_descriptor.output_type._concrete_class, callback)

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 44 Column: 1

              
class GeneratedServiceType(type):

  """Metaclass for service classes created at runtime from ServiceDescriptors.

  Implementations for all methods described in the Service class are added here
  by this class. We also create properties to allow getting/setting all fields
  in the protocol message.


            

Reported by Pylint.

java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java
104 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: 44

               */
public class TestBadIdentifiers extends TestCase {

  public void testCompilation() {
    // If this compiles, it means the generation was correct.
    TestBadIdentifiersProto.Deprecated unused1 =
        TestBadIdentifiersProto.Deprecated.newBuilder().build();
    TestBadIdentifiersProto.Override unused2 =
        TestBadIdentifiersProto.Override.getDefaultInstance();

            

Reported by PMD.

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

Line: 44

               */
public class TestBadIdentifiers extends TestCase {

  public void testCompilation() {
    // If this compiles, it means the generation was correct.
    TestBadIdentifiersProto.Deprecated unused1 =
        TestBadIdentifiersProto.Deprecated.newBuilder().build();
    TestBadIdentifiersProto.Override unused2 =
        TestBadIdentifiersProto.Override.getDefaultInstance();

            

Reported by PMD.

Avoid unused local variables such as 'unused1'.
Design

Line: 46

              
  public void testCompilation() {
    // If this compiles, it means the generation was correct.
    TestBadIdentifiersProto.Deprecated unused1 =
        TestBadIdentifiersProto.Deprecated.newBuilder().build();
    TestBadIdentifiersProto.Override unused2 =
        TestBadIdentifiersProto.Override.getDefaultInstance();
  }


            

Reported by PMD.

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

Line: 47

                public void testCompilation() {
    // If this compiles, it means the generation was correct.
    TestBadIdentifiersProto.Deprecated unused1 =
        TestBadIdentifiersProto.Deprecated.newBuilder().build();
    TestBadIdentifiersProto.Override unused2 =
        TestBadIdentifiersProto.Override.getDefaultInstance();
  }

  public void testGetDescriptor() {

            

Reported by PMD.

Avoid unused local variables such as 'unused2'.
Design

Line: 48

                  // If this compiles, it means the generation was correct.
    TestBadIdentifiersProto.Deprecated unused1 =
        TestBadIdentifiersProto.Deprecated.newBuilder().build();
    TestBadIdentifiersProto.Override unused2 =
        TestBadIdentifiersProto.Override.getDefaultInstance();
  }

  public void testGetDescriptor() {
    TestBadIdentifiersProto.getDescriptor();

            

Reported by PMD.

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

Line: 49

                  TestBadIdentifiersProto.Deprecated unused1 =
        TestBadIdentifiersProto.Deprecated.newBuilder().build();
    TestBadIdentifiersProto.Override unused2 =
        TestBadIdentifiersProto.Override.getDefaultInstance();
  }

  public void testGetDescriptor() {
    TestBadIdentifiersProto.getDescriptor();
    TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptor();

            

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: 52

                      TestBadIdentifiersProto.Override.getDefaultInstance();
  }

  public void testGetDescriptor() {
    TestBadIdentifiersProto.getDescriptor();
    TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptor();
    TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptorForType();
    TestBadIdentifiersProto.Descriptor.NestedDescriptor.getDefaultInstance().getDescriptor();
    TestBadIdentifiersProto.Descriptor.NestedDescriptor.getDefaultInstance().getDescriptorForType();

            

Reported by PMD.

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

Line: 52

                      TestBadIdentifiersProto.Override.getDefaultInstance();
  }

  public void testGetDescriptor() {
    TestBadIdentifiersProto.getDescriptor();
    TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptor();
    TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptorForType();
    TestBadIdentifiersProto.Descriptor.NestedDescriptor.getDefaultInstance().getDescriptor();
    TestBadIdentifiersProto.Descriptor.NestedDescriptor.getDefaultInstance().getDescriptorForType();

            

Reported by PMD.

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

Line: 54

              
  public void testGetDescriptor() {
    TestBadIdentifiersProto.getDescriptor();
    TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptor();
    TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptorForType();
    TestBadIdentifiersProto.Descriptor.NestedDescriptor.getDefaultInstance().getDescriptor();
    TestBadIdentifiersProto.Descriptor.NestedDescriptor.getDefaultInstance().getDescriptorForType();
  }


            

Reported by PMD.

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

Line: 54

              
  public void testGetDescriptor() {
    TestBadIdentifiersProto.getDescriptor();
    TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptor();
    TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptorForType();
    TestBadIdentifiersProto.Descriptor.NestedDescriptor.getDefaultInstance().getDescriptor();
    TestBadIdentifiersProto.Descriptor.NestedDescriptor.getDefaultInstance().getDescriptorForType();
  }


            

Reported by PMD.

conformance/ConformanceJava.java
100 issues
Avoid throwing raw exception types.
Design

Line: 156

                    exceptions.add(null);
    }
    if (messages.isEmpty()) {
      throw new RuntimeException("binary decoder types missing");
    }

    BinaryDecoder<T> decoder = new BinaryDecoder<>();

    boolean hasMessage = false;

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 185

                        sb.append(" rejected the payload.\n");
        }
      }
      throw new RuntimeException(sb.toString());
    }

    if (hasException) {
      // We do not check if exceptions are equal. Different implementations may return different
      // exception messages. Throw an arbitrary one out instead.

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 225

                        }
        }
      }
      throw new RuntimeException(sb.toString());
    }

    return messages.get(0);
  }


            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 266

                                .build();
            }
          } else {
            throw new RuntimeException("Protobuf request doesn't have specific payload type.");
          }
          break;
        }
      case JSON_PAYLOAD:
        {

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 289

                            parser.merge(request.getJsonPayload(), builder);
              testMessage = builder.build();
            } else {
              throw new RuntimeException("Protobuf request doesn't have specific payload type.");
            }
          } catch (InvalidProtocolBufferException e) {
            return Conformance.ConformanceResponse.newBuilder()
                .setParseError(e.getMessage())
                .build();

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 323

                                .build();
            }
          } else {
            throw new RuntimeException("Protobuf request doesn't have specific payload type.");
          }
          break;
        }
      case PAYLOAD_NOT_SET:
        {

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 329

                      }
      case PAYLOAD_NOT_SET:
        {
          throw new RuntimeException("Request didn't have payload.");
        }

      default:
        {
          throw new RuntimeException("Unexpected payload case.");

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 334

              
      default:
        {
          throw new RuntimeException("Unexpected payload case.");
        }
    }

    switch (request.getRequestedOutputFormat()) {
      case UNSPECIFIED:

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 340

              
    switch (request.getRequestedOutputFormat()) {
      case UNSPECIFIED:
        throw new RuntimeException("Unspecified output format.");

      case PROTOBUF:
        {
          ByteString messageString = testMessage.toByteString();
          return Conformance.ConformanceResponse.newBuilder()

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 369

              
      default:
        {
          throw new RuntimeException("Unexpected request output.");
        }
    }
  }

  private boolean doTestIo() throws Exception {

            

Reported by PMD.

java/core/src/test/java/com/google/protobuf/MessageTest.java
97 issues
This class has too many methods, consider refactoring it.
Design

Line: 48

              
/** Misc. unit tests for message operations that apply to both generated and dynamic messages. */
@RunWith(JUnit4.class)
public class MessageTest {
  // =================================================================
  // Message-merging tests.

  static final TestAllTypes MERGE_SOURCE =
      TestAllTypes.newBuilder()

            

Reported by PMD.

Do not add empty strings
Performance

Line: 69

                        .build();

  static final String MERGE_RESULT_TEXT =
      ""
          + "optional_int32: 1\n"
          + "optional_int64: 2\n"
          + "optional_string: \"foo\"\n"
          + "optional_foreign_message {\n"
          + "  c: 3\n"

            

Reported by PMD.

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

Line: 83

                public void testParsingWithNullExtensionRegistry() throws Exception {
    try {
      TestAllTypes.parseFrom(new byte[] {}, null);
      assertWithMessage("Expected exception").fail();
    } catch (NullPointerException expected) {
    }
  }

  @Test

            

Reported by PMD.

Avoid catching NullPointerException; consider removing the cause of the NPE.
Error

Line: 84

                  try {
      TestAllTypes.parseFrom(new byte[] {}, null);
      assertWithMessage("Expected exception").fail();
    } catch (NullPointerException expected) {
    }
  }

  @Test
  public void testMergeFrom() throws Exception {

            

Reported by PMD.

Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block
Design

Line: 84

                  try {
      TestAllTypes.parseFrom(new byte[] {}, null);
      assertWithMessage("Expected exception").fail();
    } catch (NullPointerException expected) {
    }
  }

  @Test
  public void testMergeFrom() throws Exception {

            

Reported by PMD.

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

Line: 92

                public void testMergeFrom() throws Exception {
    TestAllTypes result = TestAllTypes.newBuilder(MERGE_DEST).mergeFrom(MERGE_SOURCE).build();

    assertThat(result.toString()).isEqualTo(MERGE_RESULT_TEXT);
  }

  /**
   * Test merging a DynamicMessage into a GeneratedMessage. As long as they have the same
   * descriptor, this should work, but it is an entirely different code path.

            

Reported by PMD.

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

Line: 92

                public void testMergeFrom() throws Exception {
    TestAllTypes result = TestAllTypes.newBuilder(MERGE_DEST).mergeFrom(MERGE_SOURCE).build();

    assertThat(result.toString()).isEqualTo(MERGE_RESULT_TEXT);
  }

  /**
   * Test merging a DynamicMessage into a GeneratedMessage. As long as they have the same
   * descriptor, this should work, but it is an entirely different code path.

            

Reported by PMD.

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

Line: 106

                          .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
            .build();

    assertThat(result.toString()).isEqualTo(MERGE_RESULT_TEXT);
  }

  /** Test merging two DynamicMessages. */
  @Test
  public void testDynamicMergeFrom() throws Exception {

            

Reported by PMD.

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

Line: 106

                          .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
            .build();

    assertThat(result.toString()).isEqualTo(MERGE_RESULT_TEXT);
  }

  /** Test merging two DynamicMessages. */
  @Test
  public void testDynamicMergeFrom() throws Exception {

            

Reported by PMD.

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

Line: 117

                          .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build())
            .build();

    assertThat(result.toString()).isEqualTo(MERGE_RESULT_TEXT);
  }

  // =================================================================
  // Required-field-related tests.


            

Reported by PMD.

java/core/src/test/java/com/google/protobuf/AbstractMessageTest.java
95 issues
Object clone() should be implemented with super.clone()
Error

Line: 137

                    }

      @Override
      public Builder clone() {
        return new Builder(wrappedBuilder.clone());
      }

      @Override
      public boolean isInitialized() {

            

Reported by PMD.

This class has a bunch of public methods and attributes
Design

Line: 31

              // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package com.google.protobuf;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.protobuf.TestUtil.TEST_REQUIRED_INITIALIZED;
import static com.google.protobuf.TestUtil.TEST_REQUIRED_UNINITIALIZED;

            

Reported by PMD.

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

Line: 55

              
/** Unit test for {@link AbstractMessage}. */
@RunWith(JUnit4.class)
public class AbstractMessageTest {
  /**
   * Extends AbstractMessage and wraps some other message object. The methods of the Message
   * interface which aren't explicitly implemented by AbstractMessage are forwarded to the wrapped
   * object. This allows us to test that AbstractMessage's implementations work even if the wrapped
   * object does not use them.

            

Reported by PMD.

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

Line: 63

                 * object does not use them.
   */
  private static class AbstractMessageWrapper extends AbstractMessage {
    private final Message wrappedMessage;

    public AbstractMessageWrapper(Message wrappedMessage) {
      this.wrappedMessage = wrappedMessage;
    }


            

Reported by PMD.

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

Line: 120

                  }

    static class Builder extends AbstractMessage.Builder<Builder> {
      private final Message.Builder wrappedBuilder;

      public Builder(Message.Builder wrappedBuilder) {
        this.wrappedBuilder = wrappedBuilder;
      }


            

Reported by PMD.

clone() method should be implemented only if implementing Cloneable interface
Error

Line: 137

                    }

      @Override
      public Builder clone() {
        return new Builder(wrappedBuilder.clone());
      }

      @Override
      public boolean isInitialized() {

            

Reported by PMD.

clone() method should throw CloneNotSupportedException
Error

Line: 137

                    }

      @Override
      public Builder clone() {
        return new Builder(wrappedBuilder.clone());
      }

      @Override
      public boolean isInitialized() {

            

Reported by PMD.

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

Line: 143

              
      @Override
      public boolean isInitialized() {
        return clone().buildPartial().isInitialized();
      }

      @Override
      public Descriptors.Descriptor getDescriptorForType() {
        return wrappedBuilder.getDescriptorForType();

            

Reported by PMD.

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

Line: 143

              
      @Override
      public boolean isInitialized() {
        return clone().buildPartial().isInitialized();
      }

      @Override
      public Descriptors.Descriptor getDescriptorForType() {
        return wrappedBuilder.getDescriptorForType();

            

Reported by PMD.

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

Line: 243

                        TestAllExtensions.getDescriptor(), TestUtil.getFullExtensionRegistry());

  @Test
  public void testClear() throws Exception {
    AbstractMessageWrapper message =
        new AbstractMessageWrapper.Builder(TestAllTypes.newBuilder(TestUtil.getAllSet()))
            .clear()
            .build();
    TestUtil.assertClear((TestAllTypes) message.wrappedMessage);

            

Reported by PMD.

java/core/src/test/java/com/google/protobuf/RepeatedFieldBuilderV3Test.java
95 issues
Unit tests should not contain more than 1 assert(s).
Design

Line: 52

              public class RepeatedFieldBuilderV3Test {

  @Test
  public void testBasicUse() {
    TestUtil.MockBuilderParent mockParent = new TestUtil.MockBuilderParent();
    RepeatedFieldBuilderV3<TestAllTypes, TestAllTypes.Builder, TestAllTypesOrBuilder> builder =
        newRepeatedFieldBuilderV3(mockParent);
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build());
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());

            

Reported by PMD.

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

Line: 58

                      newRepeatedFieldBuilderV3(mockParent);
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build());
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
    assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(0);
    assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(1);

    List<TestAllTypes> list = builder.build();
    assertThat(list).hasSize(2);
    assertThat(list.get(0).getOptionalInt32()).isEqualTo(0);

            

Reported by PMD.

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

Line: 58

                      newRepeatedFieldBuilderV3(mockParent);
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build());
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
    assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(0);
    assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(1);

    List<TestAllTypes> list = builder.build();
    assertThat(list).hasSize(2);
    assertThat(list.get(0).getOptionalInt32()).isEqualTo(0);

            

Reported by PMD.

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

Line: 59

                  builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build());
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
    assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(0);
    assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(1);

    List<TestAllTypes> list = builder.build();
    assertThat(list).hasSize(2);
    assertThat(list.get(0).getOptionalInt32()).isEqualTo(0);
    assertThat(list.get(1).getOptionalInt32()).isEqualTo(1);

            

Reported by PMD.

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

Line: 59

                  builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(0).build());
    builder.addMessage(TestAllTypes.newBuilder().setOptionalInt32(1).build());
    assertThat(builder.getMessage(0).getOptionalInt32()).isEqualTo(0);
    assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(1);

    List<TestAllTypes> list = builder.build();
    assertThat(list).hasSize(2);
    assertThat(list.get(0).getOptionalInt32()).isEqualTo(0);
    assertThat(list.get(1).getOptionalInt32()).isEqualTo(1);

            

Reported by PMD.

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

Line: 62

                  assertThat(builder.getMessage(1).getOptionalInt32()).isEqualTo(1);

    List<TestAllTypes> list = builder.build();
    assertThat(list).hasSize(2);
    assertThat(list.get(0).getOptionalInt32()).isEqualTo(0);
    assertThat(list.get(1).getOptionalInt32()).isEqualTo(1);
    assertIsUnmodifiable(list);

    // Make sure it doesn't change.

            

Reported by PMD.

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

Line: 63

              
    List<TestAllTypes> list = builder.build();
    assertThat(list).hasSize(2);
    assertThat(list.get(0).getOptionalInt32()).isEqualTo(0);
    assertThat(list.get(1).getOptionalInt32()).isEqualTo(1);
    assertIsUnmodifiable(list);

    // Make sure it doesn't change.
    List<TestAllTypes> list2 = builder.build();

            

Reported by PMD.

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

Line: 63

              
    List<TestAllTypes> list = builder.build();
    assertThat(list).hasSize(2);
    assertThat(list.get(0).getOptionalInt32()).isEqualTo(0);
    assertThat(list.get(1).getOptionalInt32()).isEqualTo(1);
    assertIsUnmodifiable(list);

    // Make sure it doesn't change.
    List<TestAllTypes> list2 = builder.build();

            

Reported by PMD.

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

Line: 63

              
    List<TestAllTypes> list = builder.build();
    assertThat(list).hasSize(2);
    assertThat(list.get(0).getOptionalInt32()).isEqualTo(0);
    assertThat(list.get(1).getOptionalInt32()).isEqualTo(1);
    assertIsUnmodifiable(list);

    // Make sure it doesn't change.
    List<TestAllTypes> list2 = builder.build();

            

Reported by PMD.

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

Line: 64

                  List<TestAllTypes> list = builder.build();
    assertThat(list).hasSize(2);
    assertThat(list.get(0).getOptionalInt32()).isEqualTo(0);
    assertThat(list.get(1).getOptionalInt32()).isEqualTo(1);
    assertIsUnmodifiable(list);

    // Make sure it doesn't change.
    List<TestAllTypes> list2 = builder.build();
    assertThat(list).isSameInstanceAs(list2);

            

Reported by PMD.

java/core/src/main/java/com/google/protobuf/ExtensionSchemaFull.java
94 issues
Avoid reassigning parameters such as 'unknownFields'
Design

Line: 92

                    Object extensionObject,
      ExtensionRegistryLite extensionRegistry,
      FieldSet<FieldDescriptor> extensions,
      UB unknownFields,
      UnknownFieldSchema<UT, UB> unknownFieldSchema)
      throws IOException {
    ExtensionRegistry.ExtensionInfo extension = (ExtensionRegistry.ExtensionInfo) extensionObject;
    int fieldNumber = extension.descriptor.getNumber();


            

Reported by PMD.

The class 'ExtensionSchemaFull' has a total cyclomatic complexity of 101 (highest 45).
Design

Line: 43

              import java.util.Map;

@SuppressWarnings("unchecked")
final class ExtensionSchemaFull extends ExtensionSchema<FieldDescriptor> {

  private static final long EXTENSION_FIELD_OFFSET = getExtensionsFieldOffset();

  private static <T> long getExtensionsFieldOffset() {
    try {

            

Reported by PMD.

The class 'ExtensionSchemaFull' has a Standard Cyclomatic Complexity of 8 (Highest = 41).
Design

Line: 43

              import java.util.Map;

@SuppressWarnings("unchecked")
final class ExtensionSchemaFull extends ExtensionSchema<FieldDescriptor> {

  private static final long EXTENSION_FIELD_OFFSET = getExtensionsFieldOffset();

  private static <T> long getExtensionsFieldOffset() {
    try {

            

Reported by PMD.

The class 'ExtensionSchemaFull' has a Modified Cyclomatic Complexity of 3 (Highest = 11).
Design

Line: 43

              import java.util.Map;

@SuppressWarnings("unchecked")
final class ExtensionSchemaFull extends ExtensionSchema<FieldDescriptor> {

  private static final long EXTENSION_FIELD_OFFSET = getExtensionsFieldOffset();

  private static <T> long getExtensionsFieldOffset() {
    try {

            

Reported by PMD.

Possible God Class (WMC=101, ATFD=122, TCC=1.515%)
Design

Line: 43

              import java.util.Map;

@SuppressWarnings("unchecked")
final class ExtensionSchemaFull extends ExtensionSchema<FieldDescriptor> {

  private static final long EXTENSION_FIELD_OFFSET = getExtensionsFieldOffset();

  private static <T> long getExtensionsFieldOffset() {
    try {

            

Reported by PMD.

A catch statement should never catch throwable since it includes errors.
Error

Line: 51

                  try {
      Field field = GeneratedMessageV3.ExtendableMessage.class.getDeclaredField("extensions");
      return UnsafeUtil.objectFieldOffset(field);
    } catch (Throwable e) {
      throw new IllegalStateException("Unable to lookup extension field offset");
    }
  }

  @Override

            

Reported by PMD.

New exception is thrown in catch block, original stack trace may be lost
Design

Line: 52

                    Field field = GeneratedMessageV3.ExtendableMessage.class.getDeclaredField("extensions");
      return UnsafeUtil.objectFieldOffset(field);
    } catch (Throwable e) {
      throw new IllegalStateException("Unable to lookup extension field offset");
    }
  }

  @Override
  boolean hasExtensions(MessageLite prototype) {

            

Reported by PMD.

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

Line: 74

                @Override
  FieldSet<FieldDescriptor> getMutableExtensions(Object message) {
    FieldSet<FieldDescriptor> extensions = getExtensions(message);
    if (extensions.isImmutable()) {
      extensions = extensions.clone();
      setExtensions(message, extensions);
    }
    return extensions;
  }

            

Reported by PMD.

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

Line: 83

              
  @Override
  void makeImmutable(Object message) {
    getExtensions(message).makeImmutable();
  }

  @Override
  <UT, UB> UB parseExtension(
      Reader reader,

            

Reported by PMD.

The method parseExtension() has an NCSS line count of 164
Design

Line: 87

                }

  @Override
  <UT, UB> UB parseExtension(
      Reader reader,
      Object extensionObject,
      ExtensionRegistryLite extensionRegistry,
      FieldSet<FieldDescriptor> extensions,
      UB unknownFields,

            

Reported by PMD.

java/core/src/test/java/com/google/protobuf/DynamicMessageTest.java
93 issues
This class has too many methods, consider refactoring it.
Design

Line: 53

               * DynamicMessage} functionality.
 */
@RunWith(JUnit4.class)
public class DynamicMessageTest {
  TestUtil.ReflectionTester reflectionTester =
      new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);

  TestUtil.ReflectionTester extensionsReflectionTester =
      new TestUtil.ReflectionTester(

            

Reported by PMD.

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

Line: 54

               */
@RunWith(JUnit4.class)
public class DynamicMessageTest {
  TestUtil.ReflectionTester reflectionTester =
      new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);

  TestUtil.ReflectionTester extensionsReflectionTester =
      new TestUtil.ReflectionTester(
          TestAllExtensions.getDescriptor(), TestUtil.getFullExtensionRegistry());

            

Reported by PMD.

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

Line: 57

                TestUtil.ReflectionTester reflectionTester =
      new TestUtil.ReflectionTester(TestAllTypes.getDescriptor(), null);

  TestUtil.ReflectionTester extensionsReflectionTester =
      new TestUtil.ReflectionTester(
          TestAllExtensions.getDescriptor(), TestUtil.getFullExtensionRegistry());
  TestUtil.ReflectionTester packedReflectionTester =
      new TestUtil.ReflectionTester(TestPackedTypes.getDescriptor(), null);


            

Reported by PMD.

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

Line: 60

                TestUtil.ReflectionTester extensionsReflectionTester =
      new TestUtil.ReflectionTester(
          TestAllExtensions.getDescriptor(), TestUtil.getFullExtensionRegistry());
  TestUtil.ReflectionTester packedReflectionTester =
      new TestUtil.ReflectionTester(TestPackedTypes.getDescriptor(), null);

  @Test
  public void testDynamicMessageAccessors() throws Exception {
    Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());

            

Reported by PMD.

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

Line: 64

                    new TestUtil.ReflectionTester(TestPackedTypes.getDescriptor(), null);

  @Test
  public void testDynamicMessageAccessors() throws Exception {
    Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
    reflectionTester.setAllFieldsViaReflection(builder);
    Message message = builder.build();
    reflectionTester.assertAllFieldsSetViaReflection(message);
  }

            

Reported by PMD.

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

Line: 72

                }

  @Test
  public void testSettersAfterBuild() throws Exception {
    Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
    Message firstMessage = builder.build();
    // double build()
    Message unused = builder.build();
    // clear() after build()

            

Reported by PMD.

Avoid unused local variables such as 'unused'.
Design

Line: 76

                  Message.Builder builder = DynamicMessage.newBuilder(TestAllTypes.getDescriptor());
    Message firstMessage = builder.build();
    // double build()
    Message unused = builder.build();
    // clear() after build()
    builder.clear();
    // setters after build()
    reflectionTester.setAllFieldsViaReflection(builder);
    Message message = builder.build();

            

Reported by PMD.

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

Line: 92

                }

  @Test
  public void testUnknownFields() throws Exception {
    Message.Builder builder = DynamicMessage.newBuilder(TestEmptyMessage.getDescriptor());
    builder.setUnknownFields(
        UnknownFieldSet.newBuilder()
            .addField(1, UnknownFieldSet.Field.newBuilder().addVarint(1).build())
            .addField(2, UnknownFieldSet.Field.newBuilder().addFixed32(1).build())

            

Reported by PMD.

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

Line: 96

                  Message.Builder builder = DynamicMessage.newBuilder(TestEmptyMessage.getDescriptor());
    builder.setUnknownFields(
        UnknownFieldSet.newBuilder()
            .addField(1, UnknownFieldSet.Field.newBuilder().addVarint(1).build())
            .addField(2, UnknownFieldSet.Field.newBuilder().addFixed32(1).build())
            .build());
    Message message = builder.build();
    assertThat(builder.getUnknownFields().asMap()).hasSize(2);
    // clone() with unknown fields

            

Reported by PMD.

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

Line: 97

                  builder.setUnknownFields(
        UnknownFieldSet.newBuilder()
            .addField(1, UnknownFieldSet.Field.newBuilder().addVarint(1).build())
            .addField(2, UnknownFieldSet.Field.newBuilder().addFixed32(1).build())
            .build());
    Message message = builder.build();
    assertThat(builder.getUnknownFields().asMap()).hasSize(2);
    // clone() with unknown fields
    Message.Builder newBuilder = builder.clone();

            

Reported by PMD.

java/core/src/main/java/com/google/protobuf/MessageReflection.java
89 issues
Avoid reassigning parameters such as 'fields'
Design

Line: 49

              
  static void writeMessageTo(
      Message message,
      Map<FieldDescriptor, Object> fields,
      CodedOutputStream output,
      boolean alwaysWriteRequiredFields)
      throws IOException {
    final boolean isMessageSet =
        message.getDescriptorForType().getOptions().getMessageSetWireFormat();

            

Reported by PMD.

This class has a bunch of public methods and attributes
Design

Line: 31

              // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package com.google.protobuf;

import com.google.protobuf.Descriptors.FieldDescriptor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

            

Reported by PMD.

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: 45

               *
 * @author liujisi@google.com (Pherl Liu)
 */
class MessageReflection {

  static void writeMessageTo(
      Message message,
      Map<FieldDescriptor, Object> fields,
      CodedOutputStream output,

            

Reported by PMD.

The class 'MessageReflection' has a total cyclomatic complexity of 94 (highest 30).
Design

Line: 45

               *
 * @author liujisi@google.com (Pherl Liu)
 */
class MessageReflection {

  static void writeMessageTo(
      Message message,
      Map<FieldDescriptor, Object> fields,
      CodedOutputStream output,

            

Reported by PMD.

The class 'MessageReflection' has a Standard Cyclomatic Complexity of 7 (Highest = 26).
Design

Line: 45

               *
 * @author liujisi@google.com (Pherl Liu)
 */
class MessageReflection {

  static void writeMessageTo(
      Message message,
      Map<FieldDescriptor, Object> fields,
      CodedOutputStream output,

            

Reported by PMD.

The class 'MessageReflection' has a Modified Cyclomatic Complexity of 7 (Highest = 24).
Design

Line: 45

               *
 * @author liujisi@google.com (Pherl Liu)
 */
class MessageReflection {

  static void writeMessageTo(
      Message message,
      Map<FieldDescriptor, Object> fields,
      CodedOutputStream output,

            

Reported by PMD.

Possible God Class (WMC=94, ATFD=106, TCC=0.000%)
Design

Line: 45

               *
 * @author liujisi@google.com (Pherl Liu)
 */
class MessageReflection {

  static void writeMessageTo(
      Message message,
      Map<FieldDescriptor, Object> fields,
      CodedOutputStream output,

            

Reported by PMD.

The method 'writeMessageTo(Message, Map, CodedOutputStream, boolean)' has a cyclomatic complexity of 11.
Design

Line: 47

               */
class MessageReflection {

  static void writeMessageTo(
      Message message,
      Map<FieldDescriptor, Object> fields,
      CodedOutputStream output,
      boolean alwaysWriteRequiredFields)
      throws IOException {

            

Reported by PMD.

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

Line: 54

                    boolean alwaysWriteRequiredFields)
      throws IOException {
    final boolean isMessageSet =
        message.getDescriptorForType().getOptions().getMessageSetWireFormat();
    if (alwaysWriteRequiredFields) {
      fields = new TreeMap<FieldDescriptor, Object>(fields);
      for (final FieldDescriptor field : message.getDescriptorForType().getFields()) {
        if (field.isRequired() && !fields.containsKey(field)) {
          fields.put(field, message.getField(field));

            

Reported by PMD.

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

Line: 54

                    boolean alwaysWriteRequiredFields)
      throws IOException {
    final boolean isMessageSet =
        message.getDescriptorForType().getOptions().getMessageSetWireFormat();
    if (alwaysWriteRequiredFields) {
      fields = new TreeMap<FieldDescriptor, Object>(fields);
      for (final FieldDescriptor field : message.getDescriptorForType().getFields()) {
        if (field.isRequired() && !fields.containsKey(field)) {
          fields.put(field, message.getField(field));

            

Reported by PMD.