com.google.protobuf.Descriptors.FieldDescriptor Java Examples

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 File: GeneratedMessage.java    From android-chromium with BSD 2-Clause "Simplified" License 7 votes vote down vote up
/** Internal helper which returns a mutable map. */
private Map<FieldDescriptor, Object> getAllFieldsMutable() {
  final TreeMap<FieldDescriptor, Object> result =
    new TreeMap<FieldDescriptor, Object>();
  final Descriptor descriptor = internalGetFieldAccessorTable().descriptor;
  for (final FieldDescriptor field : descriptor.getFields()) {
    if (field.isRepeated()) {
      final List value = (List) getField(field);
      if (!value.isEmpty()) {
        result.put(field, value);
      }
    } else {
      if (hasField(field)) {
        result.put(field, getField(field));
      }
    }
  }
  return result;
}
 
Example #2
Source File: ProtoFuzzer.java    From bundletool with Apache License 2.0 6 votes vote down vote up
private static <T extends Message> Object fuzzField(FieldDescriptor field, T containingMessage) {
  switch (field.getType().getJavaType()) {
    case BOOLEAN:
      return RAND.nextBoolean();
    case BYTE_STRING:
      return randomByteString();
    case DOUBLE:
      return RAND.nextDouble();
    case ENUM:
      return randomEnum(field.getEnumType());
    case FLOAT:
      return RAND.nextFloat();
    case INT:
      return RAND.nextInt();
    case LONG:
      return RAND.nextLong();
    case STRING:
      return randomString();
    case MESSAGE:
      return randomProtoMessage(
          ProtoReflection.getJavaClassOfMessageField(containingMessage, field));
  }
  throw new RuntimeException("Unhandled field type: " + field.getType());
}
 
Example #3
Source File: MessageDifferencer.java    From startup-os with Apache License 2.0 6 votes vote down vote up
public Builder treatAsMapWithMultipleFieldsAsKey(
    FieldDescriptor field, List<FieldDescriptor> keyFields) {
  Preconditions.checkArgument(
      field.isRepeated(), "Field must be repeated " + field.getFullName());
  Preconditions.checkArgument(
      JavaType.MESSAGE.equals(field.getJavaType()),
      "Field has to be message type.  Field name is: " + field.getFullName());
  for (int i = 0; i < keyFields.size(); ++i) {
    FieldDescriptor key = keyFields.get(i);
    Preconditions.checkArgument(
        key.getContainingType().equals(field.getMessageType()),
        key.getFullName()
            + " must be a direct subfield within the repeated field: "
            + field.getFullName());
  }
  Preconditions.checkArgument(
      !setFields.contains(field),
      "Cannot treat this repeated field as both Map and Set for comparison.");
  MapKeyComparator keyComparator = new MultipleFieldsMapKeyComparator(keyFields);
  mapKeyComparatorMap.put(field, keyComparator);
  return this;
}
 
Example #4
Source File: GeneratedMessage.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** For use by generated code only. */
public static <ContainingType extends Message, Type>
    GeneratedExtension<ContainingType, Type>
    newMessageScopedGeneratedExtension(final Message scope,
                                       final int descriptorIndex,
                                       final Class singularType,
                                       final Message defaultInstance) {
  // For extensions scoped within a Message, we use the Message to resolve
  // the outer class's descriptor, from which the extension descriptor is
  // obtained.
  return new GeneratedExtension<ContainingType, Type>(
      new ExtensionDescriptorRetriever() {
        //@Override (Java 1.6 override semantics, but we must support 1.5)
        public FieldDescriptor getDescriptor() {
          return scope.getDescriptorForType().getExtensions()
              .get(descriptorIndex);
        }
      },
      singularType,
      defaultInstance);
}
 
Example #5
Source File: GeoWaveGrpcCliGeoserverService.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
public void geoServerAddWorkspaceCommand(
    final org.locationtech.geowave.service.grpc.protobuf.GeoServerAddWorkspaceCommandParametersProtos request,
    final StreamObserver<org.locationtech.geowave.service.grpc.protobuf.GeoWaveReturnTypesProtos.StringResponseProtos> responseObserver) {
  final GeoServerAddWorkspaceCommand cmd = new GeoServerAddWorkspaceCommand();
  final Map<FieldDescriptor, Object> m = request.getAllFields();
  GeoWaveGrpcServiceCommandUtil.setGrpcToCommandFields(m, cmd);

  final File configFile = GeoWaveGrpcServiceOptions.geowaveConfigFile;
  final OperationParams params = new ManualOperationParams();
  params.getContext().put(ConfigOptions.PROPERTIES_FILE_CONTEXT, configFile);

  cmd.prepare(params);

  LOGGER.info("Executing GeoServerAddWorkspaceCommand...");
  try {
    final String result = cmd.computeResults(params);
    final StringResponseProtos resp =
        StringResponseProtos.newBuilder().setResponseValue(result).build();
    responseObserver.onNext(resp);
    responseObserver.onCompleted();

  } catch (final Exception e) {
    LOGGER.error("Exception encountered executing command", e);
  }
}
 
