Java Code Examples for com.google.protobuf.Descriptors.FieldDescriptor#getMessageType()

The following examples show how to use com.google.protobuf.Descriptors.FieldDescriptor#getMessageType() . 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: ProtobufRowConverter.java    From sql-layer with GNU Affero General Public License v3.0 6 votes vote down vote up
public GroupConverter(Group group, Descriptor groupMessage) {
    super(group.getRoot().getTableId(), groupMessage);
    Map<String,Table> tablesByUuid = new HashMap<>();
    getUuids(group.getRoot(), tablesByUuid);
    tableConvertersByTableId = new HashMap<>(tablesByUuid.size());
    groupFieldsByTabelId = new HashMap<>(tablesByUuid.size());
    tableConvertersByField = new HashMap<>(tablesByUuid.size());
    for (FieldDescriptor field : groupMessage.getFields()) {
        String uuid = field.getOptions().getExtension(ColumnOptions.fdbsql).getUuid();
        Table table = tablesByUuid.get(uuid);
        if (table != null) {
            ProtobufRowConverter converter = new TableConverter(table, field.getMessageType());
            tableConvertersByTableId.put(table.getTableId(), converter);
            groupFieldsByTabelId.put(table.getTableId(), field);
            tableConvertersByField.put(field, converter);
        }
    }
}
 
Example 2
Source File: ExtensionRegistry.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void add(final ExtensionInfo extension) {
  if (!extension.descriptor.isExtension()) {
    throw new IllegalArgumentException(
      "ExtensionRegistry.add() was given a FieldDescriptor for a regular " +
      "(non-extension) field.");
  }

  extensionsByName.put(extension.descriptor.getFullName(), extension);
  extensionsByNumber.put(
    new DescriptorIntPair(extension.descriptor.getContainingType(),
                          extension.descriptor.getNumber()),
    extension);

  final FieldDescriptor field = extension.descriptor;
  if (field.getContainingType().getOptions().getMessageSetWireFormat() &&
      field.getType() == FieldDescriptor.Type.MESSAGE &&
      field.isOptional() &&
      field.getExtensionScope() == field.getMessageType()) {
    // This is an extension of a MessageSet type defined within the extension
    // type's own scope.  For backwards-compatibility, allow it to be looked
    // up by type name.
    extensionsByName.put(field.getMessageType().getFullName(), extension);
  }
}
 
Example 3
Source File: ProtobufSerializer.java    From jackson-datatype-protobuf with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected void writeMap(
        FieldDescriptor field,
        Object entries,
        JsonGenerator generator,
        SerializerProvider serializerProvider
) throws IOException {
  Descriptor entryDescriptor = field.getMessageType();
  FieldDescriptor keyDescriptor = entryDescriptor.findFieldByName("key");
  FieldDescriptor valueDescriptor = entryDescriptor.findFieldByName("value");
  generator.writeStartObject();
  for (Message entry : (List<? extends Message>) entries) {
    // map keys can only be integers or strings so this should be fine
    generator.writeFieldName(entry.getField(keyDescriptor).toString());
    Object value = entry.getField(valueDescriptor);
    // map values can't be maps or repeated so this should be fine
    writeValue(valueDescriptor, value, generator, serializerProvider);
  }
  generator.writeEndObject();
}
 
Example 4
Source File: ProtoFieldInfo.java    From curiostack with MIT License 6 votes vote down vote up
ProtoFieldInfo(FieldDescriptor field, Message containingPrototype) {
  this.field = checkNotNull(field, "field");
  this.containingPrototype = checkNotNull(containingPrototype, "containingPrototype");
  builderClass = containingPrototype.newBuilderForType().getClass();

  camelCaseName = underscoresToUpperCamelCase(field.getName());

  if (field.isMapField()) {
    Descriptor mapType = field.getMessageType();
    mapKeyField = new ProtoFieldInfo(mapType.findFieldByName("key"), containingPrototype);
    mapValueField = new ProtoFieldInfo(mapType.findFieldByName("value"), containingPrototype);
  } else {
    mapKeyField = null;
    mapValueField = null;
  }
}
 
