com.google.protobuf.Descriptors.FieldDescriptor.Type Java Examples

The following examples show how to use com.google.protobuf.Descriptors.FieldDescriptor.Type. 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: ProtoFieldInfo.java    From curiostack with MIT License 6 votes vote down vote up
/**
 * Returns the {@link Method} that sets a single value of the field. For repeated and map fields,
 * this is the add or put method that only take an individual element;
 */
Method setValueMethod() {
  StringBuilder setter = new StringBuilder();
  final Class<?>[] args;
  if (isMapField()) {
    setter.append("put");
    args = new Class<?>[] {mapKeyField.javaClass(), javaClass()};
  } else {
    args = new Class<?>[] {javaClass()};
    if (field.isRepeated()) {
      setter.append("add");
    } else {
      setter.append("set");
    }
  }
  setter.append(camelCaseName);
  if (valueType() == Type.ENUM) {
    setter.append("Value");
  }
  try {
    return builderClass.getDeclaredMethod(setter.toString(), args);
  } catch (NoSuchMethodException e) {
    throw new IllegalStateException("Could not find setter.", e);
  }
}
 
Example #2
Source File: CompatibilityTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testFindFieldByNumber() throws Exception {
  Descriptor descriptor = TypicalData.Builder.getDescriptor();
  Collection<FieldDescriptor> fields = descriptor.getFields();
  for (FieldDescriptor field : fields) {
    FieldDescriptor.Type type = field.getType();
    int fieldId = field.getNumber();
    switch (fieldId) {
      case 1:
        assertEquals(Type.INT32, type);
        break;
      case 2:
        assertEquals(Type.BYTES, type);
        break;
      case 3:
        assertEquals(Type.ENUM, type);
        break;
    }
    FieldDescriptor result = descriptor.findFieldByNumber(fieldId);
    assertEquals(field.getNumber(), result.getNumber());
    assertEquals(field.getName(), result.getName());
  }
}
 
Example #3
Source File: ProtoToGql.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
/** Returns a GraphQLOutputType generated from a FieldDescriptor. */
static GraphQLOutputType convertType(
    FieldDescriptor fieldDescriptor, SchemaOptions schemaOptions) {
  final GraphQLOutputType type;

  if (fieldDescriptor.getType() == Type.MESSAGE) {
    type = getReference(fieldDescriptor.getMessageType());
  } else if (fieldDescriptor.getType() == Type.GROUP) {
    type = getReference(fieldDescriptor.getMessageType());
  } else if (fieldDescriptor.getType() == Type.ENUM) {
    type = getReference(fieldDescriptor.getEnumType());
  } else if (schemaOptions.useProtoScalarTypes()) {
    type = PROTO_TYPE_MAP.get(fieldDescriptor.getType());
  } else {
    type = TYPE_MAP.get(fieldDescriptor.getType());
  }

  if (type == null) {
    throw new RuntimeException("Unknown type: " + fieldDescriptor.getType());
  }

  if (fieldDescriptor.isRepeated()) {
    return new GraphQLList(type);
  } else {
    return type;
  }
}
 
Example #4
Source File: DoParse.java    From curiostack with MIT License 5 votes vote down vote up
/**
 * Returns the {@link StackManipulation} for setting the value of a field. This will be all the
 * elements for a repeated field.
 *
 * @param info description of the field to set.
 * @param beforeReadField jump target for before reading a field, used once this field is
 *     completed being set.
 * @param locals the method local variables
 * @param fieldsByName the instance fields
 */
private StackManipulation setFieldValue(
    ProtoFieldInfo info,
    Label beforeReadField,
    LocalVariables<LocalVariable> locals,
    Map<String, FieldDescription> fieldsByName) {
  if (info.isMapField()) {
    return setMapFieldValue(info, beforeReadField, locals, fieldsByName);
  } else {
    final StackManipulation setConcreteValue = invoke(info.setValueMethod());
    final StackManipulation setSingleValue;
    if (info.valueJavaType() == JavaType.MESSAGE) {
      setSingleValue =
          new StackManipulation.Compound(
              TypeCasting.to(new ForLoadedType(info.javaClass())), setConcreteValue);
    } else if (info.valueType() == Type.ENUM && !info.isRepeated()) {
      // For non-repeated enums, we treat unknown as the default value.
      setSingleValue =
          new StackManipulation.Compound(ParseSupport_mapUnknownEnumValue, setConcreteValue);
    } else {
      setSingleValue = setConcreteValue;
    }
    if (info.descriptor().isRepeated()) {
      return setRepeatedFieldValue(info, beforeReadField, locals, fieldsByName, setSingleValue);
    } else {
      // Set a singular value, e.g.,
      // builder.setFoo(readValue());
      return new StackManipulation.Compound(
          locals.load(LocalVariable.builder),
          locals.load(LocalVariable.parser),
          readValue(info, fieldsByName, locals),
          setSingleValue,
          Removal.SINGLE,
          new Goto(beforeReadField));
    }
  }
}
 
