The following issues were found

java/core/src/test/java/com/google/protobuf/Proto2ExtensionLookupSchemaTest.java
49 issues
Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 48

              
@RunWith(JUnit4.class)
public class Proto2ExtensionLookupSchemaTest {
  private byte[] data;
  private ExtensionRegistry extensionRegistry;

  @Before
  public void setup() {
    TestSchemas.registerGenericProto2Schemas();

            

Reported by PMD.

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

Line: 49

              @RunWith(JUnit4.class)
public class Proto2ExtensionLookupSchemaTest {
  private byte[] data;
  private ExtensionRegistry extensionRegistry;

  @Before
  public void setup() {
    TestSchemas.registerGenericProto2Schemas();


            

Reported by PMD.

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

Line: 55

                public void setup() {
    TestSchemas.registerGenericProto2Schemas();

    Protobuf.getInstance().schemaFor(Proto2MessageWithExtensions.class);
    data = new Proto2MessageFactory(10, 20, 1, 1).newMessage().toByteArray();
    extensionRegistry = ExtensionRegistry.newInstance();
    Proto2Testing.registerAllExtensions(extensionRegistry);
  }


            

Reported by PMD.

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

Line: 62

                }

  @Test
  public void testExtensions() throws Exception {
    Proto2MessageWithExtensions base =
        Proto2MessageWithExtensions.parseFrom(data, extensionRegistry);

    Proto2MessageWithExtensions message =
        ExperimentalSerializationUtil.fromByteArray(

            

Reported by PMD.

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

Line: 69

                  Proto2MessageWithExtensions message =
        ExperimentalSerializationUtil.fromByteArray(
            data, Proto2MessageWithExtensions.class, extensionRegistry);
    assertThat(message).isEqualTo(base);

    Proto2MessageWithExtensions roundtripMessage =
        ExperimentalSerializationUtil.fromByteArray(
            ExperimentalSerializationUtil.toByteArray(message),
            Proto2MessageWithExtensions.class,

            

Reported by PMD.

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

Line: 76

                          ExperimentalSerializationUtil.toByteArray(message),
            Proto2MessageWithExtensions.class,
            extensionRegistry);
    assertThat(roundtripMessage).isEqualTo(base);
  }

  @Test
  public void testUnknownEnum() throws Exception {
    // Use unknown fields to hold invalid enum values.

            

Reported by PMD.

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

Line: 80

                }

  @Test
  public void testUnknownEnum() throws Exception {
    // Use unknown fields to hold invalid enum values.
    UnknownFieldSetLite unknowns = UnknownFieldSetLite.newInstance();
    final int outOfRange = 1000;
    assertThat(TestEnum.forNumber(outOfRange)).isNull();
    unknowns.storeField(

            

Reported by PMD.

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

Line: 84

                  // Use unknown fields to hold invalid enum values.
    UnknownFieldSetLite unknowns = UnknownFieldSetLite.newInstance();
    final int outOfRange = 1000;
    assertThat(TestEnum.forNumber(outOfRange)).isNull();
    unknowns.storeField(
        WireFormat.makeTag(Proto2Message.FIELD_ENUM_13_FIELD_NUMBER, WireFormat.WIRETYPE_VARINT),
        (long) outOfRange);
    unknowns.storeField(
        WireFormat.makeTag(

            

Reported by PMD.

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

Line: 85

                  UnknownFieldSetLite unknowns = UnknownFieldSetLite.newInstance();
    final int outOfRange = 1000;
    assertThat(TestEnum.forNumber(outOfRange)).isNull();
    unknowns.storeField(
        WireFormat.makeTag(Proto2Message.FIELD_ENUM_13_FIELD_NUMBER, WireFormat.WIRETYPE_VARINT),
        (long) outOfRange);
    unknowns.storeField(
        WireFormat.makeTag(
            Proto2Message.FIELD_ENUM_LIST_30_FIELD_NUMBER, WireFormat.WIRETYPE_VARINT),

            

Reported by PMD.

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

Line: 88

                  unknowns.storeField(
        WireFormat.makeTag(Proto2Message.FIELD_ENUM_13_FIELD_NUMBER, WireFormat.WIRETYPE_VARINT),
        (long) outOfRange);
    unknowns.storeField(
        WireFormat.makeTag(
            Proto2Message.FIELD_ENUM_LIST_30_FIELD_NUMBER, WireFormat.WIRETYPE_VARINT),
        (long) TestEnum.ONE_VALUE);
    unknowns.storeField(
        WireFormat.makeTag(

            

Reported by PMD.

java/core/src/test/java/com/google/protobuf/Proto2MessageFactory.java
49 issues
The class 'Proto2MessageFactory' has a Modified Cyclomatic Complexity of 2 (Highest = 19).
Design

Line: 41

              import java.util.Map;

/** Creates instances of {@link Proto2Message} based on the tree configuration. */
public final class Proto2MessageFactory implements ExperimentalMessageFactory<Proto2Message> {
  private final int numRepeatedFields;
  private final int branchingFactor;
  private final Proto2MessageFactory nextLevel;
  private final ExperimentalTestDataProvider data;


            

Reported by PMD.

The class 'Proto2MessageFactory' has a Standard Cyclomatic Complexity of 2 (Highest = 19).
Design

Line: 41

              import java.util.Map;

/** Creates instances of {@link Proto2Message} based on the tree configuration. */
public final class Proto2MessageFactory implements ExperimentalMessageFactory<Proto2Message> {
  private final int numRepeatedFields;
  private final int branchingFactor;
  private final Proto2MessageFactory nextLevel;
  private final ExperimentalTestDataProvider data;


            

Reported by PMD.

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

Line: 42

              
/** Creates instances of {@link Proto2Message} based on the tree configuration. */
public final class Proto2MessageFactory implements ExperimentalMessageFactory<Proto2Message> {
  private final int numRepeatedFields;
  private final int branchingFactor;
  private final Proto2MessageFactory nextLevel;
  private final ExperimentalTestDataProvider data;

  public Proto2MessageFactory(

            

Reported by PMD.

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

Line: 43

              /** Creates instances of {@link Proto2Message} based on the tree configuration. */
public final class Proto2MessageFactory implements ExperimentalMessageFactory<Proto2Message> {
  private final int numRepeatedFields;
  private final int branchingFactor;
  private final Proto2MessageFactory nextLevel;
  private final ExperimentalTestDataProvider data;

  public Proto2MessageFactory(
      int numRepeatedFields, int stringLength, int branchingFactor, int treeDepth) {

            

Reported by PMD.

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

Line: 44

              public final class Proto2MessageFactory implements ExperimentalMessageFactory<Proto2Message> {
  private final int numRepeatedFields;
  private final int branchingFactor;
  private final Proto2MessageFactory nextLevel;
  private final ExperimentalTestDataProvider data;

  public Proto2MessageFactory(
      int numRepeatedFields, int stringLength, int branchingFactor, int treeDepth) {
    this(

            

Reported by PMD.

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

Line: 45

                private final int numRepeatedFields;
  private final int branchingFactor;
  private final Proto2MessageFactory nextLevel;
  private final ExperimentalTestDataProvider data;

  public Proto2MessageFactory(
      int numRepeatedFields, int stringLength, int branchingFactor, int treeDepth) {
    this(
        new ExperimentalTestDataProvider(stringLength),

            

Reported by PMD.

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

Line: 92

                  // repeated message field below.
    builder.setFieldBytes11(data.getBytes());
    builder.setFieldUint3212(data.getInt());
    builder.setFieldEnum13(Proto2Message.TestEnum.forNumber(data.getEnum()));
    builder.setFieldSfixed3214(data.getInt());
    builder.setFieldSfixed6415(data.getLong());
    builder.setFieldSint3216(data.getInt());
    builder.setFieldSint6417(data.getLong());


            

Reported by PMD.

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

Line: 111

                    // Repeated message field is controlled by the branching factor below.
      builder.addFieldBytesList28(data.getBytes());
      builder.addFieldUint32List29(data.getInt());
      builder.addFieldEnumList30(Proto2Message.TestEnum.forNumber(data.getEnum()));
      builder.addFieldSfixed32List31(data.getInt());
      builder.addFieldSfixed64List32(data.getLong());
      builder.addFieldSint32List33(data.getInt());
      builder.addFieldSint64List34(data.getLong());


            

Reported by PMD.

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

Line: 126

                    builder.addFieldFixed32ListPacked41(data.getInt());
      builder.addFieldBoolListPacked42(data.getBool());
      builder.addFieldUint32ListPacked43(data.getInt());
      builder.addFieldEnumListPacked44(Proto2Message.TestEnum.forNumber(data.getEnum()));
      builder.addFieldSfixed32ListPacked45(data.getInt());
      builder.addFieldSfixed64ListPacked46(data.getLong());
      builder.addFieldSint32ListPacked47(data.getInt());
      builder.addFieldSint64ListPacked48(data.getLong());
    }

            

Reported by PMD.

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

Line: 133

                    builder.addFieldSint64ListPacked48(data.getLong());
    }

    builder.setFieldGroup49(Proto2Message.FieldGroup49.newBuilder().setFieldInt3250(data.getInt()));

    for (int i = 0; i < branchingFactor; ++i) {
      builder.addFieldGroupList51(
          Proto2Message.FieldGroupList51.newBuilder().setFieldInt3252(data.getInt()));
    }

            

Reported by PMD.

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

Line: 50

               * UTF-8 checks.
 */
@RunWith(JUnit4.class)
public class CheckUtf8Test {

  private static final String UTF8_BYTE_STRING_TEXT = "some text";
  private static final ByteString UTF8_BYTE_STRING = ByteString.copyFromUtf8(UTF8_BYTE_STRING_TEXT);
  private static final ByteString NON_UTF8_BYTE_STRING =
      ByteString.copyFrom(new byte[] {(byte) 0x80}); // A lone continuation byte.

            

Reported by PMD.

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

Line: 59

              
  @Test
  public void testBuildRequiredStringWithGoodUtf8() throws Exception {
    assertThat(StringWrapper.newBuilder().setReqBytes(UTF8_BYTE_STRING).getReq())
        .isEqualTo(UTF8_BYTE_STRING_TEXT);
  }

  @Test
  public void testParseRequiredStringWithGoodUtf8() throws Exception {

            

Reported by PMD.

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

Line: 67

                public void testParseRequiredStringWithGoodUtf8() throws Exception {
    ByteString serialized =
        BytesWrapper.newBuilder().setReq(UTF8_BYTE_STRING).build().toByteString();
    assertThat(StringWrapper.parser().parseFrom(serialized).getReq())
        .isEqualTo(UTF8_BYTE_STRING_TEXT);
  }

  @Test
  public void testBuildRequiredStringWithBadUtf8() throws Exception {

            

Reported by PMD.

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

Line: 67

                public void testParseRequiredStringWithGoodUtf8() throws Exception {
    ByteString serialized =
        BytesWrapper.newBuilder().setReq(UTF8_BYTE_STRING).build().toByteString();
    assertThat(StringWrapper.parser().parseFrom(serialized).getReq())
        .isEqualTo(UTF8_BYTE_STRING_TEXT);
  }

  @Test
  public void testBuildRequiredStringWithBadUtf8() throws Exception {

            

Reported by PMD.

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

Line: 67

                public void testParseRequiredStringWithGoodUtf8() throws Exception {
    ByteString serialized =
        BytesWrapper.newBuilder().setReq(UTF8_BYTE_STRING).build().toByteString();
    assertThat(StringWrapper.parser().parseFrom(serialized).getReq())
        .isEqualTo(UTF8_BYTE_STRING_TEXT);
  }

  @Test
  public void testBuildRequiredStringWithBadUtf8() throws Exception {

            

Reported by PMD.

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

Line: 72

                }

  @Test
  public void testBuildRequiredStringWithBadUtf8() throws Exception {
    try {
      StringWrapper.newBuilder().setReqBytes(NON_UTF8_BYTE_STRING);
      assertWithMessage("Expected IllegalArgumentException for non UTF-8 byte string.").fail();
    } catch (IllegalArgumentException exception) {
      assertThat(exception).hasMessageThat().isEqualTo("Byte string is not UTF-8.");

            

Reported by PMD.

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

Line: 75

                public void testBuildRequiredStringWithBadUtf8() throws Exception {
    try {
      StringWrapper.newBuilder().setReqBytes(NON_UTF8_BYTE_STRING);
      assertWithMessage("Expected IllegalArgumentException for non UTF-8 byte string.").fail();
    } catch (IllegalArgumentException exception) {
      assertThat(exception).hasMessageThat().isEqualTo("Byte string is not UTF-8.");
    }
  }


            

Reported by PMD.

The String literal 'Expected IllegalArgumentException for non UTF-8 byte string.' appears 6 times in this file; the first occurrence is on line 75
Error

Line: 75

                public void testBuildRequiredStringWithBadUtf8() throws Exception {
    try {
      StringWrapper.newBuilder().setReqBytes(NON_UTF8_BYTE_STRING);
      assertWithMessage("Expected IllegalArgumentException for non UTF-8 byte string.").fail();
    } catch (IllegalArgumentException exception) {
      assertThat(exception).hasMessageThat().isEqualTo("Byte string is not UTF-8.");
    }
  }


            

Reported by PMD.

The String literal 'Byte string is not UTF-8.' appears 6 times in this file; the first occurrence is on line 77
Error

Line: 77

                    StringWrapper.newBuilder().setReqBytes(NON_UTF8_BYTE_STRING);
      assertWithMessage("Expected IllegalArgumentException for non UTF-8 byte string.").fail();
    } catch (IllegalArgumentException exception) {
      assertThat(exception).hasMessageThat().isEqualTo("Byte string is not UTF-8.");
    }
  }

  @Test
  public void testBuildOptionalStringWithBadUtf8() throws Exception {

            

Reported by PMD.

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

Line: 77

                    StringWrapper.newBuilder().setReqBytes(NON_UTF8_BYTE_STRING);
      assertWithMessage("Expected IllegalArgumentException for non UTF-8 byte string.").fail();
    } catch (IllegalArgumentException exception) {
      assertThat(exception).hasMessageThat().isEqualTo("Byte string is not UTF-8.");
    }
  }

  @Test
  public void testBuildOptionalStringWithBadUtf8() throws Exception {

            

Reported by PMD.

kokoro/linux/make_test_output.py
48 issues
Unable to import 'yattag'
Error

Line: 22 Column: 1

              
import os
import sys
from yattag import Doc
from collections import defaultdict


def readtests(basedir):
  tests = defaultdict(dict)

            

Reported by Pylint.

Unused variable 'firstline'
Error

Line: 34 Column: 5

                # Seq	Host	Starttime	Runtime	Send	Receive	Exitval	Signal	Command
  # 1	:	1456263838.313	0.005	0	0	0	0	echo A
  with open(basedir + "/joblog") as jobs:
    firstline = next(jobs)
    for line in jobs:
      values = line.split("\t")

      name = values[8].split()[-1]
      test = tests[name]

            

Reported by Pylint.

standard import "from collections import defaultdict" should be placed before "from yattag import Doc"
Error

Line: 23 Column: 1

              import os
import sys
from yattag import Doc
from collections import defaultdict


def readtests(basedir):
  tests = defaultdict(dict)


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 26 Column: 1

              from collections import defaultdict


def readtests(basedir):
  tests = defaultdict(dict)

  # Sample input (note: separators are tabs).
  #
  # Seq	Host	Starttime	Runtime	Send	Receive	Exitval	Signal	Command

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 27 Column: 1

              

def readtests(basedir):
  tests = defaultdict(dict)

  # Sample input (note: separators are tabs).
  #
  # Seq	Host	Starttime	Runtime	Send	Receive	Exitval	Signal	Command
  # 1	:	1456263838.313	0.005	0	0	0	0	echo A

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 33 Column: 1

                #
  # Seq	Host	Starttime	Runtime	Send	Receive	Exitval	Signal	Command
  # 1	:	1456263838.313	0.005	0	0	0	0	echo A
  with open(basedir + "/joblog") as jobs:
    firstline = next(jobs)
    for line in jobs:
      values = line.split("\t")

      name = values[8].split()[-1]

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 34 Column: 1

                # Seq	Host	Starttime	Runtime	Send	Receive	Exitval	Signal	Command
  # 1	:	1456263838.313	0.005	0	0	0	0	echo A
  with open(basedir + "/joblog") as jobs:
    firstline = next(jobs)
    for line in jobs:
      values = line.split("\t")

      name = values[8].split()[-1]
      test = tests[name]

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 35 Column: 1

                # 1	:	1456263838.313	0.005	0	0	0	0	echo A
  with open(basedir + "/joblog") as jobs:
    firstline = next(jobs)
    for line in jobs:
      values = line.split("\t")

      name = values[8].split()[-1]
      test = tests[name]
      test["name"] = name

            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 36 Column: 1

                with open(basedir + "/joblog") as jobs:
    firstline = next(jobs)
    for line in jobs:
      values = line.split("\t")

      name = values[8].split()[-1]
      test = tests[name]
      test["name"] = name
      test["time"] = values[3]

            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 38 Column: 1

                  for line in jobs:
      values = line.split("\t")

      name = values[8].split()[-1]
      test = tests[name]
      test["name"] = name
      test["time"] = values[3]

      exitval = values[6]

            

Reported by Pylint.

java/core/src/test/java/com/google/protobuf/DiscardUnknownFieldsTest.java
48 issues
JUnit tests should include assert() or fail()
Design

Line: 45

              @RunWith(JUnit4.class)
public class DiscardUnknownFieldsTest {
  @Test
  public void testProto2() throws Exception {
    testProto2Message(UnittestProto.TestEmptyMessage.getDefaultInstance());
    testProto2Message(UnittestProto.TestEmptyMessageWithExtensions.getDefaultInstance());
    testProto2Message(
        DynamicMessage.getDefaultInstance(UnittestProto.TestEmptyMessage.getDescriptor()));
    testProto2Message(

            

Reported by PMD.

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

Line: 46

              public class DiscardUnknownFieldsTest {
  @Test
  public void testProto2() throws Exception {
    testProto2Message(UnittestProto.TestEmptyMessage.getDefaultInstance());
    testProto2Message(UnittestProto.TestEmptyMessageWithExtensions.getDefaultInstance());
    testProto2Message(
        DynamicMessage.getDefaultInstance(UnittestProto.TestEmptyMessage.getDescriptor()));
    testProto2Message(
        DynamicMessage.getDefaultInstance(

            

Reported by PMD.

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

Line: 47

                @Test
  public void testProto2() throws Exception {
    testProto2Message(UnittestProto.TestEmptyMessage.getDefaultInstance());
    testProto2Message(UnittestProto.TestEmptyMessageWithExtensions.getDefaultInstance());
    testProto2Message(
        DynamicMessage.getDefaultInstance(UnittestProto.TestEmptyMessage.getDescriptor()));
    testProto2Message(
        DynamicMessage.getDefaultInstance(
            UnittestProto.TestEmptyMessageWithExtensions.getDescriptor()));

            

Reported by PMD.

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

Line: 49

                  testProto2Message(UnittestProto.TestEmptyMessage.getDefaultInstance());
    testProto2Message(UnittestProto.TestEmptyMessageWithExtensions.getDefaultInstance());
    testProto2Message(
        DynamicMessage.getDefaultInstance(UnittestProto.TestEmptyMessage.getDescriptor()));
    testProto2Message(
        DynamicMessage.getDefaultInstance(
            UnittestProto.TestEmptyMessageWithExtensions.getDescriptor()));
  }


            

Reported by PMD.

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

Line: 52

                      DynamicMessage.getDefaultInstance(UnittestProto.TestEmptyMessage.getDescriptor()));
    testProto2Message(
        DynamicMessage.getDefaultInstance(
            UnittestProto.TestEmptyMessageWithExtensions.getDescriptor()));
  }

  @Test
  public void testProto3() throws Exception {
    testProto3Message(UnittestProto3.TestEmptyMessage.getDefaultInstance());

            

Reported by PMD.

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

Line: 56

                }

  @Test
  public void testProto3() throws Exception {
    testProto3Message(UnittestProto3.TestEmptyMessage.getDefaultInstance());
    testProto3Message(
        DynamicMessage.getDefaultInstance(UnittestProto3.TestEmptyMessage.getDescriptor()));
  }


            

Reported by PMD.

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

Line: 57

              
  @Test
  public void testProto3() throws Exception {
    testProto3Message(UnittestProto3.TestEmptyMessage.getDefaultInstance());
    testProto3Message(
        DynamicMessage.getDefaultInstance(UnittestProto3.TestEmptyMessage.getDescriptor()));
  }

  private static void testProto2Message(Message message) throws Exception {

            

Reported by PMD.

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

Line: 59

                public void testProto3() throws Exception {
    testProto3Message(UnittestProto3.TestEmptyMessage.getDefaultInstance());
    testProto3Message(
        DynamicMessage.getDefaultInstance(UnittestProto3.TestEmptyMessage.getDescriptor()));
  }

  private static void testProto2Message(Message message) throws Exception {
    assertUnknownFieldsPreserved(message);
    assertUnknownFieldsExplicitlyDiscarded(message);

            

Reported by PMD.

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

Line: 62

                      DynamicMessage.getDefaultInstance(UnittestProto3.TestEmptyMessage.getDescriptor()));
  }

  private static void testProto2Message(Message message) throws Exception {
    assertUnknownFieldsPreserved(message);
    assertUnknownFieldsExplicitlyDiscarded(message);
    assertReuseCodedInputStreamPreserve(message);
    assertUnknownFieldsInUnknownFieldSetArePreserve(message);
  }

            

Reported by PMD.

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

Line: 69

                  assertUnknownFieldsInUnknownFieldSetArePreserve(message);
  }

  private static void testProto3Message(Message message) throws Exception {
    assertUnknownFieldsPreserved(message);
    assertUnknownFieldsExplicitlyDiscarded(message);
    assertReuseCodedInputStreamPreserve(message);
    assertUnknownFieldsInUnknownFieldSetArePreserve(message);
  }

            

Reported by PMD.

java/core/src/main/java/com/google/protobuf/ByteString.java
47 issues
Avoid throwing null pointer exceptions.
Design

Line: 1317

                   */
    LiteralByteString(byte[] bytes) {
      if (bytes == null) {
        throw new NullPointerException();
      }
      this.bytes = bytes;
    }

    @Override

            

Reported by PMD.

Avoid reassigning parameters such as 'length'
Design

Line: 1026

                  }

    @Override
    public synchronized void write(byte[] b, int offset, int length) {
      if (length <= buffer.length - bufferPos) {
        // The bytes can fit into the current buffer.
        System.arraycopy(b, offset, buffer, bufferPos, length);
        bufferPos += length;
      } else {

            

Reported by PMD.

Avoid reassigning parameters such as 'offset'
Design

Line: 1026

                  }

    @Override
    public synchronized void write(byte[] b, int offset, int length) {
      if (length <= buffer.length - bufferPos) {
        // The bytes can fit into the current buffer.
        System.arraycopy(b, offset, buffer, bufferPos, length);
        bufferPos += length;
      } else {

            

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.protobuf.TextFormatEscaper.escapeBytes;
import static java.lang.Integer.toHexString;
import static java.lang.System.identityHashCode;


            

Reported by PMD.

Possible God Class (WMC=74, ATFD=15, TCC=0.111%)
Design

Line: 76

               * @author carlanton@google.com Carl Haverl
 * @author martinrb@google.com Martin Buchholz
 */
public abstract class ByteString implements Iterable<Byte>, Serializable {

  /**
   * When two strings to be concatenated have a combined length shorter than this, we just copy
   * their bytes on {@link #concat(ByteString)}. The trade-off is copy size versus the overhead of
   * creating tree nodes in {@link RopeByteString}.

            

Reported by PMD.

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

Line: 76

               * @author carlanton@google.com Carl Haverl
 * @author martinrb@google.com Martin Buchholz
 */
public abstract class ByteString implements Iterable<Byte>, Serializable {

  /**
   * When two strings to be concatenated have a combined length shorter than this, we just copy
   * their bytes on {@link #concat(ByteString)}. The trade-off is copy size versus the overhead of
   * creating tree nodes in {@link RopeByteString}.

            

Reported by PMD.

Avoid really long classes.
Design

Line: 76

               * @author carlanton@google.com Carl Haverl
 * @author martinrb@google.com Martin Buchholz
 */
public abstract class ByteString implements Iterable<Byte>, Serializable {

  /**
   * When two strings to be concatenated have a combined length shorter than this, we just copy
   * their bytes on {@link #concat(ByteString)}. The trade-off is copy size versus the overhead of
   * creating tree nodes in {@link RopeByteString}.

            

Reported by PMD.

Classes implementing Serializable should set a serialVersionUID
Error

Line: 76

               * @author carlanton@google.com Carl Haverl
 * @author martinrb@google.com Martin Buchholz
 */
public abstract class ByteString implements Iterable<Byte>, Serializable {

  /**
   * When two strings to be concatenated have a combined length shorter than this, we just copy
   * their bytes on {@link #concat(ByteString)}. The trade-off is copy size versus the overhead of
   * creating tree nodes in {@link RopeByteString}.

            

Reported by PMD.

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

Line: 142

                 * Memory Model's "no out-of-thin-air values" guarantees for ints. A value of 0 implies that the
   * hash has not been set.
   */
  private int hash = 0;

  // This constructor is here to prevent subclassing outside of this package,
  ByteString() {}

  /**

            

Reported by PMD.

Avoid using redundant field initializer for 'hash'
Performance

Line: 142

                 * Memory Model's "no out-of-thin-air values" guarantees for ints. A value of 0 implies that the
   * hash has not been set.
   */
  private int hash = 0;

  // This constructor is here to prevent subclassing outside of this package,
  ByteString() {}

  /**

            

Reported by PMD.

python/docs/generate_docs.py
45 issues
Missing function or method docstring
Error

Line: 131 Column: 1

              """


def find_modules():
  modules = []
  for module_path in SOURCE_DIR.glob("**/*.py"):
    # Determine the (dotted) relative package and module names.
    package_path = module_path.parent.relative_to(PYTHON_DIR)
    if package_path == SOURCE_DIR:

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 132 Column: 1

              

def find_modules():
  modules = []
  for module_path in SOURCE_DIR.glob("**/*.py"):
    # Determine the (dotted) relative package and module names.
    package_path = module_path.parent.relative_to(PYTHON_DIR)
    if package_path == SOURCE_DIR:
      package_name = ""

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 133 Column: 1

              
def find_modules():
  modules = []
  for module_path in SOURCE_DIR.glob("**/*.py"):
    # Determine the (dotted) relative package and module names.
    package_path = module_path.parent.relative_to(PYTHON_DIR)
    if package_path == SOURCE_DIR:
      package_name = ""
      module_name = module_path.stem

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 135 Column: 1

                modules = []
  for module_path in SOURCE_DIR.glob("**/*.py"):
    # Determine the (dotted) relative package and module names.
    package_path = module_path.parent.relative_to(PYTHON_DIR)
    if package_path == SOURCE_DIR:
      package_name = ""
      module_name = module_path.stem
    else:
      package_name = package_path.as_posix().replace("/", ".")

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 136 Column: 1

                for module_path in SOURCE_DIR.glob("**/*.py"):
    # Determine the (dotted) relative package and module names.
    package_path = module_path.parent.relative_to(PYTHON_DIR)
    if package_path == SOURCE_DIR:
      package_name = ""
      module_name = module_path.stem
    else:
      package_name = package_path.as_posix().replace("/", ".")
      module_name = package_name + "." + module_path.stem

            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 137 Column: 1

                  # Determine the (dotted) relative package and module names.
    package_path = module_path.parent.relative_to(PYTHON_DIR)
    if package_path == SOURCE_DIR:
      package_name = ""
      module_name = module_path.stem
    else:
      package_name = package_path.as_posix().replace("/", ".")
      module_name = package_name + "." + module_path.stem


            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 138 Column: 1

                  package_path = module_path.parent.relative_to(PYTHON_DIR)
    if package_path == SOURCE_DIR:
      package_name = ""
      module_name = module_path.stem
    else:
      package_name = package_path.as_posix().replace("/", ".")
      module_name = package_name + "." + module_path.stem

    # Filter: first, accept anything in the whitelist; then, reject anything

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 139 Column: 1

                  if package_path == SOURCE_DIR:
      package_name = ""
      module_name = module_path.stem
    else:
      package_name = package_path.as_posix().replace("/", ".")
      module_name = package_name + "." + module_path.stem

    # Filter: first, accept anything in the whitelist; then, reject anything
    # at package level, then module name level.

            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 140 Column: 1

                    package_name = ""
      module_name = module_path.stem
    else:
      package_name = package_path.as_posix().replace("/", ".")
      module_name = package_name + "." + module_path.stem

    # Filter: first, accept anything in the whitelist; then, reject anything
    # at package level, then module name level.
    if any(include == module_name for include in INCLUDED_MODULES):

            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 141 Column: 1

                    module_name = module_path.stem
    else:
      package_name = package_path.as_posix().replace("/", ".")
      module_name = package_name + "." + module_path.stem

    # Filter: first, accept anything in the whitelist; then, reject anything
    # at package level, then module name level.
    if any(include == module_name for include in INCLUDED_MODULES):
      pass

            

Reported by Pylint.

java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java
45 issues
Logger calls should be surrounded by log level guards.
Design

Line: 286

                  for (Entry<String, Node> entry : node.children.entrySet()) {
      FieldDescriptor field = descriptor.findFieldByName(entry.getKey());
      if (field == null) {
        logger.warning(
            "Cannot find field \""
                + entry.getKey()
                + "\" in message type "
                + descriptor.getFullName());
        continue;

            

Reported by PMD.

Logger calls should be surrounded by log level guards.
Design

Line: 295

                    }
      if (!entry.getValue().children.isEmpty()) {
        if (field.isRepeated() || field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) {
          logger.warning(
              "Field \""
                  + field.getFullName()
                  + "\" is not a "
                  + "singular message field and cannot have sub-fields.");
          continue;

            

Reported by PMD.

The class 'FieldMaskTree' has a Standard Cyclomatic Complexity of 4 (Highest = 16).
Design

Line: 64

               * intersection to two FieldMasks and traverse all fields specified by the
 * FieldMask in a message tree.
 */
final class FieldMaskTree {
  private static final Logger logger = Logger.getLogger(FieldMaskTree.class.getName());

  private static final String FIELD_PATH_SEPARATOR_REGEX = "\\.";

  private static final class Node {

            

Reported by PMD.

Possible God Class (WMC=58, ATFD=53, TCC=18.182%)
Design

Line: 64

               * intersection to two FieldMasks and traverse all fields specified by the
 * FieldMask in a message tree.
 */
final class FieldMaskTree {
  private static final Logger logger = Logger.getLogger(FieldMaskTree.class.getName());

  private static final String FIELD_PATH_SEPARATOR_REGEX = "\\.";

  private static final class Node {

            

Reported by PMD.

The class 'FieldMaskTree' has a Modified Cyclomatic Complexity of 4 (Highest = 16).
Design

Line: 64

               * intersection to two FieldMasks and traverse all fields specified by the
 * FieldMask in a message tree.
 */
final class FieldMaskTree {
  private static final Logger logger = Logger.getLogger(FieldMaskTree.class.getName());

  private static final String FIELD_PATH_SEPARATOR_REGEX = "\\.";

  private static final class Node {

            

Reported by PMD.

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

Line: 70

                private static final String FIELD_PATH_SEPARATOR_REGEX = "\\.";

  private static final class Node {
    final SortedMap<String, Node> children = new TreeMap<>();
  }

  private final Node root = new Node();

  /**

            

Reported by PMD.

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

Line: 73

                  final SortedMap<String, Node> children = new TreeMap<>();
  }

  private final Node root = new Node();

  /**
   * Creates an empty FieldMaskTree.
   */
  FieldMaskTree() {}

            

Reported by PMD.

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

Line: 112

                  // Find the matching node in the tree.
    for (String part : parts) {
      // Check whether the path matches an existing leaf node.
      if (!createNewBranch && node != root && node.children.isEmpty()) {
        // The path to add is a sub-path of an existing leaf node.
        return this;
      }
      if (node.children.containsKey(part)) {
        node = node.children.get(part);

            

Reported by PMD.

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

Line: 116

                      // The path to add is a sub-path of an existing leaf node.
        return this;
      }
      if (node.children.containsKey(part)) {
        node = node.children.get(part);
      } else {
        createNewBranch = true;
        Node tmp = new Node();
        node.children.put(part, tmp);

            

Reported by PMD.

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

Line: 117

                      return this;
      }
      if (node.children.containsKey(part)) {
        node = node.children.get(part);
      } else {
        createNewBranch = true;
        Node tmp = new Node();
        node.children.put(part, tmp);
        node = tmp;

            

Reported by PMD.

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

Line: 52

              public class NestedBuildersTest {

  @Test
  public void testMessagesAndBuilders() {
    Vehicle.Builder vehicleBuilder = Vehicle.newBuilder();
    vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(1);
    vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(2);
    vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(3);
    vehicleBuilder.addWheelBuilder().setRadius(4).setWidth(4);

            

Reported by PMD.

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

Line: 61

                  vehicleBuilder.getEngineBuilder().setLiters(10);

    Vehicle vehicle = vehicleBuilder.build();
    assertThat(vehicle.getWheelCount()).isEqualTo(4);
    for (int i = 0; i < 4; i++) {
      Wheel wheel = vehicle.getWheel(i);
      assertThat(wheel.getRadius()).isEqualTo(4);
      assertThat(wheel.getWidth()).isEqualTo(i + 1);
    }

            

Reported by PMD.

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

Line: 61

                  vehicleBuilder.getEngineBuilder().setLiters(10);

    Vehicle vehicle = vehicleBuilder.build();
    assertThat(vehicle.getWheelCount()).isEqualTo(4);
    for (int i = 0; i < 4; i++) {
      Wheel wheel = vehicle.getWheel(i);
      assertThat(wheel.getRadius()).isEqualTo(4);
      assertThat(wheel.getWidth()).isEqualTo(i + 1);
    }

            

Reported by PMD.

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

Line: 64

                  assertThat(vehicle.getWheelCount()).isEqualTo(4);
    for (int i = 0; i < 4; i++) {
      Wheel wheel = vehicle.getWheel(i);
      assertThat(wheel.getRadius()).isEqualTo(4);
      assertThat(wheel.getWidth()).isEqualTo(i + 1);
    }
    assertThat(vehicle.getEngine().getLiters()).isEqualTo(10);

    for (int i = 0; i < 4; i++) {

            

Reported by PMD.

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

Line: 64

                  assertThat(vehicle.getWheelCount()).isEqualTo(4);
    for (int i = 0; i < 4; i++) {
      Wheel wheel = vehicle.getWheel(i);
      assertThat(wheel.getRadius()).isEqualTo(4);
      assertThat(wheel.getWidth()).isEqualTo(i + 1);
    }
    assertThat(vehicle.getEngine().getLiters()).isEqualTo(10);

    for (int i = 0; i < 4; i++) {

            

Reported by PMD.

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

Line: 65

                  for (int i = 0; i < 4; i++) {
      Wheel wheel = vehicle.getWheel(i);
      assertThat(wheel.getRadius()).isEqualTo(4);
      assertThat(wheel.getWidth()).isEqualTo(i + 1);
    }
    assertThat(vehicle.getEngine().getLiters()).isEqualTo(10);

    for (int i = 0; i < 4; i++) {
      vehicleBuilder.getWheelBuilder(i).setRadius(5).setWidth(i + 10);

            

Reported by PMD.

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

Line: 65

                  for (int i = 0; i < 4; i++) {
      Wheel wheel = vehicle.getWheel(i);
      assertThat(wheel.getRadius()).isEqualTo(4);
      assertThat(wheel.getWidth()).isEqualTo(i + 1);
    }
    assertThat(vehicle.getEngine().getLiters()).isEqualTo(10);

    for (int i = 0; i < 4; i++) {
      vehicleBuilder.getWheelBuilder(i).setRadius(5).setWidth(i + 10);

            

Reported by PMD.

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

Line: 67

                    assertThat(wheel.getRadius()).isEqualTo(4);
      assertThat(wheel.getWidth()).isEqualTo(i + 1);
    }
    assertThat(vehicle.getEngine().getLiters()).isEqualTo(10);

    for (int i = 0; i < 4; i++) {
      vehicleBuilder.getWheelBuilder(i).setRadius(5).setWidth(i + 10);
    }
    Engine.Builder engineBuilder = vehicleBuilder.getEngineBuilder().setLiters(20);

            

Reported by PMD.

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

Line: 67

                    assertThat(wheel.getRadius()).isEqualTo(4);
      assertThat(wheel.getWidth()).isEqualTo(i + 1);
    }
    assertThat(vehicle.getEngine().getLiters()).isEqualTo(10);

    for (int i = 0; i < 4; i++) {
      vehicleBuilder.getWheelBuilder(i).setRadius(5).setWidth(i + 10);
    }
    Engine.Builder engineBuilder = vehicleBuilder.getEngineBuilder().setLiters(20);

            

Reported by PMD.

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

Line: 67

                    assertThat(wheel.getRadius()).isEqualTo(4);
      assertThat(wheel.getWidth()).isEqualTo(i + 1);
    }
    assertThat(vehicle.getEngine().getLiters()).isEqualTo(10);

    for (int i = 0; i < 4; i++) {
      vehicleBuilder.getWheelBuilder(i).setRadius(5).setWidth(i + 10);
    }
    Engine.Builder engineBuilder = vehicleBuilder.getEngineBuilder().setLiters(20);

            

Reported by PMD.

java/core/src/main/java/com/google/protobuf/SchemaUtil.java
45 issues
Avoid throwing raw exception types.
Design

Line: 839

                    }
      return UnsafeUtil.getStaticObject(fields[0]);
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }

  static String toCamelCase(String name, boolean capNext) {
    StringBuilder sb = new StringBuilder();

            

Reported by PMD.

Avoid reassigning parameters such as 'capNext'
Design

Line: 843

                  }
  }

  static String toCamelCase(String name, boolean capNext) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < name.length(); ++i) {
      char c = name.charAt(i);
      // Matches protoc field name function:
      if ('a' <= c && c <= 'z') {

            

Reported by PMD.

Avoid reassigning parameters such as 'capNext'
Design

Line: 843

                  }
  }

  static String toCamelCase(String name, boolean capNext) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < name.length(); ++i) {
      char c = name.charAt(i);
      // Matches protoc field name function:
      if ('a' <= c && c <= 'z') {

            

Reported by PMD.

Avoid reassigning parameters such as 'capNext'
Design

Line: 843

                  }
  }

  static String toCamelCase(String name, boolean capNext) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < name.length(); ++i) {
      char c = name.charAt(i);
      // Matches protoc field name function:
      if ('a' <= c && c <= 'z') {

            

Reported by PMD.

Avoid reassigning parameters such as 'capNext'
Design

Line: 843

                  }
  }

  static String toCamelCase(String name, boolean capNext) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < name.length(); ++i) {
      char c = name.charAt(i);
      // Matches protoc field name function:
      if ('a' <= c && c <= 'z') {

            

Reported by PMD.

Avoid reassigning parameters such as 'unknownFields'
Design

Line: 907

                    int number,
      List<Integer> enumList,
      EnumLiteMap<?> enumMap,
      UB unknownFields,
      UnknownFieldSchema<UT, UB> unknownFieldSchema) {
    if (enumMap == null) {
      return unknownFields;
    }
    // TODO(dweis): Specialize for IntArrayList to avoid boxing.

            

Reported by PMD.

Avoid reassigning parameters such as 'unknownFields'
Design

Line: 907

                    int number,
      List<Integer> enumList,
      EnumLiteMap<?> enumMap,
      UB unknownFields,
      UnknownFieldSchema<UT, UB> unknownFieldSchema) {
    if (enumMap == null) {
      return unknownFields;
    }
    // TODO(dweis): Specialize for IntArrayList to avoid boxing.

            

Reported by PMD.

Avoid reassigning parameters such as 'unknownFields'
Design

Line: 947

                    int number,
      List<Integer> enumList,
      EnumVerifier enumVerifier,
      UB unknownFields,
      UnknownFieldSchema<UT, UB> unknownFieldSchema) {
    if (enumVerifier == null) {
      return unknownFields;
    }
    // TODO(dweis): Specialize for IntArrayList to avoid boxing.

            

Reported by PMD.

Avoid reassigning parameters such as 'unknownFields'
Design

Line: 947

                    int number,
      List<Integer> enumList,
      EnumVerifier enumVerifier,
      UB unknownFields,
      UnknownFieldSchema<UT, UB> unknownFieldSchema) {
    if (enumVerifier == null) {
      return unknownFields;
    }
    // TODO(dweis): Specialize for IntArrayList to avoid boxing.

            

Reported by PMD.

Avoid reassigning parameters such as 'unknownFields'
Design

Line: 984

              
  /** Stores an unrecognized enum value as an unknown value. */
  static <UT, UB> UB storeUnknownEnum(
      int number, int enumValue, UB unknownFields, UnknownFieldSchema<UT, UB> unknownFieldSchema) {
    if (unknownFields == null) {
      unknownFields = unknownFieldSchema.newBuilder();
    }
    unknownFieldSchema.addVarint(unknownFields, number, enumValue);
    return unknownFields;

            

Reported by PMD.