Example 5
Source File: MetaDataEvolutionValidator.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
private void validateField(@Nonnull FieldDescriptor oldFieldDescriptor, @Nonnull FieldDescriptor newFieldDescriptor,
                           @Nonnull Set<Pair<Descriptor, Descriptor>> seenDescriptors) {
    if (!oldFieldDescriptor.getName().equals(newFieldDescriptor.getName())) {
        // TODO: Field renaming should be allowed with some caveats about if the field is indexed or not
        throw new MetaDataException("field renamed",
                LogMessageKeys.OLD_FIELD_NAME, oldFieldDescriptor.getName(),
                LogMessageKeys.NEW_FIELD_NAME, newFieldDescriptor.getName());
    }
    if (!oldFieldDescriptor.getType().equals(newFieldDescriptor.getType())) {
        validateTypeChange(oldFieldDescriptor, newFieldDescriptor);
    }
    if (oldFieldDescriptor.isRequired() && !newFieldDescriptor.isRequired()) {
        throw new MetaDataException("required field is no longer required",
                LogMessageKeys.FIELD_NAME, oldFieldDescriptor.getName());
    } else if (oldFieldDescriptor.isOptional() && !newFieldDescriptor.isOptional()) {
        // TODO: In theory, optional -> repeated is okay, but only if the field is not indexed
        throw new MetaDataException("optional field is no longer optional",
                LogMessageKeys.FIELD_NAME, oldFieldDescriptor.getName());
    } else if (oldFieldDescriptor.isRepeated() && !newFieldDescriptor.isRepeated()) {
        throw new MetaDataException("repeated field is no longer repeated",
                LogMessageKeys.FIELD_NAME, oldFieldDescriptor.getName());
    }
    if (oldFieldDescriptor.getType().equals(FieldDescriptor.Type.ENUM)) {
        validateEnum(newFieldDescriptor.getName(), oldFieldDescriptor.getEnumType(), newFieldDescriptor.getEnumType());
    }
    if (oldFieldDescriptor.getType().equals(FieldDescriptor.Type.GROUP) || oldFieldDescriptor.getType().equals(FieldDescriptor.Type.MESSAGE)) {
        // Message types need to be validated against each other as well.
        final Descriptor oldMessageType = oldFieldDescriptor.getMessageType();
        final Descriptor newMessageType = newFieldDescriptor.getMessageType();
        validateMessage(oldMessageType, newMessageType, seenDescriptors);
    }
}
 
Example 6
Source File: DynamicMessage.java    From 365browser with Apache License 2.0 5 votes vote down vote up
public Builder newBuilderForField(FieldDescriptor field) {
  verifyContainingType(field);

  if (field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) {
    throw new IllegalArgumentException(
      "newBuilderForField is only valid for fields with message type.");
  }

  return new Builder(field.getMessageType());
}
 
Example 7
Source File: ProtobufDeserializer.java    From jackson-datatype-protobuf with Apache License 2.0 5 votes vote down vote up
protected List<Message> readMap(
        Message.Builder builder,
        FieldDescriptor field,
        JsonParser parser,
        DeserializationContext context
) throws IOException {
  if (parser.getCurrentToken() == JsonToken.VALUE_NULL) {
    // Seems like we should treat null as an empty map rather than fail?
    return Collections.emptyList();
  } else if (parser.getCurrentToken() != JsonToken.START_OBJECT) {
    throw reportWrongToken(
            JsonToken.START_OBJECT,
            context,
            "Can't parse map field out of " + parser.currentToken() + " token"
    );
  }

  Descriptor entryDescriptor = field.getMessageType();
  FieldDescriptor keyDescriptor = entryDescriptor.findFieldByName("key");
  FieldDescriptor valueDescriptor = entryDescriptor.findFieldByName("value");

  List<Message> entries = new ArrayList<>();
  while (parser.nextToken() != JsonToken.END_OBJECT) {
    Message.Builder entryBuilder = builder.newBuilderForField(field);
    Object key = readKey(keyDescriptor, parser, context);
    parser.nextToken(); // move from key to value
    Object value = readValue(entryBuilder, valueDescriptor, null, parser, context);

    entryBuilder.setField(keyDescriptor, key);
    entryBuilder.setField(valueDescriptor, value);
    entries.add(entryBuilder.build());
  }
  return entries;
}
 
