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

The following examples show how to use com.google.protobuf.Descriptors#FieldDescriptor . 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 Project: xresloader   File: DataDstPb.java    License: MIT License 6 votes vote down vote up
private void filterMissingFields(LinkedList<String> missingFields, HashMap<String, String> oneofField,
        Descriptors.FieldDescriptor fd, boolean isMissing) throws ConvException {
    if (missingFields == null && oneofField == null) {
        return;
    }

    Descriptors.OneofDescriptor oneof = fd.getContainingOneof();
    if (isMissing && oneof == null && missingFields != null) {
        missingFields.push(fd.getName());
    }

    if (!isMissing && oneof != null && oneofField.containsKey(oneof.getFullName())) {
        String old_field = oneofField.get(oneof.getFullName());
        if (old_field != null) {
            setLastErrorMessage(
                    "field \"%s\" in oneof descriptor \"%s\" already exists, can not add another field \"%s\" with the same oneof descriptor",
                    old_field, oneof.getFullName(), fd.getName());
            throw new ConvException(getLastErrorMessage());
        }
        oneofField.replace(oneof.getFullName(), fd.getName());
    }
}
 
Example 2
Source Project: metastore   File: ProtoDomain.java    License: Apache License 2.0 6 votes vote down vote up
public Collection<Descriptors.Descriptor> findDescriptorsByOption(String optionName) {
  Descriptors.FieldDescriptor fieldDescriptor = optionsCatalog.getMessageOptionByName(optionName);
  return descriptorMap.values().stream()
      .filter(
          descriptor -> {
            DescriptorProtos.MessageOptions 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 3
Source Project: metastore   File: ProtoDomain.java    License: Apache License 2.0 6 votes vote down vote up
public Collection<Descriptors.FileDescriptor> findFileDescriptorsByOption(String optionName) {
  Descriptors.FieldDescriptor fieldDescriptor = optionsCatalog.getFileOptionByName(optionName);
  return fileDescriptorMap.values().stream()
      .filter(
          descriptor -> {
            DescriptorProtos.FileOptions 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 4
Source Project: sofa-jraft   File: GrpcResponseFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Message newResponse(final Message parent, final int code, final String fmt, final Object... args) {
    final RpcRequests.ErrorResponse.Builder eBuilder = RpcRequests.ErrorResponse.newBuilder();
    eBuilder.setErrorCode(code);
    if (fmt != null) {
        eBuilder.setErrorMsg(String.format(fmt, args));
    }

    if (parent == null || parent instanceof RpcRequests.ErrorResponse) {
        return eBuilder.build();
    }

    final Descriptors.FieldDescriptor errFd = parent //
        .getDescriptorForType() //
        .findFieldByNumber(ERROR_RESPONSE_NUM);
    Requires.requireNonNull(errFd, "errFd");
    final Message.Builder builder = parent.toBuilder();
    for (final Descriptors.FieldDescriptor fd : parent.getDescriptorForType().getFields()) {
        builder.setField(fd, parent.getField(fd));
    }
    return builder //
        .setField(errFd, eBuilder.build()) //
        .build();
}
 
Example 5
Source Project: metastore   File: ProtoDiff.java    License: Apache License 2.0 6 votes vote down vote up
private void diffOptionsFromField(
    Descriptors.FieldDescriptor descriptorRef, Descriptors.FieldDescriptor descriptorNew) {
  DescriptorProtos.FieldOptions optionsRef = descriptorRef.getOptions();
  DescriptorProtos.FieldOptions optionsNew = descriptorNew.getOptions();
  diffExtensionOptions(
      OptionChangeInfo.OptionType.FIELD_OPTION,
      descriptorRef,
      optionsRef.getAllFields(),
      descriptorNew,
      optionsNew.getAllFields());
  diffUnknownOptions(
      OptionChangeInfo.OptionType.FIELD_OPTION,
      descriptorRef,
      optionsRef.getUnknownFields(),
      descriptorNew,
      optionsNew.getUnknownFields());
}
 
Example 6
Source Project: metastore   File: ProtoDiff.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isDeprecated(Descriptors.MethodDescriptor fieldDescriptor) {
  Map<Descriptors.FieldDescriptor, Object> allFields =
      fieldDescriptor.getOptions().getAllFields();
  if (allFields.size() > 0) {
    for (Map.Entry<Descriptors.FieldDescriptor, Object> entry : allFields.entrySet()) {
      Descriptors.FieldDescriptor f = entry.getKey();
      switch (f.getFullName()) {
        case "google.protobuf.MethodOptions.deprecated":
          return true;
      }
    }
  }
  return false;
}
 
Example 7
Source Project: jigsaw-payment   File: JavaPropsFormat.java    License: 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 8
Source Project: metastore   File: ValidationResults.java    License: 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;
}
 
Example 9
@Nullable
private Double getCoordinateField(@Nullable Message message, @Nonnull String fieldName) {
    if (message == null) {
        return null;
    }
    final Descriptors.FieldDescriptor field = message.getDescriptorForType().findFieldByName(fieldName);
    if (field == null) {
        throw new Query.InvalidExpressionException("Missing field " + fieldName);
    }
    return (Double)message.getField(field);
}
 
Example 10
Source Project: datacollector   File: ProtobufTypeUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static void handleMapField(
    Record record,
    Field field,
    String fieldPath,
    Map<String, Set<Descriptors.FieldDescriptor>> messageTypeToExtensionMap,
    Map<String, Object> defaultValueMap,
    Descriptors.FieldDescriptor fieldDescriptor,
    DynamicMessage.Builder builder
) throws DataGeneratorException {
  Descriptors.Descriptor mapEntryDescriptor = fieldDescriptor.getMessageType();
  // MapEntry contains key and value fields
  Map<String, Field> sdcMapField = field.getValueAsMap();
  for (Map.Entry<String, Field> entry : sdcMapField.entrySet()) {
    builder.addRepeatedField(fieldDescriptor, DynamicMessage.newBuilder(mapEntryDescriptor)
        .setField(mapEntryDescriptor.findFieldByName(KEY), entry.getKey())
        .setField(
            mapEntryDescriptor.findFieldByName(VALUE),
            getValue(
                mapEntryDescriptor.findFieldByName(VALUE),
                entry.getValue(),
                record,
                fieldPath + FORWARD_SLASH + entry.getKey(),
                messageTypeToExtensionMap,
                defaultValueMap
            )
        )
        .build()
    );
  }
}
 
Example 11
Source Project: jigsaw-payment   File: JavaPropsFormat.java    License: Apache License 2.0 5 votes vote down vote up
public void printField(final Descriptors.FieldDescriptor field,
                              final Object value,
                              final Appendable output)
                              throws IOException {
  final JavaPropsGenerator generator = new JavaPropsGenerator(output);
  printField(field, value, generator);
}
 
Example 12
Source Project: fdb-record-layer   File: Key.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert a field descriptor into a expression. Assumes FanOut for repeated keys.
 * @param fieldDescriptor a field in a record type.
 * @return a new {@code Field} to get the value of the given field descriptor.
 */
@Nonnull
public static FieldKeyExpression fromDescriptor(@Nonnull Descriptors.FieldDescriptor fieldDescriptor) {
    final FieldKeyExpression field = fieldDescriptor.isRepeated() ?
                                     Expressions.field(fieldDescriptor.getName(), KeyExpression.FanType.FanOut) :
                                     Expressions.field(fieldDescriptor.getName());
    field.validate(fieldDescriptor.getContainingType(), fieldDescriptor, false);
    return field;
}
 
Example 13
static boolean isSimilarEntry(@NotNull final CassandraFrameworkProtos.HealthCheckDetails existing, @NotNull final CassandraFrameworkProtos.HealthCheckDetails current) {
    for (final Descriptors.FieldDescriptor f : existing.getDescriptorForType().getFields()) {
        if (!"info".equals(f.getName())) {
            if (!objEquals(existing.getField(f), current.getField(f))) {
                return false;
            }
        } else {
            if (!isSimilarEntry(existing.getInfo(), current.getInfo())) {
                return false;
            }
        }
    }
    return true;
}
 
Example 14
Source Project: xresloader   File: DataDstPbHelper.java    License: MIT License 4 votes vote down vote up
private static <T extends com.google.protobuf.GeneratedMessageV3.ExtendableMessage<T>> HashMap<String, Object> dumpMessageExtensions(
        T msg, Map<Descriptors.FieldDescriptor, Object> options,
        com.google.protobuf.ExtensionRegistry custom_extensions) {
    HashMap<String, Object> ret = null;
    if (null == custom_extensions) {
        return ret;
    }

    if (options != null && !options.isEmpty()) {
        ret = new HashMap<String, Object>();
        for (Map.Entry<Descriptors.FieldDescriptor, Object> kv : options.entrySet()) {
            ret.put(kv.getKey().getName(), convertMessageFieldIntoObject(kv.getKey(), kv.getValue(), true));
        }
    }

    Map<Integer, com.google.protobuf.UnknownFieldSet.Field> all_unknown_fields = msg.getUnknownFields().asMap();
    if (all_unknown_fields.isEmpty()) {
        return ret;
    }

    Set<ExtensionInfo> all_ext_types = custom_extensions
            .getAllImmutableExtensionsByExtendedType(msg.getDescriptorForType().getFullName());

    if (all_ext_types.isEmpty()) {
        return ret;
    }

    for (ExtensionInfo ext_type : all_ext_types) {
        com.google.protobuf.UnknownFieldSet.Field field_data = all_unknown_fields
                .getOrDefault(ext_type.descriptor.getNumber(), null);
        if (field_data == null) {
            continue;
        }

        if (ret != null && ret.containsKey(ext_type.descriptor.getName())) {
            continue;
        }

        try {
            Object val;
            val = pickMessageField(field_data, ext_type.descriptor, ext_type.defaultInstance, true);
            if (null != val) {
                if (ret == null) {
                    ret = new HashMap<String, Object>();
                }
                ret.put(ext_type.descriptor.getName(), val);
            }
        } catch (InvalidProtocolBufferException | UnsupportedEncodingException e) {
            // Ignore error
        }
    }

    return ret;
}
 
Example 15
Source Project: krpc   File: MessageToBean.java    License: Apache License 2.0 4 votes vote down vote up
static void parseSingleField(Descriptors.FieldDescriptor field, Object value, Object bean, boolean isArray) {

        String name = field.getName();

        switch (field.getType()) {
            case INT32:
            case SINT32:
            case SFIXED32:
                addToResults(name, value, bean, isArray);
                break;

            case INT64:
            case SINT64:
            case SFIXED64:
                addToResults(name, value, bean, isArray);
                break;

            case BOOL:
                addToResults(name,value, bean, isArray);
                break;

            case FLOAT:
                addToResults(name,value, bean, isArray);
                break;

            case DOUBLE:
                addToResults(name,value, bean, isArray);
                break;

            case UINT32:
            case FIXED32:
                addToResults(name, unsignedToLong((Integer) value), bean, isArray);
                break;

            case UINT64:
            case FIXED64:
                addToResults(name, unsignedToBigInteger((Long) value), bean, isArray);
                break;

            case STRING:
                addToResults(name,value, bean, isArray);
                break;

            case BYTES: {
                if (value instanceof ByteString) {
                    addToResults(name, value, bean, isArray);
                }
                if (value instanceof String) {
                    byte[] bb = getBytes((String) value);
                    if (bb != null) {
                        addToResults(name, ByteString.copyFrom(bb), bean, isArray);
                    }
                }
                if (value instanceof byte[]) {
                    addToResults(name, ByteString.copyFrom((byte[]) value), bean, isArray);
                }
            }
            break;

            case ENUM:
                addToResults(name, ((Descriptors.EnumValueDescriptor) value).getNumber(), bean, isArray);
                break;

            case MESSAGE:
                Object sub = getFieldInstance(name,bean);
                copyProperties((Message) value, sub);
                addToResults(name, sub, bean, isArray);
                break;

            default:
                break;
        }
    }
 
Example 16
Source Project: metastore   File: ProtoDomain.java    License: Apache License 2.0 4 votes vote down vote up
Map<Integer, Descriptors.FieldDescriptor> getFileOptionMap() {
  return Collections.unmodifiableMap(fileOptionMap);
}
 
Example 17
@Override
public List<Descriptors.FieldDescriptor> validate(@Nonnull Descriptors.Descriptor descriptor) {
    throw new UnsupportedOperationException();
}
 
Example 18
public List<Descriptors.FieldDescriptor> validate(@Nonnull Descriptors.Descriptor parentDescriptor, boolean allowMessageType) {
    final Descriptors.FieldDescriptor fieldDescriptor = parentDescriptor.findFieldByName(fieldName);
    validate(parentDescriptor, fieldDescriptor, allowMessageType);
    return Collections.singletonList(fieldDescriptor);
}
 
Example 19
Source Project: metastore   File: ProtoDomain.java    License: Apache License 2.0 4 votes vote down vote up
public Descriptors.FieldDescriptor getFileOptionByName(String fullName) {
  return findByName(fileOptionMap, fullName);
}
 
Example 20
/**
 * Create a new typed record store builder.
 *
 * @param fieldDescriptor field descriptor for the union field used to hold the target record type
 * @param builderSupplier builder for the union message type
 * @param tester predicate to determine whether an instance of the union message has the target record type
 * @param getter accessor to get record message instance from union message instance
 * @param setter access to store record message instance into union message instance
 * @param <M> generated Protobuf class for the record message type
 * @param <U> generated Protobuf class for the union message
 * @param <B> generated Protobuf class for the union message's builder
 * @return a builder using the given functions
 */
@Nonnull
public static <M extends Message, U extends Message, B extends Message.Builder> Builder<M> newBuilder(@Nonnull Descriptors.FieldDescriptor fieldDescriptor,
                                                                                                      @Nonnull Supplier<B> builderSupplier,
                                                                                                      @Nonnull Predicate<U> tester,
                                                                                                      @Nonnull Function<U, M> getter,
                                                                                                      @Nonnull BiConsumer<B, M> setter) {
    RecordSerializer<M> typedSerializer = new TypedRecordSerializer<>(fieldDescriptor, builderSupplier, tester, getter, setter);
    RecordSerializer<Message> untypedSerializer = new MessageBuilderRecordSerializer(builderSupplier::get);
    return newBuilder(typedSerializer).setUntypedSerializer(untypedSerializer);
}