Example #5
Source File: Java7BaseTest.java    From compiler with Apache License 2.0 5 votes vote down vote up
protected static HashMap<Integer, Declaration> collectDeclarations(FieldDescriptor field, Object value) {
	HashMap<Integer, Declaration> nodeDeclaration = new HashMap<Integer, Declaration>();
	if (field.isRepeated()) {
		// Repeated field. Print each element.
		for (Iterator<?> iter = ((List<?>) value).iterator(); iter.hasNext();)
			if (field.getType() == Type.MESSAGE)
				nodeDeclaration.putAll(collectDeclarations((Message) iter.next()));
	}
	return nodeDeclaration;
}
 
Example #6
Source File: CompatibilityTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testEnumDescriptor() throws Exception {
  Descriptor descriptor = TypicalData.Builder.getDescriptor();
  FieldDescriptor fieldDescriptor = descriptor.findFieldByNumber(3);
  assertEquals(Type.ENUM, fieldDescriptor.getType());
  EnumDescriptor enumDescriptor = fieldDescriptor.getEnumType();
  assertNotNull(enumDescriptor);

  EnumValueDescriptor enumValueDescriptor = enumDescriptor.findValueByNumber(1);
  assertEquals(1, enumValueDescriptor.getNumber());
  assertEquals("VALUE1", enumValueDescriptor.getName());
}
 
Example #7
Source File: DoParse.java    From curiostack with MIT License 4 votes vote down vote up
/**
 * Returns the {@link StackManipulation} for setting the value of a normal repeated field.
 *
 * <p>Roughly equivalent to:
 *
 * <pre>{@code
 * ParseSupport.parseArrayStart(parser);
 * while (!ParseSupport.checkArrayEnd(parser)) {
 *   builder.addFoo(readValue());
 * }
 * }</pre>
 */
private StackManipulation setRepeatedFieldValue(
    ProtoFieldInfo info,
    Label beforeReadField,
    LocalVariables<LocalVariable> locals,
    Map<String, FieldDescription> fieldsByName,
    StackManipulation setSingleValue) {
  Label arrayStart = new Label();

  StackManipulation.Compound beforeRead =
      new StackManipulation.Compound(
          locals.load(LocalVariable.parser),
          ParseSupport_parseArrayStart,
          new SetJumpTargetLabel(arrayStart),
          locals.load(LocalVariable.parser),
          ParseSupport_throwIfRepeatedNull,
          locals.load(LocalVariable.parser),
          ParseSupport_checkArrayEnd,
          new IfTrue(beforeReadField));

  Label afterSet = new Label();

  StackManipulation.Compound setValueAndPrepareForNext =
      new StackManipulation.Compound(
          setSingleValue,
          Removal.SINGLE,
          new SetJumpTargetLabel(afterSet),
          locals.load(LocalVariable.parser),
          Parser_nextValue,
          Removal.SINGLE,
          new Goto(arrayStart));

  if (info.valueType() == Type.ENUM) {
    // We special-case enum since we may need to skip unknown values.
    return new StackManipulation.Compound(
        beforeRead,
        locals.load(LocalVariable.parser),
        readValue(info, fieldsByName, locals),
        locals.store(LocalVariable.intvalue),
        locals.load(LocalVariable.intvalue),
        IntegerConstant.forValue(-1),
        new IfEqual(int.class, afterSet),
        locals.load(LocalVariable.builder),
        locals.load(LocalVariable.intvalue),
        setValueAndPrepareForNext);
  } else {
    return new StackManipulation.Compound(
        beforeRead,
        locals.load(LocalVariable.builder),
        locals.load(LocalVariable.parser),
        readValue(info, fieldsByName, locals),
        setValueAndPrepareForNext);
  }
}
 
Example #8
Source File: DoParse.java    From curiostack with MIT License 4 votes vote down vote up
/**
 * Returns the {@link StackManipulation} for setting the value of a map field.
 *
 * <p>Roughly equivalent to:
 *
 * <pre>{@code
 * ParseSupport.parseObjectStart(parser);
 * while (!ParseSupport.checkObjectEnd(parser.currentToken())) {
 *   builder.putFoo(readKey(), readValue());
 * }
 * }</pre>
 */
