Java Code Examples for com.google.protobuf.Descriptors.FieldDescriptor.JavaType#MESSAGE

The following examples show how to use com.google.protobuf.Descriptors.FieldDescriptor.JavaType#MESSAGE . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProtoFuzzer.java    From bundletool with Apache License 2.0 6 votes vote down vote up
private static void shuffleRepeatedFields(Message.Builder shuffled) {
  for (FieldDescriptor field : shuffled.getAllFields().keySet()) {
    // Shuffle all contained proto messages recursively.
    if (field.getJavaType() == JavaType.MESSAGE) {
      if (field.isRepeated()) {
        IntStream.range(0, shuffled.getRepeatedFieldCount(field))
            .forEach(i -> shuffleRepeatedFields(shuffled.getRepeatedFieldBuilder(field, i)));
      } else {
        shuffleRepeatedFields(shuffled.getFieldBuilder(field));
      }
    }
    // Shuffle values of the field itself.
    if (field.isRepeated()) {
      int len = shuffled.getRepeatedFieldCount(field);
      for (int i = 0; i < len - 1; i++) {
        swapRepeatedFieldValues(shuffled, field, i, i + RAND.nextInt(len - i));
      }
    }
  }
}
 
Example 2
Source File: ProtoTruthMessageDifferencer.java    From curiostack with MIT License 6 votes vote down vote up
private SingularField compareSingularValue(
    @NullableDecl Object actual,
    @NullableDecl Object expected,
    @NullableDecl Object defaultValue,
    boolean excludeNonRecursive,
    FieldDescriptor fieldDescriptor,
    String fieldName,
    FluentEqualityConfig config) {
  if (fieldDescriptor.getJavaType() == JavaType.MESSAGE) {
    return compareSingularMessage(
        (Message) actual,
        (Message) expected,
        (Message) defaultValue,
        excludeNonRecursive,
        fieldDescriptor,
        fieldName,
        config);
  } else if (excludeNonRecursive) {
    return SingularField.ignored(fieldName);
  } else {
    return compareSingularPrimitive(
        actual, expected, defaultValue, fieldDescriptor, fieldName, config);
  }
}
 
Example 3
Source File: TestExtensionRegistry.java    From jackson-datatype-protobuf with Apache License 2.0 6 votes vote down vote up
public static ExtensionRegistry getInstance() {
  ExtensionRegistry extensionRegistry = ExtensionRegistry.newInstance();
  Iterable<FieldDescriptor> extensionDescriptors = Iterables.concat(
      AllExtensions.getDescriptor().getExtensions(),
      RepeatedExtensions.getDescriptor().getExtensions()
  );

  for (FieldDescriptor extension : extensionDescriptors) {
    if (extension.getJavaType() == JavaType.MESSAGE) {
      extensionRegistry.add(extension, Nested.getDefaultInstance());
    } else {
      extensionRegistry.add(extension);
    }
  }

  return extensionRegistry;
}
 
Example 4
Source File: ProtoFieldInfo.java    From curiostack with MIT License 5 votes vote down vote up
/**
 * Return the Java {@link Class} that corresponds to the value of this field. Generally used for
 * method resolution and casting generics.
 */
Class<?> javaClass() {
  if (isMapField() && valueJavaType() == JavaType.MESSAGE) {
    Message mapEntry = containingPrototype.newBuilderForType().newBuilderForField(field).build();
    return mapEntry.getField(mapEntry.getDescriptorForType().findFieldByName("value")).getClass();
  }
  switch (valueJavaType()) {
    case INT:
      return int.class;
    case LONG:
      return long.class;
    case FLOAT:
      return float.class;
    case DOUBLE:
      return double.class;
    case BOOLEAN:
      return boolean.class;
    case STRING:
      return String.class;
    case BYTE_STRING:
      return ByteString.class;
    case ENUM:
      return int.class;
    case MESSAGE:
      return containingPrototype
          .newBuilderForType()
          .newBuilderForField(valueField().descriptor())
          .build()
          .getClass();
    default:
      throw new IllegalArgumentException("Unknown field type: " + valueJavaType());
  }
}
 
Example 5
Source File: DoParse.java    From curiostack with MIT License 5 votes vote down vote up
/**
 * Returns the {@link StackManipulation} for setting the value of a field. This will be all the
 * elements for a repeated field.
 *
 * @param info description of the field to set.
 * @param beforeReadField jump target for before reading a field, used once this field is
 *     completed being set.
 * @param locals the method local variables
 * @param fieldsByName the instance fields
 */
