The following issues were found

java/core/src/main/java/com/google/protobuf/ExtensionRegistry.java
32 issues
This class has too many methods, consider refactoring it.
Design

Line: 91

               *
 * @author kenton@google.com Kenton Varda
 */
public class ExtensionRegistry extends ExtensionRegistryLite {
  /** Construct a new, empty instance. */
  public static ExtensionRegistry newInstance() {
    return new ExtensionRegistry();
  }


            

Reported by PMD.

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

Line: 112

                /** A (Descriptor, Message) pair, returned by lookup methods. */
  public static final class ExtensionInfo {
    /** The extension's descriptor. */
    public final FieldDescriptor descriptor;

    /**
     * A default instance of the extension's type, if it has a message type. Otherwise, {@code
     * null}.
     */

            

Reported by PMD.

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

Line: 118

                   * A default instance of the extension's type, if it has a message type. Otherwise, {@code
     * null}.
     */
    public final Message defaultInstance;

    private ExtensionInfo(final FieldDescriptor descriptor) {
      this.descriptor = descriptor;
      defaultInstance = null;
    }

            

Reported by PMD.

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

Line: 193

                public Set<ExtensionInfo> getAllMutableExtensionsByExtendedType(final String fullName) {
    HashSet<ExtensionInfo> extensions = new HashSet<ExtensionInfo>();
    for (DescriptorIntPair pair : mutableExtensionsByNumber.keySet()) {
      if (pair.descriptor.getFullName().equals(fullName)) {
        extensions.add(mutableExtensionsByNumber.get(pair));
      }
    }
    return extensions;
  }

            

Reported by PMD.

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

Line: 193

                public Set<ExtensionInfo> getAllMutableExtensionsByExtendedType(final String fullName) {
    HashSet<ExtensionInfo> extensions = new HashSet<ExtensionInfo>();
    for (DescriptorIntPair pair : mutableExtensionsByNumber.keySet()) {
      if (pair.descriptor.getFullName().equals(fullName)) {
        extensions.add(mutableExtensionsByNumber.get(pair));
      }
    }
    return extensions;
  }

            

Reported by PMD.

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

Line: 210

                public Set<ExtensionInfo> getAllImmutableExtensionsByExtendedType(final String fullName) {
    HashSet<ExtensionInfo> extensions = new HashSet<ExtensionInfo>();
    for (DescriptorIntPair pair : immutableExtensionsByNumber.keySet()) {
      if (pair.descriptor.getFullName().equals(fullName)) {
        extensions.add(immutableExtensionsByNumber.get(pair));
      }
    }
    return extensions;
  }

            

Reported by PMD.

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

Line: 210

