com.google.protobuf.Descriptors Java Examples

The following examples show how to use com.google.protobuf.Descriptors. 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: DataVerifyPbOneof.java    From xresloader with MIT License 6 votes vote down vote up
public DataVerifyPbOneof(Descriptors.OneofDescriptor desc) {
    super(desc.getName());

    for (Descriptors.FieldDescriptor fd : desc.getFields()) {

        all_names.put(fd.getName(), (long) fd.getNumber());
        all_numbers.add((long) fd.getNumber());

        // alias extension
        if (fd.getOptions().hasExtension(Xresloader.fieldAlias)) {
            String alias_name = fd.getOptions().getExtension(Xresloader.fieldAlias);
            if (!alias_name.isEmpty()) {
                all_names.put(alias_name, (long) fd.getNumber());
            }
        }
    }
}
 
Example #2
Source File: RecordMetaDataBuilder.java    From fdb-record-layer with Apache License 2.0 6 votes vote down vote up
private void fillUnionFields(boolean processExtensionOptions) {
    if (unionDescriptor == null) {
        throw new RecordCoreException("cannot fill union fiends as no union descriptor has been set");
    }
    if (!unionFields.isEmpty()) {
        throw new RecordCoreException("cannot set union fields twice");
    }
    for (Descriptors.FieldDescriptor unionField : unionDescriptor.getFields()) {
        Descriptors.Descriptor descriptor = unionField.getMessageType();
        if (!unionFields.containsKey(descriptor)) {
            processRecordType(unionField, processExtensionOptions);
            unionFields.put(descriptor, unionField);
        } else {
            // The preferred field is the last one, except if there is one whose name matches.
            remapUnionField(descriptor, unionField);
        }
    }
}
 
Example #3
Source File: DataDstPb.java    From xresloader with MIT License 6 votes vote down vote up
static Descriptors.FileDescriptor try_get_inner_deile_desc(String name) {
    if (inner_file_descs != null) {
        return inner_file_descs.getOrDefault(name.replace('\\', '/').toLowerCase(), null);
    }

    Descriptors.FileDescriptor[] inner_descs = new Descriptors.FileDescriptor[] { Xresloader.getDescriptor(),
            XresloaderUe.getDescriptor(), PbHeaderV3.getDescriptor(), DescriptorProtos.getDescriptor(),
            DurationProto.getDescriptor(), TimestampProto.getDescriptor(), AnyProto.getDescriptor(),
            ApiProto.getDescriptor(), EmptyProto.getDescriptor(), FieldMaskProto.getDescriptor(),
            StructProto.getDescriptor(), TypeProto.getDescriptor(), WrappersProto.getDescriptor(),
            SourceContextProto.getDescriptor(), };

    inner_file_descs = new HashMap<String, Descriptors.FileDescriptor>();
    for (Descriptors.FileDescriptor innerFileDesc : inner_descs) {
        inner_file_descs.put(innerFileDesc.getName().replace('\\', '/').toLowerCase(), innerFileDesc);
    }

    return inner_file_descs.getOrDefault(name.toLowerCase(), null);
}
 
Example #4
Source File: MessageValue.java    From fdb-record-layer with Apache License 2.0 6 votes vote down vote up
/**
 * Get the value of the field with the given field name on the given message.
 * If the field is repeated, the repeated values are combined into a list. If the field has a message type,
 * the value is returned as a {@link Message} of that type. Otherwise, the field is returned as a primitive.
 * @param message a message or builder to extract the field from
 * @param fieldName the field to extract
 * @return the value of the field as described above
 */
@Nullable
public static Object getFieldOnMessage(@Nonnull MessageOrBuilder message, @Nonnull String fieldName) {
    final Descriptors.FieldDescriptor field = findFieldDescriptorOnMessage(message, fieldName);
    if (field.isRepeated()) {
        int count = message.getRepeatedFieldCount(field);
        List<Object> list = new ArrayList<>(count);
        for (int i = 0; i < count; i++) {
            list.add(message.getRepeatedField(field, i));
        }
        return list;
    }
    if (field.hasDefaultValue() || message.hasField(field)) {
        if (field.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE &&
                TupleFieldsHelper.isTupleField(field.getMessageType())) {
            return TupleFieldsHelper.fromProto((Message)message.getField(field), field.getMessageType());
        } else {
            return message.getField(field);
        }
    } else {
        return null;
    }
}
 