private StackManipulation setMapFieldValue(
    ProtoFieldInfo info,
    Label beforeReadField,
    LocalVariables<LocalVariable> locals,
    Map<String, FieldDescription> fieldsByName) {
  final StackManipulation setConcreteValue = invoke(info.setValueMethod());
  final StackManipulation setMapEntry;
  if (info.valueJavaType() == JavaType.MESSAGE) {
    setMapEntry =
        new StackManipulation.Compound(
            TypeCasting.to(new ForLoadedType(info.javaClass())), setConcreteValue);
  } else {
    setMapEntry = setConcreteValue;
  }
  Label mapStart = new Label();
  Label afterSet = new Label();

  StackManipulation.Compound beforeReadKey =
      new StackManipulation.Compound(
          locals.load(LocalVariable.parser),
          ParseSupport_parseObjectStart,
          new SetJumpTargetLabel(mapStart),
          locals.load(LocalVariable.parser),
          Parser_currentToken,
          ParseSupport_checkObjectEnd,
          new IfTrue(beforeReadField));

  StackManipulation.Compound setValueAndPrepareForNext =
      new StackManipulation.Compound(
          setMapEntry,
          Removal.SINGLE,
          new SetJumpTargetLabel(afterSet),
          locals.load(LocalVariable.parser),
          Parser_nextToken,
          Removal.SINGLE,
          new Goto(mapStart));

  if (info.valueType() == Type.ENUM) {
    // We special-case enum since we may need to skip unknown values.
    final LocalVariable keyVar;
    switch (info.mapKeyField().valueJavaType()) {
      case INT:
        keyVar = LocalVariable.intMapKey;
        break;
      case LONG:
        keyVar = LocalVariable.longMapKey;
        break;
      case BOOLEAN:
        keyVar = LocalVariable.boolMapKey;
        break;
      case STRING:
        keyVar = LocalVariable.stringMapKey;
        break;
      default:
        throw new IllegalArgumentException("Invalid map key type");
    }

    return new StackManipulation.Compound(
        beforeReadKey,
        locals.load(LocalVariable.parser),
        readValue(info.mapKeyField(), fieldsByName, locals),
        locals.store(keyVar),
        locals.load(LocalVariable.parser),
        Parser_nextToken,
        Removal.SINGLE,
        locals.load(LocalVariable.parser),
        readValue(info, fieldsByName, locals),
        locals.store(LocalVariable.intvalue),
        locals.load(LocalVariable.intvalue),
        IntegerConstant.forValue(-1),
        new IfEqual(int.class, afterSet),
        locals.load(LocalVariable.builder),
        locals.load(keyVar),
        locals.load(LocalVariable.intvalue),
        setValueAndPrepareForNext);
  } else {
    return new StackManipulation.Compound(
        beforeReadKey,
        locals.load(LocalVariable.builder),
        locals.load(LocalVariable.parser),
        readValue(info.mapKeyField(), fieldsByName, locals),
        locals.load(LocalVariable.parser),
        Parser_nextToken,
        Removal.SINGLE,
        locals.load(LocalVariable.parser),
        readValue(info, fieldsByName, locals),
        setValueAndPrepareForNext);
  }
}
 
Example #9
Source File: ProtoMessageVisitor.java    From compiler with Apache License 2.0 4 votes vote down vote up
private void visitFieldValue(FieldDescriptor field, Object value) {
	if (field.getType() == Type.MESSAGE)
		visit((Message) value);
}
 
