The following issues were found

python/google/protobuf/internal/extension_dict.py
88 issues
TODO(robinson): Unify error handling of "unknown extension" crap.
Error

Line: 60 Column: 3

                                  message.DESCRIPTOR.full_name))


# TODO(robinson): Unify error handling of "unknown extension" crap.
# TODO(robinson): Support iteritems()-style iteration over all
# extensions with the "has" bits turned on?
class _ExtensionDict(object):

  """Dict-like container for Extension fields on proto instances.

            

Reported by Pylint.

TODO(robinson): Support iteritems()-style iteration over all
Error

Line: 61 Column: 3

              

# TODO(robinson): Unify error handling of "unknown extension" crap.
# TODO(robinson): Support iteritems()-style iteration over all
# extensions with the "has" bits turned on?
class _ExtensionDict(object):

  """Dict-like container for Extension fields on proto instances.


            

Reported by Pylint.

Access to a protected member _extensions_by_name of a client class
Error

Line: 181 Column: 12

                  Returns:
      Extension field descriptor.
    """
    return self._extended_message._extensions_by_name.get(name, None)

  def _FindExtensionByNumber(self, number):
    """Tries to find a known extension with the field number.

    Args:

            

Reported by Pylint.

Access to a protected member _extensions_by_number of a client class
Error