private StackManipulation setFieldValue(
    ProtoFieldInfo info,
    Label beforeReadField,
    LocalVariables<LocalVariable> locals,
    Map<String, FieldDescription> fieldsByName) {
  if (info.isMapField()) {
    return setMapFieldValue(info, beforeReadField, locals, fieldsByName);
  } else {
    final StackManipulation setConcreteValue = invoke(info.setValueMethod());
    final StackManipulation setSingleValue;
    if (info.valueJavaType() == JavaType.MESSAGE) {
      setSingleValue =
          new StackManipulation.Compound(
              TypeCasting.to(new ForLoadedType(info.javaClass())), setConcreteValue);
    } else if (info.valueType() == Type.ENUM && !info.isRepeated()) {
      // For non-repeated enums, we treat unknown as the default value.
      setSingleValue =
          new StackManipulation.Compound(ParseSupport_mapUnknownEnumValue, setConcreteValue);
    } else {
      setSingleValue = setConcreteValue;
    }
    if (info.descriptor().isRepeated()) {
      return setRepeatedFieldValue(info, beforeReadField, locals, fieldsByName, setSingleValue);
    } else {
      // Set a singular value, e.g.,
      // builder.setFoo(readValue());
      return new StackManipulation.Compound(
          locals.load(LocalVariable.builder),
          locals.load(LocalVariable.parser),
          readValue(info, fieldsByName, locals),
          setSingleValue,
          Removal.SINGLE,
          new Goto(beforeReadField));
    }
  }
}
 
Example 6
Source File: DoParse.java    From curiostack with MIT License 5 votes vote down vote up
/**
 * Determines whether we skip processing of the field if it is null. We usually skip null values
 * in the JSON to treat them as default, but must actually process the null for {@link Value} and
 * {@link NullValue} because it means their value must be set.
 */
private static boolean mustSkipNull(FieldDescriptor field) {
  if (field.isRepeated()) {
    return true;
  }
  if (field.getJavaType() == JavaType.MESSAGE
      && field.getMessageType() == Value.getDescriptor()) {
    return false;
  }
  if (field.getJavaType() == JavaType.ENUM && field.getEnumType() == NullValue.getDescriptor()) {
    return false;
  }
  return true;
}
 
Example 7
Source File: Message.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Collects messages referred to by a message and its nested messages.
 *
 * @return {@code referenced}
 */
private static Collection<Descriptor> collectMessages(
    Descriptor message, Collection<Descriptor> referenced) {
  for (FieldDescriptor fd : message.getFields()) {
    if (fd.getJavaType() == JavaType.MESSAGE) {
      referenced.add(fd.getMessageType());
    }
  }
  for (Descriptor nd : message.getNestedTypes()) {
    collectMessages(nd, referenced);
  }
  return referenced;
}
 
Example 8
Source File: ProtoSchemaConverter.java    From parquet-mr with Apache License 2.0 5 votes vote down vote up
private <T> Builder<? extends Builder<?, GroupBuilder<T>>, GroupBuilder<T>> addField(FieldDescriptor descriptor, final GroupBuilder<T> builder) {
  if (descriptor.getJavaType() == JavaType.MESSAGE) {
    return addMessageField(descriptor, builder);
  }

  ParquetType parquetType = getParquetType(descriptor);
  if (descriptor.isRepeated() && parquetSpecsCompliant) {
    // the old schema style did not include the LIST wrapper around repeated fields
    return addRepeatedPrimitive(parquetType.primitiveType, parquetType.logicalTypeAnnotation, builder);
  }

  return builder.primitive(parquetType.primitiveType, getRepetition(descriptor)).as(parquetType.logicalTypeAnnotation);
}
 
Example 9
Source File: Message.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * Collects messages referred to by a message and its nested messages.
 *
 * @return {@code referenced}
 */
private static Collection<Descriptor> collectMessages(
    Descriptor message, Collection<Descriptor> referenced) {
  for (FieldDescriptor fd : message.getFields()) {
    if (fd.getJavaType() == JavaType.MESSAGE) {
      referenced.add(fd.getMessageType());
    }
  }
  for (Descriptor nd : message.getNestedTypes()) {
    collectMessages(nd, referenced);
  }
  return referenced;
}
 
Example 10
Source File: MessageDifferencer.java    From startup-os with Apache License 2.0 4 votes vote down vote up
@Override
public void report(
    ReportType type,
    Message message1,
    Message message2,
    ImmutableList<SpecificField> fieldPath) {
  try {
    if ((type == ReportType.MODIFIED) && !reportModifiedAggregates) {
      SpecificField specificField = Iterables.getLast(fieldPath);
      if (specificField.getField() == null) {
        if (specificField.getUnknown().getFieldType() == UnknownFieldType.GROUP) {
          // Any changes to the subfields have already been printed.
          return;
        }
      } else if (specificField.getField().getJavaType() == JavaType.MESSAGE) {
        // Any changes to the subfields have already been printed.
        return;
      }
    }
    String tentativeNewline = "";
    if (fieldPath.size() == 1) {
      tentativeNewline = "\n";
    }
    output.append(type.name().toLowerCase()).append(": ");
    switch (type) {
      case ADDED:
        appendPath(fieldPath, false);
        output.append(": ");
        appendValue(message2, fieldPath, false);
        break;
      case DELETED:
        appendPath(fieldPath, true);
        output.append(": ");
        appendValue(message1, fieldPath, true);
        break;
      case IGNORED:
        appendPath(fieldPath, false);
        break;
      case MOVED:
        appendPath(fieldPath, true);
        output.append(" -> ");
        appendPath(fieldPath, false);
        output.append(" : ");
        appendValue(message1, fieldPath, true);
        break;
      case MODIFIED:
        appendPath(fieldPath, true);
        if (checkPathChanged(fieldPath)) {
          output.append(" -> ");
          appendPath(fieldPath, false);
        }
        output.append(":" + tentativeNewline);
        appendValue(message1, fieldPath, true);
        output.append(" -> " + tentativeNewline);
        appendValue(message2, fieldPath, false);
        break;
      case MATCHED:
        appendPath(fieldPath, true);
        if (checkPathChanged(fieldPath)) {
          output.append(" -> ");
          appendPath(fieldPath, false);
        }
        output.append(" : ");
        appendValue(message1, fieldPath, true);
        break;
      default:
        throw new RuntimeException("Unknown ReportType");
    }
    output.append("\n" + tentativeNewline);
  } catch (IOException e) {
    throw new StreamException(e);
  }
}
 