Example 8
Source File: JsonJacksonFormat.java    From jigsaw-payment with Apache License 2.0 5 votes vote down vote up
private void printSingleField(FieldDescriptor field,
                                     Object value,
                                     JsonGenerator generator) throws IOException {
    if (field.isExtension()) {
        // We special-case MessageSet elements for compatibility with proto1.
        if (field.getContainingType().getOptions().getMessageSetWireFormat()
            && (field.getType() == FieldDescriptor.Type.MESSAGE) && (field.isOptional())
            // object equality
            && (field.getExtensionScope() == field.getMessageType())) {
            generator.writeFieldName(field.getMessageType().getFullName());
        } else {
        	// extensions will have '.' in them, while normal fields wont..
        	generator.writeFieldName(field.getFullName());
        }
    } else {
        if (field.getType() == FieldDescriptor.Type.GROUP) {
            // Groups must be serialized with their original capitalization.
            generator.writeFieldName(field.getMessageType().getName());
        } else {
            generator.writeFieldName(field.getName());
        }
    }

    // Done with the name, on to the value
    if (field.isRepeated()) {
        // Repeated field. Print each element.
        generator.writeStartArray();
        for (Iterator<?> iter = ((List<?>) value).iterator(); iter.hasNext();) {
            printFieldValue(field, iter.next(), generator);
        }
        generator.writeEndArray();
    } else {
        printFieldValue(field, value, generator);
    }
}
 
Example 9
Source File: CompatibilityTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testGetMessageType() throws Exception {
  Descriptor descriptor = TypicalData.Builder.getDescriptor();
  FieldDescriptor fieldDescriptor = descriptor.findFieldByNumber(11);
  Descriptor messageDescriptor = fieldDescriptor.getMessageType();
  assertNotNull(messageDescriptor);
  FieldDescriptor messageFieldDescriptor = messageDescriptor.findFieldByNumber(1);
  assertEquals(1, messageFieldDescriptor.getNumber());
}
 
Example 10
Source File: MapToMessage.java    From krpc with Apache License 2.0 5 votes vote down vote up
private static void objToMap(Builder b, FieldDescriptor field, Object map0)   {

        if( !(map0 instanceof  Map) ) return;

        Descriptors.Descriptor type = field.getMessageType();
        FieldDescriptor keyField = type.findFieldByName("key");
        FieldDescriptor valueField = type.findFieldByName("value");
        if (keyField != null && valueField != null) {

            Map map  = (Map)map0;
            for(Object e: map.entrySet() ) {
                Map.Entry entry = (Map.Entry)e;
                Object key = entry.getKey();
                Object value = entry.getValue();

                com.google.protobuf.Message.Builder entryBuilder = b.newBuilderForField(field);

                Object k = objToMessageObjInner(entryBuilder,key,keyField,false);
                Object v = objToMessageObjInner(entryBuilder,value,valueField,false);

                if(k == null || v == null ) continue;

                entryBuilder.setField(keyField, k);
                entryBuilder.setField(valueField, v);
                b.addRepeatedField(field, entryBuilder.build());
            }

        } else {
            throw new RuntimeException("Invalid map field");
        }
    }
 
Example 11
Source File: MetaDataEvolutionValidator.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("PMD.CompareObjectsWithEquals")
@Nonnull
private Map<String, String> getTypeRenames(@Nonnull Descriptor oldUnionDescriptor, @Nonnull Descriptor newUnionDescriptor) {
    if (oldUnionDescriptor == newUnionDescriptor) {
        return Collections.emptyMap();
    }

    final Map<String, String> renames = disallowTypeRenames ? Collections.emptyMap() : new HashMap<>();
    for (FieldDescriptor oldField : oldUnionDescriptor.getFields()) {
        Descriptor oldRecord = oldField.getMessageType();
        Descriptor newRecord = newUnionDescriptor.findFieldByNumber(oldField.getNumber()).getMessageType();
        if (!oldRecord.getName().equals(newRecord.getName())) {
            if (disallowTypeRenames) {
                throw new MetaDataException("record type name changed",
                        LogMessageKeys.OLD_RECORD_TYPE, oldRecord.getName(),
                        LogMessageKeys.NEW_RECORD_TYPE, newRecord.getName());
            }
            String existingName = renames.putIfAbsent(oldRecord.getName(), newRecord.getName());
            if (existingName != null && !existingName.equals(newRecord.getName())) {
                // This shouldn't be possible because of the validation done in validateUnion, but it's easy enough to check here.
                throw new MetaDataException("record type corresponds to multiple types in new meta-data",
                        LogMessageKeys.OLD_RECORD_TYPE, oldRecord.getName(),
                        LogMessageKeys.NEW_RECORD_TYPE, newRecord.getName() + " & " + existingName);
            }
        }
    }
    return renames;
}
 