Line: 192 Column: 12

                  Returns:
      Extension field descriptor.
    """
    return self._extended_message._extensions_by_number.get(number, None)

  def __iter__(self):
    # Return a generator over the populated extension fields
    return (f[0] for f in self._extended_message.ListFields()
            if f[0].is_extension)

            

Reported by Pylint.

Function name "_VerifyExtensionHandle" doesn't conform to snake_case naming style
Error

Line: 38 Column: 1

              from google.protobuf.descriptor import FieldDescriptor


def _VerifyExtensionHandle(message, extension_handle):
  """Verify that the given extension handle is valid."""

  if not isinstance(extension_handle, FieldDescriptor):
    raise KeyError('HasExtension() expects an extension handle, got: %s' %
                   extension_handle)

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 39 Column: 1

              

def _VerifyExtensionHandle(message, extension_handle):
  """Verify that the given extension handle is valid."""

  if not isinstance(extension_handle, FieldDescriptor):
    raise KeyError('HasExtension() expects an extension handle, got: %s' %
                   extension_handle)


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 41 Column: 1

              def _VerifyExtensionHandle(message, extension_handle):
  """Verify that the given extension handle is valid."""

  if not isinstance(extension_handle, FieldDescriptor):
    raise KeyError('HasExtension() expects an extension handle, got: %s' %
                   extension_handle)

  if not extension_handle.is_extension:
    raise KeyError('"%s" is not an extension.' % extension_handle.full_name)

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 42 Column: 1

                """Verify that the given extension handle is valid."""

  if not isinstance(extension_handle, FieldDescriptor):
    raise KeyError('HasExtension() expects an extension handle, got: %s' %
                   extension_handle)

  if not extension_handle.is_extension:
    raise KeyError('"%s" is not an extension.' % extension_handle.full_name)


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 45 Column: 1

                  raise KeyError('HasExtension() expects an extension handle, got: %s' %
                   extension_handle)

  if not extension_handle.is_extension:
    raise KeyError('"%s" is not an extension.' % extension_handle.full_name)

  if not extension_handle.containing_type:
    raise KeyError('"%s" is missing a containing_type.'
                   % extension_handle.full_name)

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 46 Column: 1

                                 extension_handle)

  if not extension_handle.is_extension:
    raise KeyError('"%s" is not an extension.' % extension_handle.full_name)

  if not extension_handle.containing_type:
    raise KeyError('"%s" is missing a containing_type.'
                   % extension_handle.full_name)


            

Reported by Pylint.

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

Line: 161

                    writeTo(out.getCodedOutput());
      return out.build();
    } catch (final IOException e) {
      throw new RuntimeException(
          "Serializing to a ByteString threw an IOException (should never happen).", e);
    }
  }

  /**

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 179

                    output.checkNoSpaceLeft();
      return result;
    } catch (final IOException e) {
      throw new RuntimeException(
          "Serializing to a byte array threw an IOException (should never happen).", e);
    }
  }

  /**

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 575

                    } catch (final InvalidProtocolBufferException e) {
        throw e;
      } catch (final IOException e) {
        throw new RuntimeException(
            "Reading from a ByteString threw an IOException (should never happen).", e);
      }
    }

    /**

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 594

                    } catch (final InvalidProtocolBufferException e) {
        throw e;
      } catch (final IOException e) {
        throw new RuntimeException(
            "Reading from a byte array threw an IOException (should never happen).", e);
      }
    }

    /**

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 654

                    } catch (InvalidProtocolBufferException e) {
        throw e;
      } catch (IOException e) {
        throw new RuntimeException(
            "Reading from a byte array threw an IOException (should never happen).", e);
      }
    }

    @Override

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 793

                      writeTo(fieldNumber, out.getCodedOutput());
        return out.build();
      } catch (IOException e) {
        throw new RuntimeException(
            "Serializing to a ByteString should never fail with an IOException", e);
      }
    }

    /** Serializes the field, including field number, and writes it to {@code output}. */

            

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.AbstractMessageLite.Builder.LimitedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

            

Reported by PMD.

Avoid really long classes.
Design

Line: 58

               *
 * @author kenton@google.com Kenton Varda
 */
public final class UnknownFieldSet implements MessageLite {

  private UnknownFieldSet() {
    fields = null;
    fieldsDescending = null;
  }

            

Reported by PMD.

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

Line: 58

               *
 * @author kenton@google.com Kenton Varda
 */
public final class UnknownFieldSet implements MessageLite {

  private UnknownFieldSet() {
    fields = null;
    fieldsDescending = null;
  }

            

Reported by PMD.

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

Line: 97

                  this.fieldsDescending = fieldsDescending;
  }

  private final Map<Integer, Field> fields;

  /** A copy of {@link #fields} who's iterator order is reversed. */
  private final Map<Integer, Field> fieldsDescending;



            

Reported by PMD.

java/core/src/main/java/com/google/protobuf/ExtensionSchemaLite.java
84 issues
Avoid reassigning parameters such as 'extensions'
Design

Line: 54

                }

  @Override
  void setExtensions(Object message, FieldSet<ExtensionDescriptor> extensions) {
    ((GeneratedMessageLite.ExtendableMessage<?, ?>) message).extensions = extensions;
  }

  @Override
  FieldSet<ExtensionDescriptor> getMutableExtensions(Object message) {

            

Reported by PMD.

Avoid reassigning parameters such as 'unknownFields'
Design

Line: 74

                    Object extensionObject,
      ExtensionRegistryLite extensionRegistry,
      FieldSet<ExtensionDescriptor> extensions,
      UB unknownFields,
      UnknownFieldSchema<UT, UB> unknownFieldSchema)
      throws IOException {
    GeneratedMessageLite.GeneratedExtension<?, ?> extension =
        (GeneratedMessageLite.GeneratedExtension<?, ?>) extensionObject;
    int fieldNumber = extension.getNumber();

            

Reported by PMD.

Possible God Class (WMC=96, ATFD=136, TCC=0.000%)
Design

Line: 41

              import java.util.Map;

@SuppressWarnings("unchecked")
final class ExtensionSchemaLite extends ExtensionSchema<ExtensionDescriptor> {

  @Override
  boolean hasExtensions(MessageLite prototype) {
    return prototype instanceof GeneratedMessageLite.ExtendableMessage;
  }

            

Reported by PMD.

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

Line: 41

              import java.util.Map;

@SuppressWarnings("unchecked")
final class ExtensionSchemaLite extends ExtensionSchema<ExtensionDescriptor> {

  @Override
  boolean hasExtensions(MessageLite prototype) {
    return prototype instanceof GeneratedMessageLite.ExtendableMessage;
  }

            

Reported by PMD.

The class 'ExtensionSchemaLite' has a total cyclomatic complexity of 96 (highest 43).
Design

Line: 41

              import java.util.Map;

@SuppressWarnings("unchecked")
final class ExtensionSchemaLite extends ExtensionSchema<ExtensionDescriptor> {

  @Override
  boolean hasExtensions(MessageLite prototype) {
    return prototype instanceof GeneratedMessageLite.ExtendableMessage;
  }

            

Reported by PMD.

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

Line: 65

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

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

            

Reported by PMD.

Avoid really long methods.
Design

Line: 69

                }

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

            

Reported by PMD.

The method 'parseExtension' has a Standard Cyclomatic Complexity of 39.
Design

Line: 69

                }

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

            

Reported by PMD.

The method 'parseExtension(Reader, Object, ExtensionRegistryLite, FieldSet, UB, UnknownFieldSchema)' has a NCSS line count of 157.
Design

Line: 69

                }

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

            

Reported by PMD.

The method 'parseExtension(Reader, Object, ExtensionRegistryLite, FieldSet, UB, UnknownFieldSchema)' has a cyclomatic complexity of 43.
Design

Line: 69

                }

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

            

Reported by PMD.

java/core/src/test/java/com/google/protobuf/DecodeUtf8Test.java
83 issues
The Logger variable declaration does not contain the static and final modifiers
Error

Line: 13

              import junit.framework.TestCase;

public class DecodeUtf8Test extends TestCase {
  private static Logger logger = Logger.getLogger(DecodeUtf8Test.class.getName());

  private static final Processor SAFE_PROCESSOR = new SafeProcessor();
  private static final Processor UNSAFE_PROCESSOR = new UnsafeProcessor();

  public void testRoundTripAllValidChars() throws Exception {

            

Reported by PMD.

Logger calls should be surrounded by log level guards.
Design

Line: 74

                          }
            count++;
            if (count % 1000000L == 0) {
              logger.info("Processed " + (count / 1000000L) + " million characters");
            }
          }
        }
      }
      assertEquals(IsValidUtf8TestUtil.EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT, valid);

            

Reported by PMD.

Avoid reassigning parameters such as 'size'
Design

Line: 284

                  assertRoundTrips(str, 0, -1);
  }

  private void assertRoundTrips(String str, int index, int size) throws Exception {
    byte[] bytes = str.getBytes(Internal.UTF_8);
    if (size == -1) {
      size = bytes.length;
    }
    assertDecode(new String(bytes, index, size, Internal.UTF_8),

            

Reported by PMD.

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

Line: 12

              import java.util.logging.Logger;
import junit.framework.TestCase;

public class DecodeUtf8Test extends TestCase {
  private static Logger logger = Logger.getLogger(DecodeUtf8Test.class.getName());

  private static final Processor SAFE_PROCESSOR = new SafeProcessor();
  private static final Processor UNSAFE_PROCESSOR = new UnsafeProcessor();


            

Reported by PMD.

Possible God Class (WMC=47, ATFD=52, TCC=2.206%)
Design

Line: 12

              import java.util.logging.Logger;
import junit.framework.TestCase;

public class DecodeUtf8Test extends TestCase {
  private static Logger logger = Logger.getLogger(DecodeUtf8Test.class.getName());

  private static final Processor SAFE_PROCESSOR = new SafeProcessor();
  private static final Processor UNSAFE_PROCESSOR = new UnsafeProcessor();


            

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

                private static final Processor SAFE_PROCESSOR = new SafeProcessor();
  private static final Processor UNSAFE_PROCESSOR = new UnsafeProcessor();

  public void testRoundTripAllValidChars() throws Exception {
    for (int i = Character.MIN_CODE_POINT; i < Character.MAX_CODE_POINT; i++) {
      if (i < Character.MIN_SURROGATE || i > Character.MAX_SURROGATE) {
        String str = new String(Character.toChars(i));
        assertRoundTrips(str);
      }

            

Reported by PMD.

Avoid instantiating new objects inside loops
Performance

Line: 21

                public void testRoundTripAllValidChars() throws Exception {
    for (int i = Character.MIN_CODE_POINT; i < Character.MAX_CODE_POINT; i++) {
      if (i < Character.MIN_SURROGATE || i > Character.MAX_SURROGATE) {
        String str = new String(Character.toChars(i));
        assertRoundTrips(str);
      }
    }
  }


            

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

              
  // Test all 1, 2, 3 invalid byte combinations. Valid ones would have been covered above.

  public void testOneByte() throws Exception {
    int valid = 0;
    for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
      ByteString bs = ByteString.copyFrom(new byte[] { (byte) i });
      if (!bs.isValidUtf8()) {
        assertInvalid(bs.toByteArray());

            

Reported by PMD.

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

Line: 29

              
  // Test all 1, 2, 3 invalid byte combinations. Valid ones would have been covered above.

  public void testOneByte() throws Exception {
    int valid = 0;
    for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
      ByteString bs = ByteString.copyFrom(new byte[] { (byte) i });
      if (!bs.isValidUtf8()) {
        assertInvalid(bs.toByteArray());

            

Reported by PMD.

Avoid instantiating new objects inside loops
Performance

Line: 32

                public void testOneByte() throws Exception {
    int valid = 0;
    for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
      ByteString bs = ByteString.copyFrom(new byte[] { (byte) i });
      if (!bs.isValidUtf8()) {
        assertInvalid(bs.toByteArray());
      } else {
        valid++;
      }

            

Reported by PMD.

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

Line: 45

              
/** Unit test for {@link LazyFieldLite}. */
@RunWith(JUnit4.class)
public class LazyFieldLiteTest {

  @Test
  public void testGetValue() {
    MessageLite message = TestUtil.getAllSet();
    LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message);

            

Reported by PMD.

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

Line: 48

              public class LazyFieldLiteTest {

  @Test
  public void testGetValue() {
    MessageLite message = TestUtil.getAllSet();
    LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message);
    assertThat(message).isEqualTo(lazyField.getValue(TestAllTypes.getDefaultInstance()));
    changeValue(lazyField);
    assertNotEqual(message, lazyField.getValue(TestAllTypes.getDefaultInstance()));

            

Reported by PMD.

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

Line: 51

                public void testGetValue() {
    MessageLite message = TestUtil.getAllSet();
    LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message);
    assertThat(message).isEqualTo(lazyField.getValue(TestAllTypes.getDefaultInstance()));
    changeValue(lazyField);
    assertNotEqual(message, lazyField.getValue(TestAllTypes.getDefaultInstance()));
  }

  @Test

            

Reported by PMD.

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

Line: 51

                public void testGetValue() {
    MessageLite message = TestUtil.getAllSet();
    LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message);
    assertThat(message).isEqualTo(lazyField.getValue(TestAllTypes.getDefaultInstance()));
    changeValue(lazyField);
    assertNotEqual(message, lazyField.getValue(TestAllTypes.getDefaultInstance()));
  }

  @Test

            

Reported by PMD.

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

Line: 53

                  LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message);
    assertThat(message).isEqualTo(lazyField.getValue(TestAllTypes.getDefaultInstance()));
    changeValue(lazyField);
    assertNotEqual(message, lazyField.getValue(TestAllTypes.getDefaultInstance()));
  }

  @Test
  public void testGetValueEx() throws Exception {
    TestAllExtensions message = TestUtil.getAllExtensionsSet();

            

Reported by PMD.

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

Line: 57

                }

  @Test
  public void testGetValueEx() throws Exception {
    TestAllExtensions message = TestUtil.getAllExtensionsSet();
    LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message);
    assertThat(message).isEqualTo(lazyField.getValue(TestAllExtensions.getDefaultInstance()));
    changeValue(lazyField);
    assertNotEqual(message, lazyField.getValue(TestAllExtensions.getDefaultInstance()));

            

Reported by PMD.

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

Line: 60

                public void testGetValueEx() throws Exception {
    TestAllExtensions message = TestUtil.getAllExtensionsSet();
    LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message);
    assertThat(message).isEqualTo(lazyField.getValue(TestAllExtensions.getDefaultInstance()));
    changeValue(lazyField);
    assertNotEqual(message, lazyField.getValue(TestAllExtensions.getDefaultInstance()));
  }

  @Test

            

Reported by PMD.

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

Line: 60

                public void testGetValueEx() throws Exception {
    TestAllExtensions message = TestUtil.getAllExtensionsSet();
    LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message);
    assertThat(message).isEqualTo(lazyField.getValue(TestAllExtensions.getDefaultInstance()));
    changeValue(lazyField);
    assertNotEqual(message, lazyField.getValue(TestAllExtensions.getDefaultInstance()));
  }

  @Test

            

Reported by PMD.

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

Line: 62

                  LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message);
    assertThat(message).isEqualTo(lazyField.getValue(TestAllExtensions.getDefaultInstance()));
    changeValue(lazyField);
    assertNotEqual(message, lazyField.getValue(TestAllExtensions.getDefaultInstance()));
  }

  @Test
  public void testSetValue() {
    MessageLite message = TestUtil.getAllSet();

            

Reported by PMD.

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

Line: 66

                }

  @Test
  public void testSetValue() {
    MessageLite message = TestUtil.getAllSet();
    LazyFieldLite lazyField = createLazyFieldLiteFromMessage(message);
    changeValue(lazyField);
    assertNotEqual(message, lazyField.getValue(TestAllTypes.getDefaultInstance()));
    message = lazyField.getValue(TestAllTypes.getDefaultInstance());

            

Reported by PMD.

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

Line: 56

              
/** Unit test for {@link Parser}. */
@RunWith(JUnit4.class)
public class ParserTest {

  @Test
  public void testGeneratedMessageParserSingleton() throws Exception {
    for (int i = 0; i < 10; i++) {
      assertThat(TestUtil.getAllSet().getParserForType()).isEqualTo(TestAllTypes.parser());

            

Reported by PMD.

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

Line: 61

                @Test
  public void testGeneratedMessageParserSingleton() throws Exception {
    for (int i = 0; i < 10; i++) {
      assertThat(TestUtil.getAllSet().getParserForType()).isEqualTo(TestAllTypes.parser());
    }
  }

  private void assertRoundTripEquals(MessageLite message, ExtensionRegistryLite registry)
      throws Exception {

            

Reported by PMD.

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

Line: 61

                @Test
  public void testGeneratedMessageParserSingleton() throws Exception {
    for (int i = 0; i < 10; i++) {
      assertThat(TestUtil.getAllSet().getParserForType()).isEqualTo(TestAllTypes.parser());
    }
  }

  private void assertRoundTripEquals(MessageLite message, ExtensionRegistryLite registry)
      throws Exception {

            

Reported by PMD.

A method/constructor should not explicitly throw java.lang.Exception
Design

Line: 66

                }

  private void assertRoundTripEquals(MessageLite message, ExtensionRegistryLite registry)
      throws Exception {
    final byte[] data = message.toByteArray();
    final int offset = 20;
    final int length = data.length;
    final int padding = 30;
    Parser<? extends MessageLite> parser = message.getParserForType();

            

Reported by PMD.

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

Line: 72

                  final int length = data.length;
    final int padding = 30;
    Parser<? extends MessageLite> parser = message.getParserForType();
    assertMessageEquals(message, parser.parseFrom(data, registry));
    assertMessageEquals(
        message,
        parser.parseFrom(generatePaddingArray(data, offset, padding), offset, length, registry));
    assertMessageEquals(message, parser.parseFrom(message.toByteString(), registry));
    assertMessageEquals(message, parser.parseFrom(new ByteArrayInputStream(data), registry));

            

Reported by PMD.

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

Line: 75

                  assertMessageEquals(message, parser.parseFrom(data, registry));
    assertMessageEquals(
        message,
        parser.parseFrom(generatePaddingArray(data, offset, padding), offset, length, registry));
    assertMessageEquals(message, parser.parseFrom(message.toByteString(), registry));
    assertMessageEquals(message, parser.parseFrom(new ByteArrayInputStream(data), registry));
    assertMessageEquals(message, parser.parseFrom(CodedInputStream.newInstance(data), registry));
    assertMessageEquals(
        message, parser.parseFrom(message.toByteString().asReadOnlyByteBuffer(), registry));

            

Reported by PMD.

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

Line: 76

                  assertMessageEquals(
        message,
        parser.parseFrom(generatePaddingArray(data, offset, padding), offset, length, registry));
    assertMessageEquals(message, parser.parseFrom(message.toByteString(), registry));
    assertMessageEquals(message, parser.parseFrom(new ByteArrayInputStream(data), registry));
    assertMessageEquals(message, parser.parseFrom(CodedInputStream.newInstance(data), registry));
    assertMessageEquals(
        message, parser.parseFrom(message.toByteString().asReadOnlyByteBuffer(), registry));
  }

            

Reported by PMD.

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

Line: 78

                      parser.parseFrom(generatePaddingArray(data, offset, padding), offset, length, registry));
    assertMessageEquals(message, parser.parseFrom(message.toByteString(), registry));
    assertMessageEquals(message, parser.parseFrom(new ByteArrayInputStream(data), registry));
    assertMessageEquals(message, parser.parseFrom(CodedInputStream.newInstance(data), registry));
    assertMessageEquals(
        message, parser.parseFrom(message.toByteString().asReadOnlyByteBuffer(), registry));
  }

  @SuppressWarnings("unchecked")

            

Reported by PMD.

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

Line: 80

                  assertMessageEquals(message, parser.parseFrom(new ByteArrayInputStream(data), registry));
    assertMessageEquals(message, parser.parseFrom(CodedInputStream.newInstance(data), registry));
    assertMessageEquals(
        message, parser.parseFrom(message.toByteString().asReadOnlyByteBuffer(), registry));
  }

  @SuppressWarnings("unchecked")
  private void assertRoundTripEquals(MessageLite message) throws Exception {
    final byte[] data = message.toByteArray();

            

Reported by PMD.

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

Line: 80

                  assertMessageEquals(message, parser.parseFrom(new ByteArrayInputStream(data), registry));
    assertMessageEquals(message, parser.parseFrom(CodedInputStream.newInstance(data), registry));
    assertMessageEquals(
        message, parser.parseFrom(message.toByteString().asReadOnlyByteBuffer(), registry));
  }

  @SuppressWarnings("unchecked")
  private void assertRoundTripEquals(MessageLite message) throws Exception {
    final byte[] data = message.toByteArray();

            

Reported by PMD.

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

Line: 1158

              
    ArrayEncoder(byte[] buffer, int offset, int length) {
      if (buffer == null) {
        throw new NullPointerException("buffer");
      }
      if ((offset | length | (buffer.length - (offset + length))) < 0) {
        throw new IllegalArgumentException(
            String.format(
                "Array range is invalid. Buffer.length=%d, offset=%d, length=%d",

            

Reported by PMD.

Avoid throwing null pointer exceptions.
Design

Line: 2129

                        || (value.length - length) < offset
          || (limit - length) < position) {
        if (value == null) {
          throw new NullPointerException("value");
        }
        throw new OutOfSpaceException(
            String.format("Pos: %d, limit: %d, len: %d", position, limit, length));
      }


            

Reported by PMD.

Avoid throwing null pointer exceptions.
Design

Line: 2400

                  ByteOutputEncoder(ByteOutput out, int bufferSize) {
      super(bufferSize);
      if (out == null) {
        throw new NullPointerException("out");
      }
      this.out = out;
    }

    @Override

            

Reported by PMD.

Avoid throwing null pointer exceptions.
Design

Line: 2714

                  OutputStreamEncoder(OutputStream out, int bufferSize) {
      super(bufferSize);
      if (out == null) {
        throw new NullPointerException("out");
      }
      this.out = out;
    }

    @Override

            

Reported by PMD.

Avoid reassigning parameters such as 'value'
Design

Line: 770

                 * Compute the number of bytes that would be needed to encode a {@code uint64} field, including
   * tag.
   */
  public static int computeUInt64SizeNoTag(long value) {
    // handle two popular special cases up front ...
    if ((value & (~0L << 7)) == 0L) {
      return 1;
    }
    if (value < 0L) {

            

Reported by PMD.

Avoid reassigning parameters such as 'value'
Design

Line: 770

                 * Compute the number of bytes that would be needed to encode a {@code uint64} field, including
   * tag.
   */
  public static int computeUInt64SizeNoTag(long value) {
    // handle two popular special cases up front ...
    if ((value & (~0L << 7)) == 0L) {
      return 1;
    }
    if (value < 0L) {

            

Reported by PMD.

Avoid reassigning parameters such as 'value'
Design

Line: 1336

                  }

    @Override
    public final void writeUInt32NoTag(int value) throws IOException {
      if (HAS_UNSAFE_ARRAY_OPERATIONS
          && !Android.isOnAndroidDevice()
          && spaceLeft() >= MAX_VARINT32_SIZE) {
        if ((value & ~0x7F) == 0) {
          UnsafeUtil.putByte(buffer, position++, (byte) value);

            

Reported by PMD.

Avoid reassigning parameters such as 'value'
Design

Line: 1336

                  }

    @Override
    public final void writeUInt32NoTag(int value) throws IOException {
      if (HAS_UNSAFE_ARRAY_OPERATIONS
          && !Android.isOnAndroidDevice()
          && spaceLeft() >= MAX_VARINT32_SIZE) {
        if ((value & ~0x7F) == 0) {
          UnsafeUtil.putByte(buffer, position++, (byte) value);

            

Reported by PMD.

Avoid reassigning parameters such as 'value'
Design

Line: 1336

                  }

    @Override
    public final void writeUInt32NoTag(int value) throws IOException {
      if (HAS_UNSAFE_ARRAY_OPERATIONS
          && !Android.isOnAndroidDevice()
          && spaceLeft() >= MAX_VARINT32_SIZE) {
        if ((value & ~0x7F) == 0) {
          UnsafeUtil.putByte(buffer, position++, (byte) value);

            

Reported by PMD.

Avoid reassigning parameters such as 'value'
Design

Line: 1336

                  }

    @Override
    public final void writeUInt32NoTag(int value) throws IOException {
      if (HAS_UNSAFE_ARRAY_OPERATIONS
          && !Android.isOnAndroidDevice()
          && spaceLeft() >= MAX_VARINT32_SIZE) {
        if ((value & ~0x7F) == 0) {
          UnsafeUtil.putByte(buffer, position++, (byte) value);

            

Reported by PMD.

java/core/src/test/java/com/google/protobuf/ExtensionRegistryFactoryTest.java
79 issues
Avoid throwing raw exception types.
Design

Line: 261

                  try {
      classes = ClassPath.from(ExtensionRegistryFactoryTest.class.getClassLoader()).getAllClasses();
    } catch (IOException ex) {
      throw new RuntimeException(ex);
    }
    URL[] urls = new URL[classes.size()];
    int i = 0;
    for (ClassPath.ClassInfo classInfo : classes) {
      urls[i++] = classInfo.url();

            

Reported by PMD.

This class name ends with Test but contains no test cases
Error

Line: 65

               */
@SuppressWarnings("JUnit4ClassUsedInJUnit3")
@Ignore
public class ExtensionRegistryFactoryTest extends TestCase {

  // A classloader which blacklists some non-Lite classes.
  private static final ClassLoader LITE_CLASS_LOADER = getLiteOnlyClassLoader();

  /** Defines the set of test methods which will be run. */

            

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

              
  /** Defines the set of test methods which will be run. */
  static interface RegistryTests {
    void testCreate();

    void testEmpty();

    void testIsFullRegistry();


            

Reported by PMD.

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

Line: 74

                static interface RegistryTests {
    void testCreate();

    void testEmpty();

    void testIsFullRegistry();

    void testAdd();


            

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

              
    void testEmpty();

    void testIsFullRegistry();

    void testAdd();

    void testAdd_immutable();
  }

            

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

              
    void testIsFullRegistry();

    void testAdd();

    void testAdd_immutable();
  }

  /** Test implementations for the non-Lite usage of ExtensionRegistryFactory. */

            

Reported by PMD.

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

Line: 80

              
    void testAdd();

    void testAdd_immutable();
  }

  /** Test implementations for the non-Lite usage of ExtensionRegistryFactory. */
  public static class InnerTest implements RegistryTests {


            

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

                /** Test implementations for the non-Lite usage of ExtensionRegistryFactory. */
  public static class InnerTest implements RegistryTests {

    @Override
    public void testCreate() {
      ExtensionRegistryLite registry = ExtensionRegistryFactory.create();

      assertThat(registry.getClass()).isEqualTo(ExtensionRegistry.class);
    }

            

Reported by PMD.

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

Line: 90

                  public void testCreate() {
      ExtensionRegistryLite registry = ExtensionRegistryFactory.create();

      assertThat(registry.getClass()).isEqualTo(ExtensionRegistry.class);
    }

    @Override
    public void testEmpty() {
      ExtensionRegistryLite emptyRegistry = ExtensionRegistryFactory.createEmpty();

            

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

                    assertThat(registry.getClass()).isEqualTo(ExtensionRegistry.class);
    }

    @Override
    public void testEmpty() {
      ExtensionRegistryLite emptyRegistry = ExtensionRegistryFactory.createEmpty();

      assertThat(emptyRegistry.getClass()).isEqualTo(ExtensionRegistry.class);
      assertThat(emptyRegistry).isEqualTo(ExtensionRegistry.EMPTY_REGISTRY);

            

Reported by PMD.

ruby/src/main/java/com/google/protobuf/jruby/RubyFileBuilderContext.java
77 issues
The class 'RubyFileBuilderContext' has a Modified Cyclomatic Complexity of 4 (Highest = 19).
Design

Line: 58

              import java.util.TreeMap;

@JRubyClass(name = "FileBuilderContext")
public class RubyFileBuilderContext extends RubyObject {
    public static void createRubyFileBuilderContext(Ruby runtime) {
        RubyModule internal = runtime.getClassFromPath("Google::Protobuf::Internal");
        RubyClass cFileBuilderContext = internal.defineClassUnder("FileBuilderContext", runtime.getObject(), new ObjectAllocator() {
            @Override
            public IRubyObject allocate(Ruby runtime, RubyClass klazz) {

            

Reported by PMD.

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

Line: 58

              import java.util.TreeMap;

@JRubyClass(name = "FileBuilderContext")
public class RubyFileBuilderContext extends RubyObject {
    public static void createRubyFileBuilderContext(Ruby runtime) {
        RubyModule internal = runtime.getClassFromPath("Google::Protobuf::Internal");
        RubyClass cFileBuilderContext = internal.defineClassUnder("FileBuilderContext", runtime.getObject(), new ObjectAllocator() {
            @Override
            public IRubyObject allocate(Ruby runtime, RubyClass klazz) {

            

Reported by PMD.

Avoid using Literals in Conditional Statements
Error

Line: 94

                      this.builder.setName(args[1].asJavaString());
        this.builder.setSyntax("proto3");

        if (args.length > 2) {
            RubyHash options = (RubyHash) args[2];
            IRubyObject syntax = options.fastARef(context.runtime.newSymbol("syntax"));

            if (syntax != null) {
                String syntaxStr = syntax.asJavaString();

            

Reported by PMD.

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

Line: 96

              
        if (args.length > 2) {
            RubyHash options = (RubyHash) args[2];
            IRubyObject syntax = options.fastARef(context.runtime.newSymbol("syntax"));

            if (syntax != null) {
                String syntaxStr = syntax.asJavaString();
                this.builder.setSyntax(syntaxStr);
                this.proto3 = syntaxStr.equals("proto3");

            

Reported by PMD.

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

Line: 96

              
        if (args.length > 2) {
            RubyHash options = (RubyHash) args[2];
            IRubyObject syntax = options.fastARef(context.runtime.newSymbol("syntax"));

            if (syntax != null) {
                String syntaxStr = syntax.asJavaString();
                this.builder.setSyntax(syntaxStr);
                this.proto3 = syntaxStr.equals("proto3");

            

Reported by PMD.

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

Line: 99

                          IRubyObject syntax = options.fastARef(context.runtime.newSymbol("syntax"));

            if (syntax != null) {
                String syntaxStr = syntax.asJavaString();
                this.builder.setSyntax(syntaxStr);
                this.proto3 = syntaxStr.equals("proto3");
            }
        }


            

Reported by PMD.

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

Line: 101

                          if (syntax != null) {
                String syntaxStr = syntax.asJavaString();
                this.builder.setSyntax(syntaxStr);
                this.proto3 = syntaxStr.equals("proto3");
            }
        }

        return this;
    }

            

Reported by PMD.

Position literals first in String comparisons
Design

Line: 101

                          if (syntax != null) {
                String syntaxStr = syntax.asJavaString();
                this.builder.setSyntax(syntaxStr);
                this.proto3 = syntaxStr.equals("proto3");
            }
        }

        return this;
    }

            

Reported by PMD.

Position literals first in String comparisons
Design

Line: 101

                          if (syntax != null) {
                String syntaxStr = syntax.asJavaString();
                this.builder.setSyntax(syntaxStr);
                this.proto3 = syntaxStr.equals("proto3");
            }
        }

        return this;
    }

            

Reported by PMD.

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

Line: 121

                  @JRubyMethod(name = "add_enum")
    public IRubyObject addEnum(ThreadContext context, IRubyObject name, Block block) {
        RubyObject ctx = (RubyObject) cEnumBuilderContext.newInstance(context, this, name, Block.NULL_BLOCK);
        ctx.instance_eval(context, block);

        return context.nil;
    }

    /*

            

Reported by PMD.

python/google/protobuf/descriptor_database.py
76 issues
Consider explicitly re-raising using the 'from' keyword
Error

Line: 141 Column: 9

                      return self._file_desc_protos_by_symbol[top_level]
      except KeyError:
        # Raise the original symbol as a KeyError for better diagnostics.
        raise KeyError(symbol)

  def FindFileContainingExtension(self, extendee_name, extension_number):
    # TODO(jieluo): implement this API.
    return None


            

Reported by Pylint.

Unused argument 'extendee_name'
Error

Line: 143 Column: 41

                      # Raise the original symbol as a KeyError for better diagnostics.
        raise KeyError(symbol)

  def FindFileContainingExtension(self, extendee_name, extension_number):
    # TODO(jieluo): implement this API.
    return None

  def FindAllExtensionNumbers(self, extendee_name):
    # TODO(jieluo): implement this API.

            

Reported by Pylint.

Unused argument 'extension_number'
Error

Line: 143 Column: 56

                      # Raise the original symbol as a KeyError for better diagnostics.
        raise KeyError(symbol)

  def FindFileContainingExtension(self, extendee_name, extension_number):
    # TODO(jieluo): implement this API.
    return None

  def FindAllExtensionNumbers(self, extendee_name):
    # TODO(jieluo): implement this API.

            

Reported by Pylint.

TODO(jieluo): implement this API.
Error

Line: 144 Column: 3

                      raise KeyError(symbol)

  def FindFileContainingExtension(self, extendee_name, extension_number):
    # TODO(jieluo): implement this API.
    return None

  def FindAllExtensionNumbers(self, extendee_name):
    # TODO(jieluo): implement this API.
    return []

            

Reported by Pylint.

Unused argument 'extendee_name'
Error

Line: 147 Column: 37

                  # TODO(jieluo): implement this API.
    return None

  def FindAllExtensionNumbers(self, extendee_name):
    # TODO(jieluo): implement this API.
    return []

  def _AddSymbol(self, name, file_desc_proto):
    if name in self._file_desc_protos_by_symbol:

            

Reported by Pylint.

TODO(jieluo): implement this API.
Error

Line: 148 Column: 3

                  return None

  def FindAllExtensionNumbers(self, extendee_name):
    # TODO(jieluo): implement this API.
    return []

  def _AddSymbol(self, name, file_desc_proto):
    if name in self._file_desc_protos_by_symbol:
      warn_msg = ('Conflict register for file "' + file_desc_proto.name +

            

Reported by Pylint.

Missing class docstring
Error

Line: 38 Column: 1

              import warnings


class Error(Exception):
  pass


class DescriptorDatabaseConflictingDefinitionError(Error):
  """Raised when a proto is added with the same name & different descriptor."""

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 39 Column: 1

              

class Error(Exception):
  pass


class DescriptorDatabaseConflictingDefinitionError(Error):
  """Raised when a proto is added with the same name & different descriptor."""


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 43 Column: 1

              

class DescriptorDatabaseConflictingDefinitionError(Error):
  """Raised when a proto is added with the same name & different descriptor."""


class DescriptorDatabase(object):
  """A container accepting FileDescriptorProtos and maps DescriptorProtos."""


            

Reported by Pylint.

Class 'DescriptorDatabase' inherits from object, can be safely removed from bases in python3
Error

Line: 46 Column: 1

                """Raised when a proto is added with the same name & different descriptor."""


class DescriptorDatabase(object):
  """A container accepting FileDescriptorProtos and maps DescriptorProtos."""

  def __init__(self):
    self._file_desc_protos_by_file = {}
    self._file_desc_protos_by_symbol = {}

            

Reported by Pylint.