                public Set<ExtensionInfo> getAllImmutableExtensionsByExtendedType(final String fullName) {
    HashSet<ExtensionInfo> extensions = new HashSet<ExtensionInfo>();
    for (DescriptorIntPair pair : immutableExtensionsByNumber.keySet()) {
      if (pair.descriptor.getFullName().equals(fullName)) {
        extensions.add(immutableExtensionsByNumber.get(pair));
      }
    }
    return extensions;
  }

            

Reported by PMD.

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

Line: 233

                }

  static ExtensionInfo newExtensionInfo(final Extension<?, ?> extension) {
    if (extension.getDescriptor().getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
      if (extension.getMessageDefaultInstance() == null) {
        throw new IllegalStateException(
            "Registered message-type extension had null default instance: "
                + extension.getDescriptor().getFullName());
      }

            

Reported by PMD.

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

Line: 237

                    if (extension.getMessageDefaultInstance() == null) {
        throw new IllegalStateException(
            "Registered message-type extension had null default instance: "
                + extension.getDescriptor().getFullName());
      }
      return new ExtensionInfo(
          extension.getDescriptor(), (Message) extension.getMessageDefaultInstance());
    } else {
      return new ExtensionInfo(extension.getDescriptor(), null);

            

Reported by PMD.

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

Line: 286

                  this.mutableExtensionsByNumber = Collections.unmodifiableMap(other.mutableExtensionsByNumber);
  }

  private final Map<String, ExtensionInfo> immutableExtensionsByName;
  private final Map<String, ExtensionInfo> mutableExtensionsByName;
  private final Map<DescriptorIntPair, ExtensionInfo> immutableExtensionsByNumber;
  private final Map<DescriptorIntPair, ExtensionInfo> mutableExtensionsByNumber;

  ExtensionRegistry(boolean empty) {

            

Reported by PMD.

java/util/src/main/java/com/google/protobuf/util/Timestamps.java
31 issues
Avoid reassigning parameters such as 'seconds'
Design

Line: 409

                      checkedSubtract(start.getNanos(), length.getNanos()));
  }

  static Timestamp normalizedTimestamp(long seconds, int nanos) {
    if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
      seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
      nanos = (int) (nanos % NANOS_PER_SECOND);
    }
    if (nanos < 0) {

            

Reported by PMD.

Avoid reassigning parameters such as 'nanos'
Design

Line: 409

                      checkedSubtract(start.getNanos(), length.getNanos()));
  }

  static Timestamp normalizedTimestamp(long seconds, int nanos) {
    if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
      seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
      nanos = (int) (nanos % NANOS_PER_SECOND);
    }
    if (nanos < 0) {

            

Reported by PMD.

Avoid reassigning parameters such as 'seconds'
Design

Line: 409

                      checkedSubtract(start.getNanos(), length.getNanos()));
  }

  static Timestamp normalizedTimestamp(long seconds, int nanos) {
    if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
      seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
      nanos = (int) (nanos % NANOS_PER_SECOND);
    }
    if (nanos < 0) {

            

Reported by PMD.

Avoid reassigning parameters such as 'nanos'
Design

Line: 409

                      checkedSubtract(start.getNanos(), length.getNanos()));
  }

  static Timestamp normalizedTimestamp(long seconds, int nanos) {
    if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
      seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
      nanos = (int) (nanos % NANOS_PER_SECOND);
    }
    if (nanos < 0) {

            

Reported by PMD.

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

Line: 56

               * Utilities to help create/manipulate {@code protobuf/timestamp.proto}. All operations throw an
 * {@link IllegalArgumentException} if the input(s) are not {@linkplain #isValid(Timestamp) valid}.
 */
public final class Timestamps {

  // Timestamp for "0001-01-01T00:00:00Z"
  static final long TIMESTAMP_SECONDS_MIN = -62135596800L;

  // Timestamp for "9999-12-31T23:59:59Z"

            

Reported by PMD.

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

Line: 56

               * Utilities to help create/manipulate {@code protobuf/timestamp.proto}. All operations throw an
 * {@link IllegalArgumentException} if the input(s) are not {@linkplain #isValid(Timestamp) valid}.
 */
public final class Timestamps {

  // Timestamp for "0001-01-01T00:00:00Z"
  static final long TIMESTAMP_SECONDS_MIN = -62135596800L;

  // Timestamp for "9999-12-31T23:59:59Z"

            

Reported by PMD.

Possible God Class (WMC=61, ATFD=40, TCC=5.231%)
Design

Line: 56

               * Utilities to help create/manipulate {@code protobuf/timestamp.proto}. All operations throw an
 * {@link IllegalArgumentException} if the input(s) are not {@linkplain #isValid(Timestamp) valid}.
 */
public final class Timestamps {

  // Timestamp for "0001-01-01T00:00:00Z"
  static final long TIMESTAMP_SECONDS_MIN = -62135596800L;

  // Timestamp for "9999-12-31T23:59:59Z"

            

Reported by PMD.

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

Line: 56

               * Utilities to help create/manipulate {@code protobuf/timestamp.proto}. All operations throw an
 * {@link IllegalArgumentException} if the input(s) are not {@linkplain #isValid(Timestamp) valid}.
 */
public final class Timestamps {

  // Timestamp for "0001-01-01T00:00:00Z"
  static final long TIMESTAMP_SECONDS_MIN = -62135596800L;

  // Timestamp for "9999-12-31T23:59:59Z"

            

Reported by PMD.

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

Line: 134

                 *     and a value greater than {@code 0} if {@code x > y}
   */
  public static int compare(Timestamp x, Timestamp y) {
    return TimestampComparator.INSTANCE.compare(x, y);
  }

  /**
   * Returns true if the given {@link Timestamp} is valid. The {@code seconds} value must be in the
   * range [-62,135,596,800, +253,402,300,799] (i.e., between 0001-01-01T00:00:00Z and

            

Reported by PMD.

The String literal 'GoodTime' appears 9 times in this file; the first occurrence is on line 158
Error

Line: 158

                 * <p><b>Note:</b> Negative second values with fractional seconds must still have non-negative
   * nanos values that count forward in time.
   */
  @SuppressWarnings("GoodTime") // this is a legacy conversion API
  public static boolean isValid(long seconds, int nanos) {
    if (seconds < TIMESTAMP_SECONDS_MIN || seconds > TIMESTAMP_SECONDS_MAX) {
      return false;
    }
    if (nanos < 0 || nanos >= NANOS_PER_SECOND) {

            

Reported by PMD.

src/google/protobuf/compiler/cpp/cpp_message.cc
31 issues
StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 91 Column: 21 CWE codes: 120

                std::vector<std::string> parts;
  for (int i = 0; i < masks.size(); i++) {
    if (masks[i] == 0) continue;
    std::string m = StrCat("0x", strings::Hex(masks[i], strings::ZERO_PAD_8));
    // Each xor evaluates to 0 if the expected bits are present.
    parts.push_back(
        StrCat("((", has_bits_var, "[", i, "] & ", m, ") ^ ", m, ")"));
  }
  GOOGLE_CHECK(!parts.empty());

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 94 Column: 9 CWE codes: 120

                  std::string m = StrCat("0x", strings::Hex(masks[i], strings::ZERO_PAD_8));
    // Each xor evaluates to 0 if the expected bits are present.
    parts.push_back(
        StrCat("((", has_bits_var, "[", i, "] & ", m, ") ^ ", m, ")"));
  }
  GOOGLE_CHECK(!parts.empty());
  // If we have multiple parts, each expected to be 0, then bitwise-or them.
  std::string result =
      parts.size() == 1

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 101 Column: 13 CWE codes: 120

                std::string result =
      parts.size() == 1
          ? parts[0]
          : StrCat("(", Join(parts, "\n       | "), ")");
  return result + (return_success ? " == 0" : " != 0");
}

void PrintPresenceCheck(const Formatter& format, const FieldDescriptor* field,
                        const std::vector<int>& has_bit_indices,

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 115 Column: 9 CWE codes: 120

                    format("cached_has_bits = _has_bits_[$1$];\n", *cached_has_word_index);
    }
    const std::string mask =
        StrCat(strings::Hex(1u << (has_bit_index % 32), strings::ZERO_PAD_8));
    format("if (cached_has_bits & 0x$1$u) {\n", mask);
  } else {
    format("if (has_$1$()) {\n", FieldName(field));
  }
  format.Indent();

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 571 Column: 16 CWE codes: 120

                if (options.field_listener_options.forbidden_field_listener_events.count(
          std::string(annotation_name)))
    return;
  (*variables)[StrCat("annotate_", annotation_name)] = strings::Substitute(
      StrCat(injector_template_prefix, injector_template_suffix),
      (*variables)["classtype"]);
}

void GenerateExtensionAnnotations(

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 572 Column: 7 CWE codes: 120

                        std::string(annotation_name)))
    return;
  (*variables)[StrCat("annotate_", annotation_name)] = strings::Substitute(
      StrCat(injector_template_prefix, injector_template_suffix),
      (*variables)["classtype"]);
}

void GenerateExtensionAnnotations(
    const Descriptor* descriptor, const Options& options,

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 611 Column: 39 CWE codes: 120

                      !StrContains(annotation_name, "clear")) {
      // Primitive fields accessors.
      // "Has" is here as users calling "has" on a repeated field is a mistake.
      (*variables)[annotation_name] = StrCat(
          "  _tracker_.", listener_call,
          "(this, id.number(), _proto_TypeTraits::GetPtr(id.number(), "
          "_extensions_, id.default_value_ref()));");
    } else if (StrContains(annotation_name, "repeated") &&
               !StrContains(annotation_name, "list") &&

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 624 Column: 11 CWE codes: 120

                      str_index = "_extensions_.ExtensionSize(id.number()) - 1";
      }
      (*variables)[annotation_name] =
          StrCat("  _tracker_.", listener_call,
                       "(this, id.number(), "
                       "_proto_TypeTraits::GetPtr(id.number(), _extensions_, ",
                       str_index, "));");
    } else if (StrContains(annotation_name, "list") ||
               StrContains(annotation_name, "size")) {

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 631 Column: 39 CWE codes: 120

                  } else if (StrContains(annotation_name, "list") ||
               StrContains(annotation_name, "size")) {
      // Repeated full accessors.
      (*variables)[annotation_name] = StrCat(
          "  _tracker_.", listener_call,
          "(this, id.number(), _proto_TypeTraits::GetRepeatedPtr(id.number(), "
          "_extensions_));");
    } else {
      // Generic accessors such as "clear".

            

Reported by FlawFinder.

StrCat - Does not check for buffer overflows when concatenating to destination [MS-banned]
Security

Line: 1306 Column: 18 CWE codes: 120

                    format.Set("field_name", UnderscoresToCamelCase(field->name(), true));
      format.Set("oneof_name", field->containing_oneof()->name());
      format.Set("oneof_index",
                 StrCat(field->containing_oneof()->index()));
      GenerateOneofMemberHasBits(field, format);
    } else {
      // Singular field.
      GenerateSingularFieldHasBits(field, format);
    }

            

Reported by FlawFinder.

java/util/src/main/java/com/google/protobuf/util/Durations.java
31 issues
Avoid reassigning parameters such as 'value'
Design

Line: 246

                 * @return A Duration parsed from the string.
   * @throws ParseException if parsing fails.
   */
  public static Duration parse(String value) throws ParseException {
    // Must ended with "s".
    if (value.isEmpty() || value.charAt(value.length() - 1) != 's') {
      throw new ParseException("Invalid duration string: " + value, 0);
    }
    boolean negative = false;

            

Reported by PMD.

Avoid reassigning parameters such as 'nanos'
Design

Line: 463

                      checkedSubtract(d1.getNanos(), d2.getNanos()));
  }

  static Duration normalizedDuration(long seconds, int nanos) {
    if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
      seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
      nanos %= NANOS_PER_SECOND;
    }
    if (seconds > 0 && nanos < 0) {

            

Reported by PMD.

Avoid reassigning parameters such as 'nanos'
Design

Line: 463

                      checkedSubtract(d1.getNanos(), d2.getNanos()));
  }

  static Duration normalizedDuration(long seconds, int nanos) {
    if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
      seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
      nanos %= NANOS_PER_SECOND;
    }
    if (seconds > 0 && nanos < 0) {

            

Reported by PMD.

Avoid reassigning parameters such as 'seconds'
Design

Line: 463

                      checkedSubtract(d1.getNanos(), d2.getNanos()));
  }

  static Duration normalizedDuration(long seconds, int nanos) {
    if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
      seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
      nanos %= NANOS_PER_SECOND;
    }
    if (seconds > 0 && nanos < 0) {

            

Reported by PMD.

Avoid reassigning parameters such as 'seconds'
Design

Line: 463

                      checkedSubtract(d1.getNanos(), d2.getNanos()));
  }

  static Duration normalizedDuration(long seconds, int nanos) {
    if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
      seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
      nanos %= NANOS_PER_SECOND;
    }
    if (seconds > 0 && nanos < 0) {

            

Reported by PMD.

Avoid reassigning parameters such as 'seconds'
Design

Line: 463

                      checkedSubtract(d1.getNanos(), d2.getNanos()));
  }

  static Duration normalizedDuration(long seconds, int nanos) {
    if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
      seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
      nanos %= NANOS_PER_SECOND;
    }
    if (seconds > 0 && nanos < 0) {

            

Reported by PMD.

Avoid reassigning parameters such as 'nanos'
Design

Line: 463

                      checkedSubtract(d1.getNanos(), d2.getNanos()));
  }

  static Duration normalizedDuration(long seconds, int nanos) {
    if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) {
      seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND);
      nanos %= NANOS_PER_SECOND;
    }
    if (seconds > 0 && nanos < 0) {

            

Reported by PMD.

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

Line: 56

               * Utilities to help create/manipulate {@code protobuf/duration.proto}. All operations throw an
 * {@link IllegalArgumentException} if the input(s) are not {@linkplain #isValid(Duration) valid}.
 */
public final class Durations {
  static final long DURATION_SECONDS_MIN = -315576000000L;
  static final long DURATION_SECONDS_MAX = 315576000000L;

  private static final long SECONDS_PER_MINUTE = 60L;
  private static final long SECONDS_PER_HOUR = SECONDS_PER_MINUTE * 60;

            

Reported by PMD.

Possible God Class (WMC=65, ATFD=29, TCC=0.645%)
Design

Line: 56

               * Utilities to help create/manipulate {@code protobuf/duration.proto}. All operations throw an
 * {@link IllegalArgumentException} if the input(s) are not {@linkplain #isValid(Duration) valid}.
 */
public final class Durations {
  static final long DURATION_SECONDS_MIN = -315576000000L;
  static final long DURATION_SECONDS_MAX = 315576000000L;

  private static final long SECONDS_PER_MINUTE = 60L;
  private static final long SECONDS_PER_HOUR = SECONDS_PER_MINUTE * 60;

            

Reported by PMD.

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

Line: 106

                 *     and a value greater than {@code 0} if {@code x > y}
   */
  public static int compare(Duration x, Duration y) {
    return DurationComparator.INSTANCE.compare(x, y);
  }

  /**
   * Returns true if the given {@link Duration} is valid. The {@code seconds} value must be in the
   * range [-315,576,000,000, +315,576,000,000]. The {@code nanos} value must be in the range

            

Reported by PMD.

java/core/src/test/java/com/google/protobuf/AbstractProto3SchemaTest.java
30 issues
Potential violation of Law of Demeter (object not created locally)
Design

Line: 59

                  {
      ByteBuffer buffer = ByteBuffer.allocate(100);
      CodedOutputStream codedOutput = CodedOutputStream.newInstance(buffer);
      codedOutput.writeByteArray(Proto3Message.FIELD_STRING_9_FIELD_NUMBER, invalid);
      codedOutput.flush();
      buffer.flip();
      invalidBytes.add(buffer);
    }
    {

            

Reported by PMD.

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

Line: 60

                    ByteBuffer buffer = ByteBuffer.allocate(100);
      CodedOutputStream codedOutput = CodedOutputStream.newInstance(buffer);
      codedOutput.writeByteArray(Proto3Message.FIELD_STRING_9_FIELD_NUMBER, invalid);
      codedOutput.flush();
      buffer.flip();
      invalidBytes.add(buffer);
    }
    {
      ByteBuffer buffer = ByteBuffer.allocate(100);

            

Reported by PMD.

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

Line: 61

                    CodedOutputStream codedOutput = CodedOutputStream.newInstance(buffer);
      codedOutput.writeByteArray(Proto3Message.FIELD_STRING_9_FIELD_NUMBER, invalid);
      codedOutput.flush();
      buffer.flip();
      invalidBytes.add(buffer);
    }
    {
      ByteBuffer buffer = ByteBuffer.allocate(100);
      CodedOutputStream codedOutput = CodedOutputStream.newInstance(buffer);

            

Reported by PMD.

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

Line: 67

                  {
      ByteBuffer buffer = ByteBuffer.allocate(100);
      CodedOutputStream codedOutput = CodedOutputStream.newInstance(buffer);
      codedOutput.writeByteArray(Proto3Message.FIELD_STRING_LIST_26_FIELD_NUMBER, invalid);
      codedOutput.flush();
      buffer.flip();
      invalidBytes.add(buffer);
    }
    return invalidBytes;

            

Reported by PMD.

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

Line: 68

                    ByteBuffer buffer = ByteBuffer.allocate(100);
      CodedOutputStream codedOutput = CodedOutputStream.newInstance(buffer);
      codedOutput.writeByteArray(Proto3Message.FIELD_STRING_LIST_26_FIELD_NUMBER, invalid);
      codedOutput.flush();
      buffer.flip();
      invalidBytes.add(buffer);
    }
    return invalidBytes;
  }

            

Reported by PMD.

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

Line: 69

                    CodedOutputStream codedOutput = CodedOutputStream.newInstance(buffer);
      codedOutput.writeByteArray(Proto3Message.FIELD_STRING_LIST_26_FIELD_NUMBER, invalid);
      codedOutput.flush();
      buffer.flip();
      invalidBytes.add(buffer);
    }
    return invalidBytes;
  }


            

Reported by PMD.

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

Line: 76

                }

  @Test
  public void mergeOptionalMessageFields() throws Exception {
    Proto3Message message1 =
        newBuilder()
            .setFieldMessage10(newBuilder().setFieldInt643(123).clearFieldInt325().build())
            .build();
    Proto3Message message2 =

            

Reported by PMD.

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

Line: 76

                }

  @Test
  public void mergeOptionalMessageFields() throws Exception {
    Proto3Message message1 =
        newBuilder()
            .setFieldMessage10(newBuilder().setFieldInt643(123).clearFieldInt325().build())
            .build();
    Proto3Message message2 =

            

Reported by PMD.

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

Line: 90

                          .setFieldMessage10(newBuilder().setFieldInt643(789).clearFieldInt325().build())
            .build();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    message1.writeTo(output);
    message2.writeTo(output);
    message3.writeTo(output);
    byte[] data = output.toByteArray();

    Proto3Message merged = ExperimentalSerializationUtil.fromByteArray(data, Proto3Message.class);

            

Reported by PMD.

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

Line: 91

                          .build();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    message1.writeTo(output);
    message2.writeTo(output);
    message3.writeTo(output);
    byte[] data = output.toByteArray();

    Proto3Message merged = ExperimentalSerializationUtil.fromByteArray(data, Proto3Message.class);
    assertThat(merged.getFieldMessage10().getFieldInt643()).isEqualTo(789);

            

Reported by PMD.

java/core/src/main/java/com/google/protobuf/MapField.java
30 issues
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.Internal.checkNotNull;

import java.util.ArrayList;
import java.util.Collection;

            

Reported by PMD.

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

Line: 56

               * <p>THREAD-SAFETY NOTE: Read-only access is thread-safe. Users can call getMap() and getList()
 * concurrently in multiple threads. If write-access is needed, all access must be synchronized.
 */
public class MapField<K, V> implements MutabilityOracle {

  /**
   * Indicates where the data of this map field is currently stored.
   *
   * <ul>

            

Reported by PMD.

Field isMutable has the same name as a method
Error

Line: 86

                  BOTH
  }

  private volatile boolean isMutable;
  private volatile StorageMode mode;
  private MutatabilityAwareMap<K, V> mapData;
  private List<Message> listData;

  // Convert between a map entry Message and a key-value pair.

            

Reported by PMD.

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

Line: 86

                  BOTH
  }

  private volatile boolean isMutable;
  private volatile StorageMode mode;
  private MutatabilityAwareMap<K, V> mapData;
  private List<Message> listData;

  // Convert between a map entry Message and a key-value pair.

            

Reported by PMD.

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

Line: 87

                }

  private volatile boolean isMutable;
  private volatile StorageMode mode;
  private MutatabilityAwareMap<K, V> mapData;
  private List<Message> listData;

  // Convert between a map entry Message and a key-value pair.
  private static interface Converter<K, V> {

            

Reported by PMD.

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

Line: 88

              
  private volatile boolean isMutable;
  private volatile StorageMode mode;
  private MutatabilityAwareMap<K, V> mapData;
  private List<Message> listData;

  // Convert between a map entry Message and a key-value pair.
  private static interface Converter<K, V> {
    Message convertKeyAndValueToMessage(K key, V value);

            

Reported by PMD.

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

Line: 89

                private volatile boolean isMutable;
  private volatile StorageMode mode;
  private MutatabilityAwareMap<K, V> mapData;
  private List<Message> listData;

  // Convert between a map entry Message and a key-value pair.
  private static interface Converter<K, V> {
    Message convertKeyAndValueToMessage(K key, V value);


            

Reported by PMD.

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

Line: 101

                }

  private static class ImmutableMessageConverter<K, V> implements Converter<K, V> {
    private final MapEntry<K, V> defaultEntry;

    public ImmutableMessageConverter(MapEntry<K, V> defaultEntry) {
      this.defaultEntry = defaultEntry;
    }


            

Reported by PMD.

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

Line: 109

              
    @Override
    public Message convertKeyAndValueToMessage(K key, V value) {
      return defaultEntry.newBuilderForType().setKey(key).setValue(value).buildPartial();
    }

    @Override
    @SuppressWarnings("unchecked")
    public void convertMessageToKeyAndValue(Message message, Map<K, V> map) {

            

Reported by PMD.

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

Line: 109

              
    @Override
    public Message convertKeyAndValueToMessage(K key, V value) {
      return defaultEntry.newBuilderForType().setKey(key).setValue(value).buildPartial();
    }

    @Override
    @SuppressWarnings("unchecked")
    public void convertMessageToKeyAndValue(Message message, Map<K, V> map) {

            

Reported by PMD.

examples/AddPerson.java
30 issues
Avoid instantiating FileInputStream, FileOutputStream, FileReader, or FileWriter
Performance

Line: 72

              
    // Read the existing address book.
    try {
      FileInputStream input = new FileInputStream(args[0]);
      try {
        addressBook.mergeFrom(input);
      } finally {
        try { input.close(); } catch (Throwable ignore) {}
      }

            

Reported by PMD.

Avoid instantiating FileInputStream, FileOutputStream, FileReader, or FileWriter
Performance

Line: 88

                                     System.out));

    // Write the new address book back to disk.
    FileOutputStream output = new FileOutputStream(args[0]);
    try {
      addressBook.build().writeTo(output);
    } finally {
      output.close();
    }

            

Reported by PMD.

System.err.println is used
Design

Line: 64

                //   file.
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("Usage:  AddPerson ADDRESS_BOOK_FILE");
      System.exit(-1);
    }

    AddressBook.Builder addressBook = AddressBook.newBuilder();


            

Reported by PMD.

System.out.println is used
Design

Line: 79

                      try { input.close(); } catch (Throwable ignore) {}
      }
    } catch (FileNotFoundException e) {
      System.out.println(args[0] + ": File not found.  Creating a new file.");
    }

    // Add an address.
    addressBook.addPeople(
      PromptForAddress(new BufferedReader(new InputStreamReader(System.in)),

            

Reported by PMD.

All methods are static. Consider using a utility class instead. Alternatively, you could add a private constructor or make the class abstract to silence this warning.
Design

Line: 13

              import java.io.IOException;
import java.io.PrintStream;

class AddPerson {
  // This function fills in a Person message based on user input.
  static Person PromptForAddress(BufferedReader stdin,
                                 PrintStream stdout) throws IOException {
    Person.Builder person = Person.newBuilder();


            

Reported by PMD.

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

Line: 20

                  Person.Builder person = Person.newBuilder();

    stdout.print("Enter person ID: ");
    person.setId(Integer.valueOf(stdin.readLine()));

    stdout.print("Enter name: ");
    person.setName(stdin.readLine());

    stdout.print("Enter email address (blank for none): ");

            

Reported by PMD.

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

Line: 23

                  person.setId(Integer.valueOf(stdin.readLine()));

    stdout.print("Enter name: ");
    person.setName(stdin.readLine());

    stdout.print("Enter email address (blank for none): ");
    String email = stdin.readLine();
    if (email.length() > 0) {
      person.setEmail(email);

            

Reported by PMD.

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

Line: 27

              
    stdout.print("Enter email address (blank for none): ");
    String email = stdin.readLine();
    if (email.length() > 0) {
      person.setEmail(email);
    }

    while (true) {
      stdout.print("Enter a phone number (or leave blank to finish): ");

            

Reported by PMD.

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

Line: 34

                  while (true) {
      stdout.print("Enter a phone number (or leave blank to finish): ");
      String number = stdin.readLine();
      if (number.length() == 0) {
        break;
      }

      Person.PhoneNumber.Builder phoneNumber =
        Person.PhoneNumber.newBuilder().setNumber(number);

            

Reported by PMD.

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

Line: 39

                    }

      Person.PhoneNumber.Builder phoneNumber =
        Person.PhoneNumber.newBuilder().setNumber(number);

      stdout.print("Is this a mobile, home, or work phone? ");
      String type = stdin.readLine();
      if (type.equals("mobile")) {
        phoneNumber.setType(Person.PhoneType.MOBILE);

            

Reported by PMD.

java/core/src/test/java/com/google/protobuf/BoundedByteStringTest.java
29 issues
Potential violation of Law of Demeter (method chain calls)
Design

Line: 61

                  byte[] sourceBytes = ByteStringTest.getTestBytes(2341, 11337766L);
    int from = 100;
    int to = sourceBytes.length - 100;
    stringUnderTest = ByteString.copyFrom(sourceBytes).substring(from, to);
    referenceBytes = new byte[to - from];
    System.arraycopy(sourceBytes, from, referenceBytes, 0, to - from);
    expectedHashCode = 727575887;
  }


            

Reported by PMD.

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

Line: 69

              
  @Override
  @Test
  public void testToString() throws UnsupportedEncodingException {
    String testString = "I love unicode \u1234\u5678 characters";
    ByteString unicode = ByteString.wrap(testString.getBytes(Internal.UTF_8));
    ByteString chopped = unicode.substring(2, unicode.size() - 6);
    assertWithMessage("%s.substring() must have the expected type", classUnderTest)
        .that(classUnderTest)

            

Reported by PMD.

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

Line: 71

                @Test
  public void testToString() throws UnsupportedEncodingException {
    String testString = "I love unicode \u1234\u5678 characters";
    ByteString unicode = ByteString.wrap(testString.getBytes(Internal.UTF_8));
    ByteString chopped = unicode.substring(2, unicode.size() - 6);
    assertWithMessage("%s.substring() must have the expected type", classUnderTest)
        .that(classUnderTest)
        .isEqualTo(getActualClassName(chopped));


            

Reported by PMD.

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

Line: 72

                public void testToString() throws UnsupportedEncodingException {
    String testString = "I love unicode \u1234\u5678 characters";
    ByteString unicode = ByteString.wrap(testString.getBytes(Internal.UTF_8));
    ByteString chopped = unicode.substring(2, unicode.size() - 6);
    assertWithMessage("%s.substring() must have the expected type", classUnderTest)
        .that(classUnderTest)
        .isEqualTo(getActualClassName(chopped));

    String roundTripString = chopped.toString(UTF_8);

            

Reported by PMD.

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

Line: 72

                public void testToString() throws UnsupportedEncodingException {
    String testString = "I love unicode \u1234\u5678 characters";
    ByteString unicode = ByteString.wrap(testString.getBytes(Internal.UTF_8));
    ByteString chopped = unicode.substring(2, unicode.size() - 6);
    assertWithMessage("%s.substring() must have the expected type", classUnderTest)
        .that(classUnderTest)
        .isEqualTo(getActualClassName(chopped));

    String roundTripString = chopped.toString(UTF_8);

            

Reported by PMD.

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

Line: 73

                  String testString = "I love unicode \u1234\u5678 characters";
    ByteString unicode = ByteString.wrap(testString.getBytes(Internal.UTF_8));
    ByteString chopped = unicode.substring(2, unicode.size() - 6);
    assertWithMessage("%s.substring() must have the expected type", classUnderTest)
        .that(classUnderTest)
        .isEqualTo(getActualClassName(chopped));

    String roundTripString = chopped.toString(UTF_8);
    assertWithMessage("%s unicode bytes must match", classUnderTest)

            

Reported by PMD.

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

Line: 73

                  String testString = "I love unicode \u1234\u5678 characters";
    ByteString unicode = ByteString.wrap(testString.getBytes(Internal.UTF_8));
    ByteString chopped = unicode.substring(2, unicode.size() - 6);
    assertWithMessage("%s.substring() must have the expected type", classUnderTest)
        .that(classUnderTest)
        .isEqualTo(getActualClassName(chopped));

    String roundTripString = chopped.toString(UTF_8);
    assertWithMessage("%s unicode bytes must match", classUnderTest)

            

Reported by PMD.

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

Line: 77

                      .that(classUnderTest)
        .isEqualTo(getActualClassName(chopped));

    String roundTripString = chopped.toString(UTF_8);
    assertWithMessage("%s unicode bytes must match", classUnderTest)
        .that(testString.substring(2, testString.length() - 6))
        .isEqualTo(roundTripString);
  }


            

Reported by PMD.

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

Line: 78

                      .isEqualTo(getActualClassName(chopped));

    String roundTripString = chopped.toString(UTF_8);
    assertWithMessage("%s unicode bytes must match", classUnderTest)
        .that(testString.substring(2, testString.length() - 6))
        .isEqualTo(roundTripString);
  }

  @Override

            

Reported by PMD.

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

Line: 78

                      .isEqualTo(getActualClassName(chopped));

    String roundTripString = chopped.toString(UTF_8);
    assertWithMessage("%s unicode bytes must match", classUnderTest)
        .that(testString.substring(2, testString.length() - 6))
        .isEqualTo(roundTripString);
  }

  @Override

            

Reported by PMD.

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

Line: 283

                          // used on the super class.
            TypeVariable<?>[] clazzParams = clazz.getTypeParameters();
            if (realTypes.length != clazzParams.length) {
              throw new RuntimeException("Type array mismatch");
            }

            // Replace the variable parameter with the real type.
            boolean foundReplacement = false;
            for (int j = 0; j < clazzParams.length; ++j) {

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 297

                            }
            }
            if (!foundReplacement) {
              throw new RuntimeException("Unable to find replacement for " + superArg);
            }
          }
        }

        Class<?> parent = (Class<?>) parameterizedType.getRawType();

            

Reported by PMD.

Avoid throwing raw exception types.
Design

Line: 322

                  }

    if (realTypes.length != 1) {
      throw new RuntimeException("Unable to identify parameter type for List<T>");
    }
    return realTypes[0];
  }

  enum Collection {

            

Reported by PMD.

Avoid reassigning parameters such as 'clazz'
Design

Line: 267

                 *     any generic parameters, this list should be empty.
   * @return the {@link List} parameter.
   */
  private static Type getListParameter(Class<?> clazz, Type[] realTypes) {
    top:
    while (clazz != List.class) {
      // First look at generic subclass and interfaces.
      Type genericType = getGenericSuperList(clazz);
      if (genericType instanceof ParameterizedType) {

            

Reported by PMD.

Avoid reassigning parameters such as 'realTypes'
Design

Line: 267

                 *     any generic parameters, this list should be empty.
   * @return the {@link List} parameter.
   */
  private static Type getListParameter(Class<?> clazz, Type[] realTypes) {
    top:
    while (clazz != List.class) {
      // First look at generic subclass and interfaces.
      Type genericType = getGenericSuperList(clazz);
      if (genericType instanceof ParameterizedType) {

            

Reported by PMD.

Avoid reassigning parameters such as 'clazz'
Design

Line: 267

                 *     any generic parameters, this list should be empty.
   * @return the {@link List} parameter.
   */
  private static Type getListParameter(Class<?> clazz, Type[] realTypes) {
    top:
    while (clazz != List.class) {
      // First look at generic subclass and interfaces.
      Type genericType = getGenericSuperList(clazz);
      if (genericType instanceof ParameterizedType) {

            

Reported by PMD.

Avoid reassigning parameters such as 'clazz'
Design

Line: 267

                 *     any generic parameters, this list should be empty.
   * @return the {@link List} parameter.
   */
  private static Type getListParameter(Class<?> clazz, Type[] realTypes) {
    top:
    while (clazz != List.class) {
      // First look at generic subclass and interfaces.
      Type genericType = getGenericSuperList(clazz);
      if (genericType instanceof ParameterizedType) {

            

Reported by PMD.

Avoid reassigning parameters such as 'realTypes'
Design

Line: 267

                 *     any generic parameters, this list should be empty.
   * @return the {@link List} parameter.
   */
  private static Type getListParameter(Class<?> clazz, Type[] realTypes) {
    top:
    while (clazz != List.class) {
      // First look at generic subclass and interfaces.
      Type genericType = getGenericSuperList(clazz);
      if (genericType instanceof ParameterizedType) {

            

Reported by PMD.

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

Line: 41

              
/** Enumeration identifying all relevant type information for a protobuf field. */
@ExperimentalApi
public enum FieldType {
  DOUBLE(0, Collection.SCALAR, JavaType.DOUBLE),
  FLOAT(1, Collection.SCALAR, JavaType.FLOAT),
  INT64(2, Collection.SCALAR, JavaType.LONG),
  UINT64(3, Collection.SCALAR, JavaType.LONG),
  INT32(4, Collection.SCALAR, JavaType.INT),

            

Reported by PMD.

The class 'FieldType' has a Standard Cyclomatic Complexity of 3(Highest = 12).
Design

Line: 41

              
/** Enumeration identifying all relevant type information for a protobuf field. */
@ExperimentalApi
public enum FieldType {
  DOUBLE(0, Collection.SCALAR, JavaType.DOUBLE),
  FLOAT(1, Collection.SCALAR, JavaType.FLOAT),
  INT64(2, Collection.SCALAR, JavaType.LONG),
  UINT64(3, Collection.SCALAR, JavaType.LONG),
  INT32(4, Collection.SCALAR, JavaType.INT),

            

Reported by PMD.

java/core/src/main/java/com/google/protobuf/RepeatedFieldBuilderV3.java
27 issues
This class has too many methods, consider refactoring it.
Design

Line: 65

                      MType extends AbstractMessage,
        BType extends AbstractMessage.Builder,
        IType extends MessageOrBuilder>
    implements AbstractMessage.BuilderParent {

  // Parent to send changes to.
  private AbstractMessage.BuilderParent parent;

  // List of messages. Never null. It may be immutable, in which case

            

Reported by PMD.

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

Line: 68

                  implements AbstractMessage.BuilderParent {

  // Parent to send changes to.
  private AbstractMessage.BuilderParent parent;

  // List of messages. Never null. It may be immutable, in which case
  // isMessagesListMutable will be false. See note below.
  private List<MType> messages;


            

Reported by PMD.

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

Line: 72

              
  // List of messages. Never null. It may be immutable, in which case
  // isMessagesListMutable will be false. See note below.
  private List<MType> messages;

  // Whether messages is an mutable array that can be modified.
  private boolean isMessagesListMutable;

  // List of builders. May be null, in which case, no nested builders were

            

Reported by PMD.

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

Line: 75

                private List<MType> messages;

  // Whether messages is an mutable array that can be modified.
  private boolean isMessagesListMutable;

  // List of builders. May be null, in which case, no nested builders were
  // created. If not null, entries represent the builder for that index.
  private List<SingleFieldBuilderV3<MType, BType, IType>> builders;


            

Reported by PMD.

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

Line: 79

              
  // List of builders. May be null, in which case, no nested builders were
  // created. If not null, entries represent the builder for that index.
  private List<SingleFieldBuilderV3<MType, BType, IType>> builders;

  // Here are the invariants for messages and builders:
  // 1. messages is never null and its count corresponds to the number of items
  //    in the repeated field.
  // 2. If builders is non-null, messages and builders MUST always

            

Reported by PMD.

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

Line: 97

              
  // Indicates that we've built a message and so we are now obligated
  // to dispatch dirty invalidations. See AbstractMessage.BuilderListener.
  private boolean isClean;

  // A view of this builder that exposes a List interface of messages. This is
  // initialized on demand. This is fully backed by this object and all changes
  // are reflected in it. Access to any item converts it to a message if it
  // was a builder.

            

Reported by PMD.

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

Line: 103

                // initialized on demand. This is fully backed by this object and all changes
  // are reflected in it. Access to any item converts it to a message if it
  // was a builder.
  private MessageExternalList<MType, BType, IType> externalMessageList;

  // A view of this builder that exposes a List interface of builders. This is
  // initialized on demand. This is fully backed by this object and all changes
  // are reflected in it. Access to any item converts it to a builder if it
  // was a message.

            

Reported by PMD.

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

Line: 109

                // initialized on demand. This is fully backed by this object and all changes
  // are reflected in it. Access to any item converts it to a builder if it
  // was a message.
  private BuilderExternalList<MType, BType, IType> externalBuilderList;

  // A view of this builder that exposes a List interface of the interface
  // implemented by messages and builders. This is initialized on demand. This
  // is fully backed by this object and all changes are reflected in it.
  // Access to any item returns either a builder or message depending on

            

Reported by PMD.

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

Line: 116

                // is fully backed by this object and all changes are reflected in it.
  // Access to any item returns either a builder or message depending on
  // what is most efficient.
  private MessageOrBuilderExternalList<MType, BType, IType> externalMessageOrBuilderList;

  /**
   * Constructs a new builder with an empty list of messages.
   *
   * @param messages the current list of messages

            

Reported by PMD.

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

Line: 139

              
  public void dispose() {
    // Null out parent so we stop sending it invalidations.
    parent = null;
  }

  /**
   * Ensures that the list of messages is mutable so it can be updated. If it's immutable, a copy is
   * made.

            

Reported by PMD.