Example 12
Source File: HtmlFormat.java    From jigsaw-payment with Apache License 2.0 4 votes vote down vote up
private void printSingleField(FieldDescriptor field,
                                     Object value,
                                     HtmlGenerator generator) throws IOException {
    if (field.isExtension()) {
        generator.print("[<span style=\"");
        generator.print(FIELD_NAME_STYLE);
        generator.print("\">");
        // We special-case MessageSet elements for compatibility with proto1.
        if (field.getContainingType().getOptions().getMessageSetWireFormat()
                        && (field.getType() == FieldDescriptor.Type.MESSAGE) && (field.isOptional())
                        // object equality
                        && (field.getExtensionScope() == field.getMessageType())) {
            generator.print(field.getMessageType().getFullName());
        } else {
            generator.print(field.getFullName());
        }
        generator.print("</span>]");
    } else {
        generator.print("<span style=\"");
        generator.print(FIELD_NAME_STYLE);
        generator.print("\">");
        if (field.getType() == FieldDescriptor.Type.GROUP) {
            // Groups must be serialized with their original capitalization.
            generator.print(field.getMessageType().getName());
        } else {
            generator.print(field.getName());
        }
        generator.print("</span>");
    }

    if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
        generator.print(" <span style=\"color: red;\">{</span><br/>");
        generator.indent();
    } else {
        generator.print(": ");
    }

    printFieldValue(field, value, generator);

    if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
        generator.outdent();
        generator.print("<span style=\"color: red;\">}</span>");
    }
    generator.print("<br/>");
}
 
Example 13
Source File: JsonFormat.java    From jigsaw-payment with Apache License 2.0 4 votes vote down vote up
private void printSingleField(FieldDescriptor field,
                                     Object value,
                                     JsonGenerator generator) throws IOException {
    if (field.isExtension()) {
        generator.print("\"");
        // We special-case MessageSet elements for compatibility with proto1.
        if (field.getContainingType().getOptions().getMessageSetWireFormat()
            && (field.getType() == FieldDescriptor.Type.MESSAGE) && (field.isOptional())
            // object equality
            && (field.getExtensionScope() == field.getMessageType())) {
            generator.print(field.getMessageType().getFullName());
        } else {
            generator.print(field.getFullName());
        }
        generator.print("\"");
    } else {
        generator.print("\"");
        if (field.getType() == FieldDescriptor.Type.GROUP) {
            // Groups must be serialized with their original capitalization.
            generator.print(field.getMessageType().getName());
        } else {
            generator.print(field.getName());
        }
        generator.print("\"");
    }

    // Done with the name, on to the value

    if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
        generator.print(": ");
        generator.indent();
    } else {
        generator.print(": ");
    }


    if (field.isRepeated()) {
        // Repeated field. Print each element.
        generator.print("[");
        for (Iterator<?> iter = ((List<?>) value).iterator(); iter.hasNext();) {
            printFieldValue(field, iter.next(), generator);
            if (iter.hasNext()) {
                generator.print(",");
            }
        }
        generator.print("]");
    } else {
        printFieldValue(field, value, generator);
        if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
            generator.outdent();
        }
    }
}
 