Example 11
Source File: DoParse.java    From curiostack with MIT License 4 votes vote down vote up
/**
 * Returns the {@link StackManipulation} for setting the value of a map field.
 *
 * <p>Roughly equivalent to:
 *
 * <pre>{@code
 * ParseSupport.parseObjectStart(parser);
 * while (!ParseSupport.checkObjectEnd(parser.currentToken())) {
 *   builder.putFoo(readKey(), readValue());
 * }
 * }</pre>
 */
private StackManipulation setMapFieldValue(
    ProtoFieldInfo info,
    Label beforeReadField,
    LocalVariables<LocalVariable> locals,
    Map<String, FieldDescription> fieldsByName) {
  final StackManipulation setConcreteValue = invoke(info.setValueMethod());
  final StackManipulation setMapEntry;
  if (info.valueJavaType() == JavaType.MESSAGE) {
    setMapEntry =
        new StackManipulation.Compound(
            TypeCasting.to(new ForLoadedType(info.javaClass())), setConcreteValue);
  } else {
    setMapEntry = setConcreteValue;
  }
  Label mapStart = new Label();
  Label afterSet = new Label();

  StackManipulation.Compound beforeReadKey =
      new StackManipulation.Compound(
          locals.load(LocalVariable.parser),
          ParseSupport_parseObjectStart,
          new SetJumpTargetLabel(mapStart),
          locals.load(LocalVariable.parser),
          Parser_currentToken,
          ParseSupport_checkObjectEnd,
          new IfTrue(beforeReadField));

  StackManipulation.Compound setValueAndPrepareForNext =
      new StackManipulation.Compound(
          setMapEntry,
          Removal.SINGLE,
          new SetJumpTargetLabel(afterSet),
          locals.load(LocalVariable.parser),
          Parser_nextToken,
          Removal.SINGLE,
          new Goto(mapStart));

  if (info.valueType() == Type.ENUM) {
    // We special-case enum since we may need to skip unknown values.
    final LocalVariable keyVar;
    switch (info.mapKeyField().valueJavaType()) {
      case INT:
        keyVar = LocalVariable.intMapKey;
        break;
      case LONG:
        keyVar = LocalVariable.longMapKey;
        break;
      case BOOLEAN:
        keyVar = LocalVariable.boolMapKey;
        break;
      case STRING:
        keyVar = LocalVariable.stringMapKey;
        break;
      default:
        throw new IllegalArgumentException("Invalid map key type");
    }

    return new StackManipulation.Compound(
        beforeReadKey,
        locals.load(LocalVariable.parser),
        readValue(info.mapKeyField(), fieldsByName, locals),
        locals.store(keyVar),
        locals.load(LocalVariable.parser),
        Parser_nextToken,
        Removal.SINGLE,
        locals.load(LocalVariable.parser),
        readValue(info, fieldsByName, locals),
        locals.store(LocalVariable.intvalue),
        locals.load(LocalVariable.intvalue),
        IntegerConstant.forValue(-1),
        new IfEqual(int.class, afterSet),
        locals.load(LocalVariable.builder),
        locals.load(keyVar),
        locals.load(LocalVariable.intvalue),
        setValueAndPrepareForNext);
  } else {
    return new StackManipulation.Compound(
        beforeReadKey,
        locals.load(LocalVariable.builder),
        locals.load(LocalVariable.parser),
        readValue(info.mapKeyField(), fieldsByName, locals),
        locals.load(LocalVariable.parser),
        Parser_nextToken,
        Removal.SINGLE,
        locals.load(LocalVariable.parser),
        readValue(info, fieldsByName, locals),
        setValueAndPrepareForNext);
  }
}
 
Example 12
Source File: MessageSerializer.java    From jackson-datatype-protobuf with Apache License 2.0 4 votes vote down vote up
private static boolean supportsFieldPresence(FieldDescriptor field) {
  // messages still support field presence in proto3
  return field.getJavaType() == JavaType.MESSAGE;
}