Example #10
Source File: MapsTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public void testMapFieldDescriptor() throws Exception {
  Descriptor descriptor = MapMsg.Builder.getDescriptor();
  FieldDescriptor stringStringField = descriptor.findFieldByNumber(1);
  FieldDescriptor boolEnumField = descriptor.findFieldByNumber(7);
  assertEquals(Type.MESSAGE, stringStringField.getType());
  assertTrue(stringStringField.isRepeated());

  Descriptor entryDescriptor = stringStringField.getMessageType();
  assertNotNull(entryDescriptor);
  assertEquals(2, entryDescriptor.getFields().size());

  FieldDescriptor keyFieldDescriptor = entryDescriptor.findFieldByNumber(1);
  FieldDescriptor valueFieldDescriptor = entryDescriptor.findFieldByNumber(2);
  assertEquals("key", keyFieldDescriptor.getName());
  assertEquals(Type.STRING, keyFieldDescriptor.getType());
  assertEquals("value", valueFieldDescriptor.getName());
  assertEquals(Type.STRING, valueFieldDescriptor.getType());

  MapMsg msg = getFilledMessage();
  Object rawValue = msg.getField(stringStringField);
  assertTrue(rawValue instanceof List);
  List<?> list = (List<?>) rawValue;
  assertEquals(2, list.size());
  Object rawEntry = list.get(0);
  assertTrue(rawEntry instanceof MapEntry);
  MapEntry<?, ?> entry = (MapEntry<?, ?>) rawEntry;
  assertEquals("duck", entry.getKey());
  assertEquals("quack", entry.getValue());

  rawEntry = msg.getRepeatedField(stringStringField, 1);
  assertTrue(rawEntry instanceof MapEntry);
  entry = (MapEntry<?, ?>) rawEntry;
  assertEquals("cat", entry.getKey());
  assertEquals("meow", entry.getValue());

  list = (List<?>) msg.getField(boolEnumField);
  entry = (MapEntry<?, ?>) list.get(0);
  assertTrue(entry.getKey() instanceof Boolean);
  assertTrue(entry.getValue() instanceof Integer);
  assertEquals(Boolean.TRUE, entry.getKey());
  assertEquals(Integer.valueOf(0), entry.getValue());
  entry = (MapEntry<?, ?>) msg.getRepeatedField(boolEnumField, 1);
  assertTrue(entry.getKey() instanceof Boolean);
  assertTrue(entry.getValue() instanceof Integer);
  assertEquals(Boolean.FALSE, entry.getKey());
  assertEquals(Integer.valueOf(2), entry.getValue());

  MapMsg.Builder builder = msg.toBuilder();
  MapEntry<String, String> stringStringEntry =
      ((List<MapEntry<String, String>>) msg.getField(stringStringField)).get(0);
  stringStringEntry = stringStringEntry.toBuilder().setValue("neigh").build();
  builder.setRepeatedField(stringStringField, 0, stringStringEntry);
  stringStringEntry = stringStringEntry.toBuilder().setKey("cow").setValue("moo").build();
  builder.addRepeatedField(stringStringField, stringStringEntry);
  assertEquals(3, builder.getStringStringCount());
  assertEquals(3, builder.getRepeatedFieldCount(stringStringField));
  assertEquals("moo", builder.getStringStringOrThrow("cow"));
  builder.clearField(stringStringField);
  assertEquals("default", builder.getStringStringOrDefault("cow", "default"));
  assertEquals(0, builder.getStringStringCount());

  List<MapEntry<String, String>> newStringStringList = new ArrayList<>();
  newStringStringList.add(
      stringStringEntry.toBuilder().setKey("parrot").setValue("squawk").build());
  newStringStringList.add(stringStringEntry.toBuilder().setKey("pig").setValue("oink").build());
  builder.setField(stringStringField, newStringStringList);
  assertEquals("squawk", builder.getStringStringOrThrow("parrot"));
  assertEquals("oink", builder.getStringStringOrThrow("pig"));
}
 
Example #11
Source File: ProtoGenerator.java    From fuchsia with Apache License 2.0 4 votes vote down vote up
private void generateProtoFromDescriptor(FieldDescriptor descriptor,
                                         Appendable out, String indent, Map<Descriptor, Boolean> descriptors)
        throws IOException {
    out.append(indent);
    if (descriptor.isRequired()) {
        out.append("required ");
    }

    if (descriptor.isOptional()) {
        out.append("optional ");
    }

    if (descriptor.isRepeated()) {
        out.append("repeated ");
    }

    if (descriptor.getType().equals(Type.MESSAGE)) {
        out.append(descriptor.getMessageType().getFullName() + " ");
        Descriptor messageType = descriptor.getMessageType();
        if (descriptors.get(messageType) == null) {
            descriptors.put(messageType, false);
        }
    } else if (descriptor.getType().equals(Type.ENUM)) {
        out.append(descriptor.getEnumType().getFullName() + " ");
    } else {
        out.append(descriptor.getType().toString().toLowerCase() + " ");
    }

    out.append(descriptor.getName() + " = " + descriptor.getNumber());

    if (descriptor.hasDefaultValue()) {
        out.append(" [default = ");
        Object defaultValue = descriptor.getDefaultValue();

        if (defaultValue instanceof EnumValueDescriptor) {
            out.append(((EnumValueDescriptor) defaultValue).getName());
        }

        out.append("]");
    }

    out.append(";\n");
}
 
Example #12
Source File: ProtoFieldInfo.java    From curiostack with MIT License 2 votes vote down vote up
/**
 * Returns the {@link Type} of the actual value of this field, which for map fields is the type of
 * the map's value.
 */
FieldDescriptor.Type valueType() {
  return valueField().descriptor().getType();
}