Example 14
Source File: TextFormat.java    From 365browser with Apache License 2.0 4 votes vote down vote up
private void printSingleField(final FieldDescriptor field,
                              final Object value,
                              final TextGenerator generator)
                              throws IOException {
  if (field.isExtension()) {
    generator.print("[");
    // We special-case MessageSet elements for compatibility with proto1.
    if (field.getContainingType().getOptions().getMessageSetWireFormat()
        && (field.getType() == FieldDescriptor.Type.MESSAGE)
        && (field.isOptional())
        // object equality
        && (field.getExtensionScope() == field.getMessageType())) {
      generator.print(field.getMessageType().getFullName());
    } else {
      generator.print(field.getFullName());
    }
    generator.print("]");
  } else {
    if (field.getType() == FieldDescriptor.Type.GROUP) {
      // Groups must be serialized with their original capitalization.
      generator.print(field.getMessageType().getName());
    } else {
      generator.print(field.getName());
    }
  }

  if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
    if (singleLineMode) {
      generator.print(" { ");
    } else {
      generator.print(" {\n");
      generator.indent();
    }
  } else {
    generator.print(": ");
  }

  printFieldValue(field, value, generator);

  if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
    if (singleLineMode) {
      generator.print("} ");
    } else {
      generator.outdent();
      generator.print("}\n");
    }
  } else {
    if (singleLineMode) {
      generator.print(" ");
    } else {
      generator.print("\n");
    }
  }
}
 
Example 15
Source File: TextFormat.java    From android-chromium with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void printSingleField(final FieldDescriptor field,
                              final Object value,
                              final TextGenerator generator)
                              throws IOException {
  if (field.isExtension()) {
    generator.print("[");
    // We special-case MessageSet elements for compatibility with proto1.
    if (field.getContainingType().getOptions().getMessageSetWireFormat()
        && (field.getType() == FieldDescriptor.Type.MESSAGE)
        && (field.isOptional())
        // object equality
        && (field.getExtensionScope() == field.getMessageType())) {
      generator.print(field.getMessageType().getFullName());
    } else {
      generator.print(field.getFullName());
    }
    generator.print("]");
  } else {
    if (field.getType() == FieldDescriptor.Type.GROUP) {
      // Groups must be serialized with their original capitalization.
      generator.print(field.getMessageType().getName());
    } else {
      generator.print(field.getName());
    }
  }

  if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
    if (singleLineMode) {
      generator.print(" { ");
    } else {
      generator.print(" {\n");
      generator.indent();
    }
  } else {
    generator.print(": ");
  }

  printFieldValue(field, value, generator);

  if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
    if (singleLineMode) {
      generator.print("} ");
    } else {
      generator.outdent();
      generator.print("}\n");
    }
  } else {
    if (singleLineMode) {
      generator.print(" ");
    } else {
      generator.print("\n");
    }
  }
}
 
Example 16
Source File: ProtobufJsonFormat.java    From incubator-tajo with Apache License 2.0 4 votes vote down vote up
private void printSingleField(FieldDescriptor field,
                              Object value,
                              JsonGenerator generator) throws IOException {
  if (field.isExtension()) {
    generator.print("\"");
    // We special-case MessageSet elements for compatibility with proto1.
    if (field.getContainingType().getOptions().getMessageSetWireFormat()
        && (field.getType() == FieldDescriptor.Type.MESSAGE) && (field.isOptional())
        // object equality
        && (field.getExtensionScope() == field.getMessageType())) {
      generator.print(field.getMessageType().getFullName());
    } else {
      generator.print(field.getFullName());
    }
    generator.print("\"");
  } else {
    generator.print("\"");
    if (field.getType() == FieldDescriptor.Type.GROUP) {
      // Groups must be serialized with their original capitalization.
      generator.print(field.getMessageType().getName());
    } else {
      generator.print(field.getName());
    }
    generator.print("\"");
  }

  // Done with the name, on to the value

  if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
    generator.print(": ");
    generator.indent();
  } else {
    generator.print(": ");
  }


  if (field.isRepeated()) {
    // Repeated field. Print each element.
    generator.print("[");
    for (Iterator<?> iter = ((List<?>) value).iterator(); iter.hasNext();) {
      printFieldValue(field, iter.next(), generator);
      if (iter.hasNext()) {
        generator.print(",");
      }
    }
    generator.print("]");
  } else {
    printFieldValue(field, value, generator);
    if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
      generator.outdent();
    }
  }
}
 
