Java Code Examples for com.google.protobuf.Message#getDescriptorForType()

The following examples show how to use com.google.protobuf.Message#getDescriptorForType() . 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: FunctionKeyIndexTest.java    From fdb-record-layer with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public <M extends Message> List<Key.Evaluated> evaluateFunction(@Nullable FDBRecord<M> record,
                                                                @Nullable Message message,
                                                                @Nonnull Key.Evaluated arguments) {
    if (message == null) {
        return Collections.emptyList();
    }
    List<Key.Evaluated> keys = new ArrayList<>();
    Descriptors.Descriptor descriptor = message.getDescriptorForType();
    Descriptors.FieldDescriptor strField = descriptor.findFieldByNumber(TypesRecord.STR_VALUE_FIELD_NUMBER);
    Descriptors.FieldDescriptor strListField = descriptor.findFieldByNumber(TypesRecord.STR_LIST_VALUE_FIELD_NUMBER);
    if (message.hasField(strField)) {
        keys.add(toKey((String) message.getField(strField)));
    }
    final int len = message.getRepeatedFieldCount(strListField);
    for (int i = 0; i < len; i++) {
        keys.add(toKey((String) message.getRepeatedField(strListField, i)));
    }
    return keys;
}
 
Example 2
Source File: FieldScopeUtil.java    From curiostack with MIT License 6 votes vote down vote up
/**
 * Returns the singular descriptor used by all non-null messages in the list.
 *
 * <p>If there is no descriptor, or more than one, returns {@code Optional.absent()}.
 */
static Optional<Descriptor> getSingleDescriptor(Iterable<? extends Message> messages) {
  Optional<Descriptor> optDescriptor = Optional.absent();
  for (Message message : messages) {
    if (message != null) {
      Descriptor descriptor = message.getDescriptorForType();
      if (!optDescriptor.isPresent()) {
        optDescriptor = Optional.of(descriptor);
      } else if (descriptor != optDescriptor.get()) {
        // Two different descriptors - abandon ship.
        return Optional.absent();
      }
    }
  }
  return optDescriptor;
}
 
Example 3
Source File: TemplateEvaluatorTest.java    From stateful-functions with Apache License 2.0 5 votes vote down vote up
@Test
public void exampleUsage() {
  Message originalMessage = SimpleMessage.newBuilder().setName("bob").build();
  DynamicMessage message = dynamic(originalMessage);

  TemplateEvaluator evaluator =
      new TemplateEvaluator(
          originalMessage.getDescriptorForType(),
          fragments(staticFragment("foo.bar/"), dynamicFragment("$.name")));

  assertThat(evaluator.evaluate(message), is("foo.bar/bob"));
}
 
Example 4
Source File: TemplateEvaluatorTest.java    From flink-statefun with Apache License 2.0 5 votes vote down vote up
@Test
public void exampleUsage() {
  Message originalMessage = SimpleMessage.newBuilder().setName("bob").build();
  DynamicMessage message = dynamic(originalMessage);

  TemplateEvaluator evaluator =
      new TemplateEvaluator(
          originalMessage.getDescriptorForType(),
          fragments(staticFragment("foo.bar/"), dynamicFragment("$.name")));

  assertThat(evaluator.evaluate(message), is("foo.bar/bob"));
}
 
Example 5
Source File: MarshallerRegistry.java    From curiostack with MIT License 5 votes vote down vote up
/**
 * Returns the {@link TypeSpecificMarshaller} that can marshall protobufs with the same type as
 * {@code prototype}.
 */
TypeSpecificMarshaller<?> findForPrototype(Message prototype) {
  TypeSpecificMarshaller<?> marshaller = descriptorRegistry.get(prototype.getDescriptorForType());
  if (marshaller == null) {
    throw new IllegalArgumentException(
        "Could not find marshaller for type: "
            + prototype.getDescriptorForType()
            + ". Has it been registered?");
  }
  return marshaller;
}
 