Example #5
Source File: ProtoDiff.java    From metastore with Apache License 2.0 6 votes vote down vote up
private EnumValueChangeInfo diffEnumValue(
    Descriptors.EnumValueDescriptor f_ref, Descriptors.EnumValueDescriptor f_new) {
  diffOptionsFromEnumValue(f_ref, f_new);
  EnumValueChangeInfo.Builder builder = EnumValueChangeInfo.newBuilder();

  if (!f_ref.getName().equals(f_new.getName())) {
    builder.setChangeType(ChangeType.CHANGED);
    builder.setFromName(f_ref.getName());
    builder.setToName(f_new.getName());
  }
  if (isDeprecated(f_ref) != isDeprecated(f_new)) {
    builder.setChangeType(ChangeType.CHANGED);
    builder.setFromDeprecated(isDeprecated(f_ref));
    builder.setToDeprecated(isDeprecated(f_new));
  }

  if (builder.getChangeType().equals(ChangeType.CHANGED)) {
    return builder.build();
  }
  return null;
}
 
Example #6
Source File: DataDstPb.java    From xresloader with MIT License 6 votes vote down vote up
static private LinkedList<DataVerifyImpl> setup_verifier(Descriptors.Descriptor container,
        Descriptors.OneofDescriptor fd) {
    LinkedList<DataVerifyImpl> ret = new LinkedList<DataVerifyImpl>();

    String rule = String.format("%s.%s.%s", container.getFile().getPackage(), container.getName(), fd.getName());
    if (rule.length() > 0 && rule.charAt(0) == '.') {
        rule = rule.substring(1);
    }
    {
        DataVerifyImpl vfy = cachePbs.identifiers.getOrDefault(rule, null);
        // 命中缓存
        if (null != vfy) {
            ret.add(vfy);
            return ret;
        }
    }

    DataVerifyPbOneof new_vfy = new DataVerifyPbOneof(fd);
    cachePbs.identifiers.put(rule, new_vfy);
    ret.add(new_vfy);

    return ret;
}
 
Example #7
Source File: ProtoLanguageFileWriter.java    From metastore with Apache License 2.0 6 votes vote down vote up
private void writeOptionForBlock(
    Descriptors.FieldDescriptor fieldDescriptor, Object value, int indent, String optionType) {
  indent(indent);
  writer.print("option ");
  if (fieldDescriptor.getFullName().startsWith("google.protobuf." + optionType + "Options")) {
    writer.print(fieldDescriptor.getName());
  } else {
    writer.print("(");
    writer.print(fieldDescriptor.getFullName());
    writer.print(")");
  }
  writer.print(" = ");
  if (fieldDescriptor.getType() == Descriptors.FieldDescriptor.Type.MESSAGE) {
    writeMessageValue((Message) value, indent);
  } else {
    writeValue(fieldDescriptor, value);
  }
  writer.println(";");
}
 
Example #8
Source File: ProtobufDataParserFactory.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Override
public DataParser getParser(String id, InputStream is, String offset) throws DataParserException {
  try {
    return new ProtobufDataParser(
        getSettings().getContext(),
        id,
        descriptor,
        messageTypeToExtensionMap,
        extensionRegistry,
        is,
        offset,
        getSettings().getOverRunLimit(),
        isDelimited
    );
  } catch (IOException | Descriptors.DescriptorValidationException e) {
    throw new DataParserException(Errors.DATA_PARSER_01, e.toString(), e);
  }
}
 
Example #9
Source File: ProtobufUtils.java    From envelope with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a named {@code Message} from a {@code .desc} file into a {@code Descriptor}.
 * <p>
 * This will parse the {@code .desc} file and then extract the encapsulated
 * {@link com.google.protobuf.Descriptors.Descriptor} the designated {@link Message} from the resulting parent
 * {@link Descriptors.FileDescriptor}.
 *
 * @param filePath the location of the .desc file
 * @param messageName the name of the Message
 * @return the constructed Descriptor
 */