Example 17
Source File: TextFormat.java    From play-store-api with GNU General Public License v3.0 4 votes vote down vote up
private void printSingleField(final FieldDescriptor field,
                              final Object value,
                              final TextGenerator generator)
                              throws IOException {
  if (field.isExtension()) {
    generator.print("[");
    // We special-case MessageSet elements for compatibility with proto1.
    if (field.getContainingType().getOptions().getMessageSetWireFormat()
        && (field.getType() == FieldDescriptor.Type.MESSAGE)
        && (field.isOptional())
        // object equality
        && (field.getExtensionScope() == field.getMessageType())) {
      generator.print(field.getMessageType().getFullName());
    } else {
      generator.print(field.getFullName());
    }
    generator.print("]");
  } else {
    if (field.getType() == FieldDescriptor.Type.GROUP) {
      // Groups must be serialized with their original capitalization.
      generator.print(field.getMessageType().getName());
    } else {
      generator.print(field.getName());
    }
  }

  if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
    if (singleLineMode) {
      generator.print(" { ");
    } else {
      generator.print(" {\n");
      generator.indent();
    }
  } else {
    generator.print(": ");
  }

  printFieldValue(field, value, generator);

  if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
    if (singleLineMode) {
      generator.print("} ");
    } else {
      generator.outdent();
      generator.print("}\n");
    }
  } else {
    if (singleLineMode) {
      generator.print(" ");
    } else {
      generator.print("\n");
    }
  }
}
 
Example 18
Source File: ProtobufJsonFormat.java    From tajo with Apache License 2.0 4 votes vote down vote up
private void printSingleField(FieldDescriptor field,
                              Object value,
                              JsonGenerator generator) throws IOException {
  if (field.isExtension()) {
    generator.print("\"");
    // We special-case MessageSet elements for compatibility with proto1.
    if (field.getContainingType().getOptions().getMessageSetWireFormat()
        && (field.getType() == FieldDescriptor.Type.MESSAGE) && (field.isOptional())
        // object equality
        && (field.getExtensionScope() == field.getMessageType())) {
      generator.print(field.getMessageType().getFullName());
    } else {
      generator.print(field.getFullName());
    }
    generator.print("\"");
  } else {
    generator.print("\"");
    if (field.getType() == FieldDescriptor.Type.GROUP) {
      // Groups must be serialized with their original capitalization.
      generator.print(field.getMessageType().getName());
    } else {
      generator.print(field.getName());
    }
    generator.print("\"");
  }

  // Done with the name, on to the value

  if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
    generator.print(": ");
    generator.indent();
  } else {
    generator.print(": ");
  }


  if (field.isRepeated()) {
    // Repeated field. Print each element.
    generator.print("[");
    for (Iterator<?> iter = ((List<?>) value).iterator(); iter.hasNext();) {
      printFieldValue(field, iter.next(), generator);
      if (iter.hasNext()) {
        generator.print(",");
      }
    }
    generator.print("]");
  } else {
    printFieldValue(field, value, generator);
    if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
      generator.outdent();
    }
  }
}
 
Example 19
Source File: JsonFormat.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void printSingleField(FieldDescriptor field,
                                     Object value, JsonGenerator generator, boolean selfType) throws IOException {
    if (field.isExtension()) {
        generator.print("\"");
        // We special-case MessageSet elements for compatibility with proto1.
        if (field.getContainingType().getOptions().getMessageSetWireFormat()
                && (field.getType() == FieldDescriptor.Type.MESSAGE) && (field.isOptional())
                // object equality
                && (field.getExtensionScope() == field.getMessageType())) {
            generator.print(field.getMessageType().getFullName());
        } else {
            generator.print(field.getFullName());
        }
        generator.print("\"");
    } else {
        generator.print("\"");
        if (field.getType() == FieldDescriptor.Type.GROUP) {
            // Groups must be serialized with their original capitalization.
            generator.print(field.getMessageType().getName());
        } else {
            generator.print(field.getName());
        }
        generator.print("\"");
    }

    // Done with the name, on to the value

    if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
        generator.print(": ");
        generator.indent();
    } else {
        generator.print(": ");
    }

    if (field.isRepeated()) {
        // Repeated field. Print each element.
        generator.print("[");
        for (Iterator<?> iter = ((List<?>) value).iterator(); iter.hasNext(); ) {
            printFieldValue(field, iter.next(), generator, selfType);
            if (iter.hasNext()) {
                generator.print(",");
            }
        }
        generator.print("]");
    } else {
        printFieldValue(field, value, generator, selfType);
        if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
            generator.outdent();
        }
    }
}
 