Example 6
Source File: DoWrite.java    From curiostack with MIT License 5 votes vote down vote up
DoWrite(
    Message prototype,
    boolean includeDefaults,
    boolean printingEnumsAsInts,
    boolean sortingMapKeys) {
  this.prototype = prototype;
  this.messageClass = prototype.getClass();
  this.descriptor = prototype.getDescriptorForType();
  this.includeDefaults = includeDefaults;
  this.printingEnumsAsInts = printingEnumsAsInts;
  this.sortingMapKeys = sortingMapKeys;
}
 
Example 7
Source File: ProtoAssert.java    From curiostack with MIT License 5 votes vote down vote up
private static boolean notMessagesWithSameDescriptor(
    @NullableDecl Message actual, @NullableDecl Object expected) {
  if (actual != null && expected instanceof Message) {
    return actual.getDescriptorForType() != ((Message) expected).getDescriptorForType();
  }
  return true;
}
 
Example 8
Source File: ProtoDynamicMessageSchema.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
Object convertFromProtoValue(Object object) {
  Message timestamp = (Message) object;
  Descriptors.Descriptor timestampDescriptor = timestamp.getDescriptorForType();
  FieldDescriptor secondField = timestampDescriptor.findFieldByNumber(1);
  FieldDescriptor nanoField = timestampDescriptor.findFieldByNumber(2);
  long second = (long) timestamp.getField(secondField);
  int nano = (int) timestamp.getField(nanoField);
  return Instant.ofEpochSecond(second, nano);
}
 
Example 9
Source File: ProtoDynamicMessageSchema.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
Duration convertFromProtoValue(Object object) {
  Message timestamp = (Message) object;
  Descriptors.Descriptor timestampDescriptor = timestamp.getDescriptorForType();
  FieldDescriptor secondField = timestampDescriptor.findFieldByNumber(1);
  FieldDescriptor nanoField = timestampDescriptor.findFieldByNumber(2);
  long second = (long) timestamp.getField(secondField);
  int nano = (int) timestamp.getField(nanoField);
  return Duration.ofSeconds(second, nano);
}
 
Example 10
Source File: FieldKeyExpression.java    From fdb-record-layer with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
@SuppressWarnings("unchecked")
public <M extends Message> List<Key.Evaluated> evaluateMessage(@Nullable FDBRecord<M> record, @Nullable Message message) {
    if (message == null) {
        return getNullResult();
    }
    Descriptors.Descriptor recordDescriptor = message.getDescriptorForType();
    Descriptors.FieldDescriptor fieldDescriptor = recordDescriptor.findFieldByName(fieldName);
    // TODO: Part of this is working around a deficiency in DynamicMessage.getField() prior
    //  to 2.5, where a repeated message field returns an empty message instead of an
    //  empty collection.
    if (fieldDescriptor != null && fieldDescriptor.isRepeated()) {
        List<Object> values;
        if (message.getRepeatedFieldCount(fieldDescriptor) > 0) {
            values = (List<Object>)message.getField(fieldDescriptor);
        } else {
            values = Collections.emptyList();
        }

        switch (fanType) {
            case FanOut:
                return Key.Evaluated.fan(values);
            case Concatenate:
                return Collections.singletonList(Key.Evaluated.scalar(values));
            case None:
                throw new RecordCoreException("FanType.None with repeated field");
            default:
                throw new RecordCoreException(String.format("unknown fan type: %s", fanType));
        }
    } else if (fieldDescriptor != null && (nullStandin == Key.Evaluated.NullStandin.NOT_NULL || message.hasField(fieldDescriptor))) {
        Object value = message.getField(fieldDescriptor);
        if (fieldDescriptor.getJavaType() == Descriptors.FieldDescriptor.JavaType.MESSAGE &&
                TupleFieldsHelper.isTupleField(fieldDescriptor.getMessageType())) {
            value = TupleFieldsHelper.fromProto((Message)value, fieldDescriptor.getMessageType());
        }
        // ignore FanType
        return Collections.singletonList(Key.Evaluated.scalar(value));
    } else {
        return getNullResult();
    }
}
 