Example #6
Source File: GeneratedMessage.java    From play-store-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Used in proto1 generated code only.
 *
 * After enabling bridge, we can define proto2 extensions (the extended type
 * is a proto2 mutable message) in a proto1 .proto file. For these extensions
 * we should generate proto2 GeneratedExtensions.
 */
public static <ContainingType extends Message, Type>
    GeneratedExtension<ContainingType, Type>
    newMessageScopedGeneratedExtension(
        final Message scope, final String name,
        final Class singularType, final Message defaultInstance) {
  // For extensions scoped within a Message, we use the Message to resolve
  // the outer class's descriptor, from which the extension descriptor is
  // obtained.
  return new GeneratedExtension<ContainingType, Type>(
      new CachedDescriptorRetriever() {
        @Override
        protected FieldDescriptor loadDescriptor() {
          return scope.getDescriptorForType().findFieldByName(name);
        }
      },
      singularType,
      defaultInstance,
      Extension.ExtensionType.MUTABLE);
}
 
Example #7
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 #8
Source File: SimpleLogFormatter.java    From krpc with Apache License 2.0 6 votes vote down vote up
void printSingleField(FieldDescriptor field, Object value, Appender appender, Level level)
        throws IOException {
    if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
        if (level.level + 1 > maxLevels) {
            return;
        }
    }

    if (!level.isFirst()) {
        appender.appendSep(level.level);
    }
    level.setFirst(false);

    if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
        appender.appendKey(field.getName());
        appender.appendSep9();
        appender.appendMapStart();
        printFieldValue(field, value, appender, level);
        appender.appendMapEnd();
    } else {
        appender.appendKey(field.getName());
        appender.appendSep9();
        printFieldValue(field, value, appender, level);
    }
}
 
Example #9
Source File: ResourceTableMerger.java    From bundletool with Apache License 2.0 6 votes vote down vote up
/** Recursively crawls the proto message while clearing each field of type {@link Source}. */
@VisibleForTesting
static void stripSourceReferences(Message.Builder msg) {
  for (FieldDescriptor fieldDesc : msg.getAllFields().keySet()) {
    if (!fieldDesc.getJavaType().equals(JavaType.MESSAGE)) {
      continue;
    }

    if (fieldDesc.getMessageType().getFullName().equals(Source.getDescriptor().getFullName())) {
      msg.clearField(fieldDesc);
    } else {
      if (fieldDesc.isRepeated()) {
        int repeatCount = msg.getRepeatedFieldCount(fieldDesc);
        for (int i = 0; i < repeatCount; i++) {
          stripSourceReferences(msg.getRepeatedFieldBuilder(fieldDesc, i));
        }
      } else {
        stripSourceReferences(msg.getFieldBuilder(fieldDesc));
      }
    }
  }
}
 
Example #10
Source File: MessageReflection.java    From play-store-api with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object parseGroup(
    CodedInputStream input,
    ExtensionRegistryLite registry,
    Descriptors.FieldDescriptor field,
    Message defaultInstance)
    throws IOException {
  Message.Builder subBuilder =
      defaultInstance.newBuilderForType();
  if (!field.isRepeated()) {
    Message originalMessage = (Message) getField(field);
    if (originalMessage != null) {
      subBuilder.mergeFrom(originalMessage);
    }
  }
  input.readGroup(field.getNumber(), subBuilder, registry);
  return subBuilder.buildPartial();
}
 
Example #11
Source File: PerformanceBenchmarks.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private static void testAddRepeatedFieldsWithDescriptors() {
  List<FieldDescriptor> fields = getRepeatedFieldDescriptors();
  List<Object> values = new ArrayList<Object>();
  values.add(Integer.valueOf(1));
  values.add(Long.valueOf(2));
  values.add(Integer.valueOf(3));
  values.add(Long.valueOf(4));
  values.add(Boolean.TRUE);
  values.add(Float.valueOf(5.6f));
  values.add(Double.valueOf(7.8));
  values.add("foo");
  values.add(ByteString.copyFrom("bar".getBytes()));
  values.add(TypicalData.EnumType.VALUE1.getValueDescriptor());
  for (int i = 0; i < 150; i++) {
    TypicalData.Builder builder = TypicalData.newBuilder();
    for (int j = 0; j < 25; j++) {
      for (int k = 0; k < 10; k++) {
        builder.addRepeatedField(fields.get(k), values.get(k));
      }
    }
  }
}
 