Example 20
Source File: MetaDataEvolutionValidator.java    From fdb-record-layer with Apache License 2.0 4 votes vote down vote up
/**
 * Validate that the record types have all been evolved in a legal way. In particular, this makes sure that
 * each record type defined in the union descriptor is in the new union descriptor in the correct
 * place. It will then verify that each message type has been updated in a legal way, i.e., that it only
 * includes new fields.
 *
 * @param oldUnionDescriptor the union descriptor for the existing meta-data for some record store
 * @param newUnionDescriptor the new proposed meta-data
 */
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public void validateUnion(@Nonnull Descriptor oldUnionDescriptor, @Nonnull Descriptor newUnionDescriptor) {
    if (oldUnionDescriptor == newUnionDescriptor) {
        // Don't bother validating the record types if they are all the same.
        return;
    }
    final BiMap<Descriptor, Descriptor> updatedDescriptors = HashBiMap.create(oldUnionDescriptor.getFields().size());
    final Set<Pair<Descriptor, Descriptor>> seenDescriptors = new HashSet<>();

    for (FieldDescriptor oldUnionField : oldUnionDescriptor.getFields()) {
        if (!oldUnionField.getType().equals(FieldDescriptor.Type.MESSAGE)) {
            throw new MetaDataException("field in union is not a message type", LogMessageKeys.FIELD_NAME, oldUnionField.getName());
        }
        int fieldNumber = oldUnionField.getNumber();
        FieldDescriptor newUnionField = newUnionDescriptor.findFieldByNumber(fieldNumber);
        if (newUnionField != null) {
            if (!newUnionField.getType().equals(FieldDescriptor.Type.MESSAGE)) {
                throw new MetaDataException("field in new union is not a message type", LogMessageKeys.FIELD_NAME, newUnionField.getName());
            }
            Descriptor oldRecord = oldUnionField.getMessageType();
            Descriptor newRecord = newUnionField.getMessageType();

            // Verify that all fields of the same type in the old union are also of the same type
            // in the new union (i.e., that there are no "splits" or "merges" of record types).
            Descriptor alreadySeenNewRecord = updatedDescriptors.get(oldRecord);
            if (alreadySeenNewRecord != null) {
                if (alreadySeenNewRecord != newRecord) {
                    // A "split" -- the same type in the old union points to two different types in the new union
                    throw new MetaDataException("record type corresponds to multiple types in new meta-data",
                            LogMessageKeys.OLD_RECORD_TYPE, oldRecord.getName(),
                            LogMessageKeys.NEW_RECORD_TYPE, newRecord.getName() + " & " + alreadySeenNewRecord.getName());
                }
            } else {
                if (updatedDescriptors.containsValue(newRecord)) {
                    // A "merge" -- two different types in the old union point to the same type in the new union
                    final Descriptor alreadySeenOldRecord = updatedDescriptors.inverse().get(newRecord);
                    throw new MetaDataException("record type corresponds to multiple types in old meta-data",
                            LogMessageKeys.OLD_RECORD_TYPE, oldRecord.getName() + " & " + alreadySeenOldRecord.getName(),
                            LogMessageKeys.NEW_RECORD_TYPE, newRecord.getName());
                }
            }
            updatedDescriptors.put(oldRecord, newRecord);

            // Validate the form of the old and new record types
            validateMessage(oldRecord, newRecord, seenDescriptors);
        } else {
            throw new MetaDataException("record type removed from union", LogMessageKeys.RECORD_TYPE, oldUnionField.getMessageType());
        }
    }
}