public static Descriptors.Descriptor buildDescriptor(String filePath, String messageName) {
  Descriptors.FileDescriptor fileDescriptor = parseFileDescriptor(filePath);
  Descriptors.Descriptor result = null;

  for (Descriptors.Descriptor descriptor : fileDescriptor.getMessageTypes()) {
    if (descriptor.getName().equals(messageName)) {
      result = descriptor;
    }
  }

  if (null == result) {
    throw new RuntimeException("Unable to locate Message '" + messageName + "' in Descriptor");
  }

  return result;
}
 
Example #10
Source File: ProtobufSchema.java    From pulsar with Apache License 2.0 6 votes vote down vote up
private String getParsingInfo(T protoMessageInstance) {
    List<ProtoBufParsingInfo> protoBufParsingInfos = new LinkedList<>();
    protoMessageInstance.getDescriptorForType().getFields().forEach(new Consumer<Descriptors.FieldDescriptor>() {
        @Override
        public void accept(Descriptors.FieldDescriptor fieldDescriptor) {
            protoBufParsingInfos.add(new ProtoBufParsingInfo(fieldDescriptor.getNumber(),
                    fieldDescriptor.getName(), fieldDescriptor.getType().name(),
                    fieldDescriptor.toProto().getLabel().name(), null));
        }
    });

    try {
        return new ObjectMapper().writeValueAsString(protoBufParsingInfos);
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #11
Source File: ProtobufUtils.java    From envelope with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves and converts Protobuf fields from a Message.
 * <p>
 * If the field in the {@link com.google.protobuf.Descriptors.Descriptor} exists in the {@link Message}, the value is
 * retrieved and converted using {@link #getFieldValue(Descriptors.FieldDescriptor, Object, DataType)}.
 * Otherwise, the field value is {@code null}.
 * The extraction honors the order of the {@code Descriptor}.
 *
 * @param dsc the Protobuf Descriptor with all fields
 * @param msg the Message with the current field values
 * @param schema the Dataset schema derived from the Descriptor
 * @return a list of converted values
 */
public static List<Object> buildRowValues(Descriptors.Descriptor dsc, Message msg, StructType schema) {
  List<Object> values = new ArrayList<>();
  Object val;

  for (Descriptors.FieldDescriptor fd : dsc.getFields()) {
    if ( (!fd.isRepeated() && msg.hasField(fd)) || (fd.isRepeated() && msg.getRepeatedFieldCount(fd) > 0) ) {
      val = getFieldValue(fd, msg.getField(fd), schema.apply(fd.getName()).dataType());
    } else {
      LOG.trace("FieldDescriptor[{}] => not found", fd.getFullName());
      val = null;
    }
    values.add(val);
  }

  return values;
}
 
Example #12
Source File: ProtoDomain.java    From metastore with Apache License 2.0 6 votes vote down vote up
public Collection<Descriptors.EnumDescriptor> findEnumDescriptorsByOption(String optionName) {
  Descriptors.FieldDescriptor fieldDescriptor = optionsCatalog.getEnumOptionByName(optionName);
  return enumMap.values().stream()
      .filter(
          descriptor -> {
            DescriptorProtos.EnumOptions options = descriptor.getOptions();
            UnknownFieldSet.Field unknown =
                options.getUnknownFields().getField(fieldDescriptor.getNumber());
            if (unknown.getLengthDelimitedList().size()
                    + unknown.getFixed64List().size()
                    + unknown.getFixed32List().size()
                    + unknown.getVarintList().size()
                > 0) {
              return true;
            }
            return options.getAllFields().containsKey(fieldDescriptor);
          })
      .collect(Collectors.toList());
}
 
Example #13
Source File: ProtobufHttpMessageWriter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Mono<Void> write(Publisher<? extends Message> inputStream, ResolvableType elementType,
		@Nullable MediaType mediaType, ReactiveHttpOutputMessage message, Map<String, Object> hints) {

	try {
		Message.Builder builder = getMessageBuilder(elementType.toClass());
		Descriptors.Descriptor descriptor = builder.getDescriptorForType();
		message.getHeaders().add(X_PROTOBUF_SCHEMA_HEADER, descriptor.getFile().getName());
		message.getHeaders().add(X_PROTOBUF_MESSAGE_HEADER, descriptor.getFullName());
		if (inputStream instanceof Flux) {
			if (mediaType == null) {
				message.getHeaders().setContentType(((HttpMessageEncoder<?>)getEncoder()).getStreamingMediaTypes().get(0));
			}
			else if (!ProtobufEncoder.DELIMITED_VALUE.equals(mediaType.getParameters().get(ProtobufEncoder.DELIMITED_KEY))) {
				Map<String, String> parameters = new HashMap<>(mediaType.getParameters());
				parameters.put(ProtobufEncoder.DELIMITED_KEY, ProtobufEncoder.DELIMITED_VALUE);
				message.getHeaders().setContentType(new MediaType(mediaType.getType(), mediaType.getSubtype(), parameters));
			}
		}
		return super.write(inputStream, elementType, mediaType, message, hints);
	}
	catch (Exception ex) {
		return Mono.error(new DecodingException("Could not read Protobuf message: " + ex.getMessage(), ex));
	}
}
 
Example #14
Source File: ProtoMessageConverter.java    From parquet-mr with Apache License 2.0 6 votes vote down vote up
public ListConverter(Message.Builder parentBuilder, Descriptors.FieldDescriptor fieldDescriptor, Type parquetType) {
  LogicalTypeAnnotation logicalTypeAnnotation = parquetType.getLogicalTypeAnnotation();
  if (!(logicalTypeAnnotation instanceof LogicalTypeAnnotation.ListLogicalTypeAnnotation) || parquetType.isPrimitive()) {
    throw new ParquetDecodingException("Expected LIST wrapper. Found: " + logicalTypeAnnotation + " instead.");
  }

  GroupType rootWrapperType = parquetType.asGroupType();
  if (!rootWrapperType.containsField("list") || rootWrapperType.getType("list").isPrimitive()) {
    throw new ParquetDecodingException("Expected repeated 'list' group inside LIST wrapperr but got: " + rootWrapperType);
  }

  GroupType listType = rootWrapperType.getType("list").asGroupType();
  if (!listType.containsField("element")) {
    throw new ParquetDecodingException("Expected 'element' inside repeated list group but got: " + listType);
  }

  Type elementType = listType.getType("element");
  converter = newMessageConverter(parentBuilder, fieldDescriptor, elementType);
}
 
Example #15
Source File: TestProtobufUtils.java    From envelope with Apache License 2.0 6 votes vote down vote up
private static Descriptors.Descriptor marshalDescriptor(String desc) {
  DescriptorProtos.FileDescriptorSet fileDescriptorSet;

  try (BufferedInputStream dscFile = new BufferedInputStream(new FileInputStream(
      TestProtobufUtils.class.getResource(desc).getPath()
  ))) {
    fileDescriptorSet = DescriptorProtos.FileDescriptorSet.parseFrom(dscFile);
  } catch (Throwable throwable) {
    throw new RuntimeException("Unable to construct test resources", throwable);
  }

  // Get the attached .proto file
  DescriptorProtos.FileDescriptorProto descriptorProto = fileDescriptorSet.getFile(0);

  try {
    Descriptors.FileDescriptor fileDescriptor =  Descriptors.FileDescriptor.buildFrom(descriptorProto,
        new Descriptors.FileDescriptor[]{});
    if (fileDescriptor.getMessageTypes().isEmpty()) {
      throw new RuntimeException("No MessageTypes returned, " + fileDescriptor.getName());
    }

    return fileDescriptor.getMessageTypes().get(0);
  } catch (Descriptors.DescriptorValidationException e) {
    throw new RuntimeException("Error constructing FileDescriptor", e);
  }
}
 
Example #16
Source File: FDBMetaDataStoreTest.java    From fdb-record-layer with Apache License 2.0 6 votes vote down vote up
private static void validateInnerRecordsInRightPlaces(@Nonnull RecordMetaData metaData) {
    Descriptors.FileDescriptor recordsDescriptor = metaData.getRecordsDescriptor();
    Descriptors.Descriptor innerRecord = recordsDescriptor.findMessageTypeByName("InnerRecord");
    assertNotNull(innerRecord);
    Descriptors.Descriptor outerRecord = recordsDescriptor.findMessageTypeByName("OuterRecord");
    assertNotNull(outerRecord);
    Descriptors.Descriptor middleRecord = outerRecord.findNestedTypeByName("MiddleRecord");
    assertNotNull(middleRecord);
    Descriptors.Descriptor nestedInnerRecord = middleRecord.findNestedTypeByName("InnerRecord");
    assertNotNull(nestedInnerRecord);
    Descriptors.FieldDescriptor innerField = outerRecord.findFieldByName("inner");
    assertSame(nestedInnerRecord, innerField.getMessageType());
    assertNotSame(innerRecord, innerField.getMessageType());
    Descriptors.FieldDescriptor nestedInnerField = outerRecord.findFieldByName("inner");
    assertSame(nestedInnerRecord, nestedInnerField.getMessageType());
    assertNotSame(innerRecord, nestedInnerField.getMessageType());
}
 
Example #17
Source File: DataDstPb.java    From xresloader with MIT License 6 votes vote down vote up
private void dumpValue(DynamicMessage.Builder builder, Descriptors.FieldDescriptor fd, Object val) {
    if (JavaType.ENUM == fd.getJavaType()) {
        Descriptors.EnumValueDescriptor enum_val = null;
        if (val instanceof Descriptors.EnumValueDescriptor) {
            enum_val = (Descriptors.EnumValueDescriptor) val;
        } else {
            val = get_enum_value(cachePbs, fd.getEnumType(), (Integer) val);
        }

        if (null == enum_val) {
            return;
        }

        if (fd.isRepeated()) {
            builder.addRepeatedField(fd, enum_val);
        } else {
            builder.setField(fd, enum_val);
        }
    } else {
        if (fd.isRepeated()) {
            builder.addRepeatedField(fd, val);
        } else {
            builder.setField(fd, val);
        }
    }
}
 
Example #18
Source File: MessageToBean.java    From krpc with Apache License 2.0 6 votes vote down vote up
static public Map<Descriptors.FieldDescriptor, Object> getFields(MessageOrBuilder message, boolean withDefaultValue) {
        if (!withDefaultValue) {
            return message.getAllFields();
        }
        Map<Descriptors.FieldDescriptor, Object> fieldsToPrint = new LinkedHashMap<>();
        for (Descriptors.FieldDescriptor field : message.getDescriptorForType().getFields()) {
            if (field.isOptional()) {
                if (field.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE && !message.hasField(field)) {
                    continue;
                }
//                if (field.getJavaType() == Descriptors.FieldDescriptor.JavaType.STRING && !message.hasField(field)) {
//                    continue;
//                }
            }
            fieldsToPrint.put(field, message.getField(field));
        }
        return fieldsToPrint;
    }
 
Example #19
Source File: ProtoDomainTest.java    From metastore with Apache License 2.0 5 votes vote down vote up
@Test
public void getFileOptionByName() throws IOException {
  ProtoDomain domain = TestSets.baseAddFileOption();
  Descriptors.FieldDescriptor fd =
      domain.getOptions().getFileOptionByName("test.v1.file_option_1");
  Assert.assertEquals("test.v1.file_option_1", fd.getFullName());
}
 
Example #20
Source File: GrpcList.java    From karate-grpc with MIT License 5 votes vote down vote up
/**
 * Create a readable string from the field to help the user build a message.
 */
private static Object renderFieldDescriptor(Descriptors.FieldDescriptor descriptor) {
    switch (descriptor.getJavaType()) {
        case MESSAGE:
            return renderDescriptor(descriptor.getMessageType());
        case ENUM:
            return descriptor.getEnumType().getValues();
        default:
            return descriptor.getJavaType();
    }
}
 
Example #21
Source File: JavaPropsFormat.java    From jigsaw-payment with Apache License 2.0 5 votes vote down vote up
public String printFieldToString(final Descriptors.FieldDescriptor field,
                                        final Object value) {
  try {
    final StringBuilder text = new StringBuilder();
    printField(field, value, text);
    return text.toString();
  } catch (IOException e) {
    throw new RuntimeException(
      "Writing to a StringBuilder threw an IOException (should never " +
      "happen).", e);
  }
}
 
Example #22
Source File: GrpcList.java    From karate-grpc with MIT License 5 votes vote down vote up
/**
 * List the methods on the service (the mothodFilter will be applied if non empty.
 */
private static void listMethods(
        Map<String, Object> output,
        Descriptors.ServiceDescriptor descriptor,
        String methodFilter,
        Boolean withMessage,
        Boolean saveOutputInfo) {
    List<Descriptors.MethodDescriptor> methodDescriptors = descriptor.getMethods();

    methodDescriptors.forEach(method -> {
        if (methodFilter.isEmpty() || method.getName().contains(methodFilter)) {
            String key = descriptor.getFullName() + "/" + method.getName();

            Map<String, Object> res = new HashMap<>();
            res.put("file", descriptor.getFile().getName());

            // If requested, add the message definition
            if (withMessage) {
                Map<String, Object> o = new HashMap<>();
                o.put(method.getInputType().getName(), renderDescriptor(method.getInputType()));
                res.put("input", o);
                if (saveOutputInfo) {
                    Map<String, Object> oo = new HashMap<>();
                    oo.put(method.getOutputType().getName(), renderDescriptor(method.getOutputType()));
                    res.put("output", oo);
                }
            }
            output.put(key, res);
        }
    });
}
 
Example #23
Source File: ProtoDomainTest.java    From metastore with Apache License 2.0 5 votes vote down vote up
@Test
public void findDescriptorsByOption() throws IOException {
  ProtoDomain domain = TestSets.baseMultipleOptions();
  Collection<Descriptors.Descriptor> options =
      domain.findDescriptorsByOption("test.v1.message_option");
  Assert.assertEquals(1, options.size());
}
 
Example #24
Source File: IndexKeyValueToPartialRecord.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
public void addRequiredMessageFields() {
    for (Descriptors.FieldDescriptor fieldDescriptor : recordDescriptor.getFields()) {
        if (fieldDescriptor.isRequired() && fieldDescriptor.getType() == Descriptors.FieldDescriptor.Type.MESSAGE) {
            nestedBuilders.putIfAbsent(fieldDescriptor.getName(), new Builder(fieldDescriptor.getMessageType()));
        }
    }
}
 
Example #25
Source File: DynamicMessageRecordSerializer.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
@Nonnull
protected Pair<Descriptors.FieldDescriptor, DynamicMessage> getUnionField(@Nonnull final DynamicMessage unionMessage,
                                                                          @Nonnull final Tuple primaryKey) {
    final Map.Entry<Descriptors.FieldDescriptor, Object> entry = unionMessage.getAllFields().entrySet().iterator().next();
    final DynamicMessage message = (DynamicMessage)entry.getValue();
    if (!message.getUnknownFields().asMap().isEmpty()) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn(KeyValueLogMessage.of("Deserialized message has unknown fields",
                    LogMessageKeys.PRIMARY_KEY, primaryKey,
                    LogMessageKeys.RECORD_TYPE, message.getDescriptorForType().getName(),
                    LogMessageKeys.UNKNOWN_FIELDS, message.getUnknownFields().asMap().keySet()));
        }
    }
    return new ImmutablePair<>(entry.getKey(), message);
}
 
Example #26
Source File: TestProtobufTypeUtil.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testOneofProtoToSdc() throws DataParserException, IOException, DataGeneratorException {

  Descriptors.Descriptor descriptor = OneofProto.getDescriptor().findMessageTypeByName("Oneof");
  ByteArrayOutputStream bOut = new ByteArrayOutputStream();
  OneofProto.Oneof.Builder builder = OneofProto.Oneof.newBuilder();

  OneofProto.Oneof build = builder.setOneofInt(5).build();
  build.writeDelimitedTo(bOut);
  bOut.close();

  DynamicMessage.Builder dynBldr = DynamicMessage.newBuilder(descriptor);
  dynBldr.mergeDelimitedFrom(new ByteArrayInputStream(bOut.toByteArray()), null);
  Record record = RecordCreator.create();
  Field field = ProtobufTypeUtil.protobufToSdcField(record, "", descriptor, typeToExtensionMap, dynBldr.build());
  Assert.assertNotNull(field);
  Assert.assertEquals("", field.getValueAsMap().get("oneofString").getValue());
  Assert.assertEquals(Field.Type.INTEGER, field.getValueAsListMap().get("oneofInt").getType());
  Assert.assertEquals(5, field.getValueAsMap().get("oneofInt").getValueAsInteger());

  bOut.reset();
  builder.clear();
  build = builder.setOneofString("Hello").build();
  build.writeDelimitedTo(bOut);
  bOut.close();

  dynBldr = DynamicMessage.newBuilder(descriptor);
  dynBldr.mergeDelimitedFrom(new ByteArrayInputStream(bOut.toByteArray()), null);
  record = RecordCreator.create();
  field = ProtobufTypeUtil.protobufToSdcField(record, "", descriptor, typeToExtensionMap, dynBldr.build());
  Assert.assertNotNull(field);
  Assert.assertEquals(0, field.getValueAsMap().get("oneofInt").getValue());
  Assert.assertEquals(Field.Type.STRING, field.getValueAsListMap().get("oneofString").getType());
  Assert.assertEquals("Hello", field.getValueAsMap().get("oneofString").getValueAsString());

}
 
Example #27
Source File: ProtobufKafkaSerializer.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
private Serde.Schema toSchemaProto(Descriptors.FileDescriptor file) {
    Serde.Schema.Builder b = Serde.Schema.newBuilder();
    b.setFile(file.toProto());
    for (Descriptors.FileDescriptor d : file.getDependencies()) {
        b.addImport(toSchemaProto(d));
    }
    return b.build();
}
 
Example #28
Source File: MetaDataValidator.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
protected void validateUnionDescriptor(Descriptors.Descriptor unionDescriptor) {
    final List<Descriptors.OneofDescriptor> oneofs = unionDescriptor.getOneofs();
    if (!oneofs.isEmpty()) {
        if (oneofs.size() > 1) {
            throw new MetaDataException("Union descriptor has more than one oneof");
        }
        if (oneofs.get(0).getFieldCount() != unionDescriptor.getFields().size()) {
            throw new MetaDataException("Union descriptor oneof must contain every field");
        }
    }
}
 
Example #29
Source File: FieldFactoryTest.java    From beast with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnByteField() {
    Descriptors.FieldDescriptor byteDesc = message.getDescriptorForType().findFieldByNumber(10);

    ProtoField protoField = FieldFactory.getField(byteDesc, message.getField(byteDesc));

    assertEquals(ByteField.class.getName(), protoField.getClass().getName());
    String encodedToken = new String(Base64.getEncoder().encode("token".getBytes()));
    assertEquals(encodedToken, protoField.getValue());
}
 
Example #30
Source File: ValidationResults.java    From metastore with Apache License 2.0 5 votes vote down vote up
private FieldResultContainer getOrCreateFieldContainer(Descriptors.FieldDescriptor field) {
  FieldResultContainer fieldResultContainer = fieldMap.get(field.getName());
  if (fieldResultContainer == null) {
    fieldResultContainer = new FieldResultContainer();
    fieldResultContainer.name = field.getName();
    fieldResultContainer.number = field.getNumber();
    fieldMap.put(field.getName(), fieldResultContainer);
  }
  return fieldResultContainer;
}