Example #12
Source File: GeneratedMessage.java    From play-store-api with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object getField(final FieldDescriptor field) {
  if (field.isExtension()) {
    verifyContainingType(field);
    final Object value = extensions.getField(field);
    if (value == null) {
      if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
        // Lacking an ExtensionRegistry, we have no way to determine the
        // extension's real type, so we return a DynamicMessage.
        return DynamicMessage.getDefaultInstance(field.getMessageType());
      } else {
        return field.getDefaultValue();
      }
    } else {
      return value;
    }
  } else {
    return super.getField(field);
  }
}
 
Example #13
Source File: AbstractMessage.java    From travelguide with Apache License 2.0 6 votes vote down vote up
/** Get a hash code for given fields and values, using the given seed. */
@SuppressWarnings("unchecked")
protected int hashFields(int hash, Map<FieldDescriptor, Object> map) {
  for (Map.Entry<FieldDescriptor, Object> entry : map.entrySet()) {
    FieldDescriptor field = entry.getKey();
    Object value = entry.getValue();
    hash = (37 * hash) + field.getNumber();
    if (field.getType() != FieldDescriptor.Type.ENUM){
      hash = (53 * hash) + value.hashCode();
    } else if (field.isRepeated()) {
      List<? extends EnumLite> list = (List<? extends EnumLite>) value;
      hash = (53 * hash) + hashEnumList(list);
    } else {
      hash = (53 * hash) + hashEnum((EnumLite) value);
    }
  }
  return hash;
}
 
Example #14
Source File: GeneratedMessage.java    From play-store-api with GNU General Public License v3.0 6 votes vote down vote up
/** Get the value of an extension. */
@Override
@SuppressWarnings("unchecked")
public final <Type> Type getExtension(final ExtensionLite<MessageType, Type> extensionLite) {
  Extension<MessageType, Type> extension = checkNotLite(extensionLite);

  verifyExtensionContainingType(extension);
  FieldDescriptor descriptor = extension.getDescriptor();
  final Object value = extensions.getField(descriptor);
  if (value == null) {
    if (descriptor.isRepeated()) {
      return (Type) Collections.emptyList();
    } else if (descriptor.getJavaType() ==
               FieldDescriptor.JavaType.MESSAGE) {
      return (Type) extension.getMessageDefaultInstance();
    } else {
      return (Type) extension.fromReflectionType(
          descriptor.getDefaultValue());
    }
  } else {
    return (Type) extension.fromReflectionType(value);
  }
}
 
Example #15
Source File: GeneratedMessage.java    From play-store-api with GNU General Public License v3.0 6 votes vote down vote up
RepeatedEnumFieldAccessor(
    final FieldDescriptor descriptor, final String camelCaseName,
    final Class<? extends GeneratedMessage> messageClass,
    final Class<? extends Builder> builderClass) {
  super(descriptor, camelCaseName, messageClass, builderClass);

  enumDescriptor = descriptor.getEnumType();

  valueOfMethod = getMethodOrDie(type, "valueOf",
                                 EnumValueDescriptor.class);
  getValueDescriptorMethod =
    getMethodOrDie(type, "getValueDescriptor");

  supportUnknownEnumValue = descriptor.getFile().supportsUnknownEnumValue();
  if (supportUnknownEnumValue) {
    getRepeatedValueMethod =
        getMethodOrDie(messageClass, "get" + camelCaseName + "Value", int.class);
    getRepeatedValueMethodBuilder =
        getMethodOrDie(builderClass, "get" + camelCaseName + "Value", int.class);
    setRepeatedValueMethod =
        getMethodOrDie(builderClass, "set" + camelCaseName + "Value", int.class, int.class);
    addRepeatedValueMethod =
        getMethodOrDie(builderClass, "add" + camelCaseName + "Value", int.class);
  }
}
 