Example 11
Source File: FieldMasks.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
private static void compare(
    FieldMask.Builder mask, String currentField, Message original, Message modified) {
  Descriptor descriptor = original.getDescriptorForType();
  for (FieldDescriptor field : descriptor.getFields()) {
    String fieldName = getFieldName(currentField, field);
    Object originalValue = original.getField(field);
    Object modifiedValue = modified.getField(field);
    if (field.isRepeated()) {
      if (!Objects.equals(originalValue, modifiedValue)) {
        mask.addPaths(fieldName);
      }
    } else {
      switch (field.getJavaType()) {
        case MESSAGE:
          // Because getField never returns null, we use hasField to distinguish null
          // from empty message when getType() == MESSAGE
          if (original.hasField(field) != modified.hasField(field)
              || !Objects.equals(originalValue, modifiedValue)) {
            if (isWrapperType(field.getMessageType())) {
              // For wrapper types, just emit the field name.
              mask.addPaths(fieldName);
            } else if (!modified.hasField(field)) {
              // Just emit the deleted field name
              mask.addPaths(fieldName);
            } else {
              // Recursively compare to find different values
              compare(mask, fieldName, (Message) originalValue, (Message) modifiedValue);
            }
          }
          break;
        case INT:
        case LONG:
        case FLOAT:
        case DOUBLE:
        case BOOLEAN:
        case STRING:
        case BYTE_STRING:
        case ENUM:
          // Handle all java types except MESSAGE
          if (!Objects.equals(originalValue, modifiedValue)) {
            mask.addPaths(fieldName);
          }
          break;
        default:
          throw new IllegalArgumentException(
              "Unexpected java type "
                  + field.getJavaType()
                  + " encountered for field "
                  + fieldName);
      }
    }
  }
}
 
Example 12
Source File: RegistrationManager.java    From ja-micro with Apache License 2.0 4 votes vote down vote up
protected String getProtobufClassFieldDescriptions(Class<? extends Message> messageClass, Set<Class<? extends Message>> visited)
        throws Exception {

    if (visited.contains(messageClass)) {
        return "";
    }
    visited.add(messageClass);

    StringBuilder sb = new StringBuilder();
    Constructor<?> constructor = null;
    try {
        constructor = messageClass.getDeclaredConstructor();
    } catch (NoSuchMethodException nsmex) {
        //Issue #35
        logger.info("Unsupported protobuf field: {}", messageClass.getName());
        return sb.toString();
    }
    constructor.setAccessible(true);
    Object instance = constructor.newInstance();
    Message.Builder builder = ((Message)instance).newBuilderForType();
    Message message = builder.build();

    Descriptors.Descriptor requestDesc = message.getDescriptorForType();
    List<Descriptors.FieldDescriptor> requestFields = requestDesc.getFields();
    Iterator<Descriptors.FieldDescriptor> iter = requestFields.iterator();
    while (iter.hasNext()) {
        Descriptors.FieldDescriptor fd = iter.next();
        //TODO: deal with repeated fields
        sb.append("{\"name\":\"");
        sb.append(fd.getName());
        sb.append("\",\"type\":\"");
        if (fd.getType().toString().equalsIgnoreCase("message")) {
            sb.append(getLastComponent(fd.getMessageType().getFullName()));
            sb.append("\",\"values\":[");
            Descriptors.FieldDescriptor childDescriptor = requestDesc.findFieldByName(fd.getName());
            Message.Builder subMessageBuilder = builder.newBuilderForField(childDescriptor);
            Message subMessage = subMessageBuilder.build();
            sb.append(getProtobufClassFieldDescriptions(subMessage.getClass(), visited));
            sb.append("]}");
        } else {
            sb.append(fd.getType().toString().toLowerCase());
            sb.append("\",\"values\":null}");
        }
        if (iter.hasNext()) {
            sb.append(",");
        }
    }
    return sb.toString();
}
 
Example 13
Source File: DoParse.java    From curiostack with MIT License 4 votes vote down vote up
DoParse(Message prototype, boolean ignoringUnknownFields) {
  this.prototype = prototype;
  builderClass = prototype.newBuilderForType().getClass();
  descriptor = prototype.getDescriptorForType();
  this.ignoringUnknownFields = ignoringUnknownFields;
}
 
Example 14
Source File: FieldScopeLogic.java    From curiostack with MIT License 4 votes vote down vote up
RootPartialScopeLogic(Message message) {
  super(FieldNumberTree.fromMessage(message));
  this.message = message;
  this.expectedDescriptor = message.getDescriptorForType();
}