Example #16
Source File: GeoWaveGrpcCoreStoreService.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public void removeIndexCommand(
    final org.locationtech.geowave.service.grpc.protobuf.RemoveIndexCommandParametersProtos request,
    final StreamObserver<org.locationtech.geowave.service.grpc.protobuf.GeoWaveReturnTypesProtos.StringResponseProtos> responseObserver) {

  final RemoveIndexCommand cmd = new RemoveIndexCommand();
  final Map<FieldDescriptor, Object> m = request.getAllFields();
  GeoWaveGrpcServiceCommandUtil.setGrpcToCommandFields(m, cmd);

  final File configFile = GeoWaveGrpcServiceOptions.geowaveConfigFile;
  final OperationParams params = new ManualOperationParams();
  params.getContext().put(ConfigOptions.PROPERTIES_FILE_CONTEXT, configFile);

  cmd.prepare(params);

  LOGGER.info("Executing RemoveIndexCommand...");
  try {
    final String result = cmd.computeResults(params);
    final StringResponseProtos resp =
        StringResponseProtos.newBuilder().setResponseValue(result).build();
    responseObserver.onNext(resp);
    responseObserver.onCompleted();

  } catch (final Exception e) {
    LOGGER.error("Exception encountered executing command", e);
  }
}
 
Example #17
Source File: ProtoFuzzer.java    From bundletool with Apache License 2.0 5 votes vote down vote up
private static void swapRepeatedFieldValues(
    Message.Builder mutableMsg, FieldDescriptor field, int idx1, int idx2) {
  Object value1 = mutableMsg.getRepeatedField(field, idx1);
  Object value2 = mutableMsg.getRepeatedField(field, idx2);
  mutableMsg.setRepeatedField(field, idx1, value2);
  mutableMsg.setRepeatedField(field, idx2, value1);
}
 
Example #18
Source File: FieldScopeLogic.java    From curiostack with MIT License 5 votes vote down vote up
@Override
public void validate(
    Descriptor rootDescriptor, FieldDescriptorValidator fieldDescriptorValidator) {
  super.validate(rootDescriptor, fieldDescriptorValidator);
  for (FieldDescriptor fieldDescriptor : fieldDescriptors) {
    fieldDescriptorValidator.validate(fieldDescriptor);
  }
}
 
Example #19
Source File: GeoWaveGrpcCliGeoserverService.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public void geoServerAddCoverageCommand(
    final org.locationtech.geowave.service.grpc.protobuf.GeoServerAddCoverageCommandParametersProtos request,
    final StreamObserver<org.locationtech.geowave.service.grpc.protobuf.GeoWaveReturnTypesProtos.StringResponseProtos> responseObserver) {

  final GeoServerAddCoverageCommand cmd = new GeoServerAddCoverageCommand();
  final Map<FieldDescriptor, Object> m = request.getAllFields();
  GeoWaveGrpcServiceCommandUtil.setGrpcToCommandFields(m, cmd);

  final File configFile = GeoWaveGrpcServiceOptions.geowaveConfigFile;
  final OperationParams params = new ManualOperationParams();
  params.getContext().put(ConfigOptions.PROPERTIES_FILE_CONTEXT, configFile);

  cmd.prepare(params);

  LOGGER.info("Executing GeoServerAddCoverageCommand...");
  try {
    final String result = cmd.computeResults(params);
    final StringResponseProtos resp =
        StringResponseProtos.newBuilder().setResponseValue(result).build();
    responseObserver.onNext(resp);
    responseObserver.onCompleted();

  } catch (final Exception e) {
    LOGGER.error("Exception encountered executing command", e);
  }
}
 
Example #20
Source File: DynamicMessage.java    From 365browser with Apache License 2.0 5 votes vote down vote up
public Builder setRepeatedField(FieldDescriptor field,
                                int index, Object value) {
  verifyContainingType(field);
  ensureIsMutable();
  fields.setRepeatedField(field, index, value);
  return this;
}
 
Example #21
Source File: ProtoReflectionTest.java    From bundletool with Apache License 2.0 5 votes vote down vote up
@Test
public void getJavaClassOfMessageField_forSimpleMessageField() {
  Message proto = ApkTargeting.getDefaultInstance();
  FieldDescriptor field = proto.getDescriptorForType().findFieldByName("abi_targeting");

  assertThat(ProtoReflection.getJavaClassOfMessageField(proto, field))
      .isEqualTo(AbiTargeting.class);
}
 
Example #22
Source File: ProtoDynamicMessageSchema.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
Object getFromProtoMessage(Message message) {
  FieldDescriptor fieldDescriptor = getFieldDescriptor(message);
  if (message.hasField(fieldDescriptor)) {
    Message wrapper = (Message) message.getField(fieldDescriptor);
    return convertFromProtoValue(wrapper);
  }
  return null;
}
 
Example #23
Source File: ProtoReflection.java    From bundletool with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the {@link Class} object corresponding to the given message field.
 *
 * <p>If the field is repeated, then returns the class of the single item, rather than the
 * collection class.
 */
@SuppressWarnings("unchecked") // The unchecked cast is executed for proto message field only.
public static <T extends Message> Class<? extends Message> getJavaClassOfMessageField(
    T message, FieldDescriptor field) {
  checkArgument(field.getType().getJavaType().equals(JavaType.MESSAGE));

  if (field.isRepeated()) {
    String fieldGetterName = getterNameForProtoField(field);
    try {
      Method fieldGetter = message.getClass().getMethod(fieldGetterName);
      ParameterizedType fieldTypeArg = (ParameterizedType) fieldGetter.getGenericReturnType();
      checkState(
          fieldTypeArg.getActualTypeArguments().length == 1,
          "Collection representing a repeated field should have exactly one type argument.");
      return (Class<? extends Message>) fieldTypeArg.getActualTypeArguments()[0];
    } catch (NoSuchMethodException e) {
      throw new RuntimeException(
          "Failed to resolve getter of repeated field "
              + field.getName()
              + " in proto "
              + message.getClass().getName(),
          e);
    }
  } else {
    return (Class<? extends Message>) message.getField(field).getClass();
  }
}
 
Example #24
Source File: GeneratedMessage.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/** Set the value of one element of a repeated extension. */
public final <Type> BuilderType setExtension(
    final Extension<MessageType, List<Type>> extension,
    final int index, final Type value) {
  verifyExtensionContainingType(extension);
  ensureExtensionsIsMutable();
  final FieldDescriptor descriptor = extension.getDescriptor();
  extensions.setRepeatedField(
    descriptor, index,
    extension.singularToReflectionType(value));
  onChanged();
  return (BuilderType) this;
}
 
Example #25
Source File: FieldMasks.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
private static String getFieldName(String currentField, FieldDescriptor field) {
  if (currentField.isEmpty()) {
    return field.getName();
  } else {
    return currentField + "." + field.getName();
  }
}
 
Example #26
Source File: GeneratedMessage.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Set the value of one element of a repeated extension. */
public final <Type> BuilderType setExtension(
    final GeneratedExtension<MessageType, List<Type>> extension,
    final int index, final Type value) {
  verifyExtensionContainingType(extension);
  ensureExtensionsIsMutable();
  final FieldDescriptor descriptor = extension.getDescriptor();
  extensions.setRepeatedField(
    descriptor, index,
    extension.singularToReflectionType(value));
  onChanged();
  return (BuilderType) this;
}
 
Example #27
Source File: FieldScopeLogic.java    From curiostack with MIT License 5 votes vote down vote up
@Override
public void validate(
    Descriptor rootDescriptor, FieldDescriptorValidator fieldDescriptorValidator) {
  super.validate(rootDescriptor, fieldDescriptorValidator);
  for (int fieldNumber : fieldNumbers) {
    FieldDescriptor fieldDescriptor = rootDescriptor.findFieldByNumber(fieldNumber);
    checkArgument(
        fieldDescriptor != null,
        "Message type %s has no field with number %s.",
        rootDescriptor.getFullName(),
        fieldNumber);
    fieldDescriptorValidator.validate(fieldDescriptor);
  }
}
 
Example #28
Source File: AbstractMessage.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public BuilderType clear() {
  for (final Map.Entry<FieldDescriptor, Object> entry :
       getAllFields().entrySet()) {
    clearField(entry.getKey());
  }
  return (BuilderType) this;
}
 
Example #29
Source File: DynamicMessage.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Object getField(FieldDescriptor field) {
  verifyContainingType(field);
  Object result = fields.getField(field);
  if (result == null) {
    if (field.isRepeated()) {
      result = Collections.emptyList();
    } else if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
      result = getDefaultInstance(field.getMessageType());
    } else {
      result = field.getDefaultValue();
    }
  }
  return result;
}
 
Example #30
Source File: JsonFormat.java    From jigsaw-payment with Apache License 2.0 5 votes vote down vote up
protected void print(Message message, JsonGenerator generator) throws IOException {

        for (Iterator<Map.Entry<FieldDescriptor, Object>> iter = message.getAllFields().entrySet().iterator(); iter.hasNext();) {
            Map.Entry<FieldDescriptor, Object> field = iter.next();
            printField(field.getKey(), field.getValue(), generator);
            if (iter.hasNext()) {
                generator.print(",");
            }
        }
        if (message.getUnknownFields().asMap().size() > 0)
            generator.print(", ");
        printUnknownFields(message.getUnknownFields(), generator);
    }