com.google.protobuf.DescriptorProtos.FieldDescriptorProto Java Examples

The following examples show how to use com.google.protobuf.DescriptorProtos.FieldDescriptorProto. 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: GrpcDocStringExtractor.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Nullable
private static String appendToFullName(
        DescriptorProto messageDescriptor, List<Integer> path, String fullNameSoFar) {
    switch (path.get(0)) {
        case DescriptorProto.NESTED_TYPE_FIELD_NUMBER:
            final DescriptorProto nestedMessage = messageDescriptor.getNestedType(path.get(1));
            return appendMessageToFullName(nestedMessage, path, fullNameSoFar);
        case DescriptorProto.ENUM_TYPE_FIELD_NUMBER:
            final EnumDescriptorProto enumDescriptor = messageDescriptor.getEnumType(path.get(1));
            return appendEnumToFullName(enumDescriptor, path, fullNameSoFar);
        case DescriptorProto.FIELD_FIELD_NUMBER:
            final FieldDescriptorProto fieldDescriptor = messageDescriptor.getField(path.get(1));
            return appendFieldComponent(fullNameSoFar, fieldDescriptor.getName());
        default:
            return null;
    }
}
 
Example #2
Source File: PrintMessageFile.java    From saluki with Apache License 2.0 6 votes vote down vote up
private String getMessageJavaType(String packageName, DescriptorProto sourceMessageDesc,
    FieldDescriptorProto field) {
  String fieldType = CommonUtils.findNotIncludePackageType(field.getTypeName());
  Map<String, Pair<DescriptorProto, List<FieldDescriptorProto>>> nestedFieldType =
      transform(sourceMessageDesc);
  // isMap
  if (nestedFieldType.containsKey(fieldType)) {
    Pair<DescriptorProto, List<FieldDescriptorProto>> nestedFieldPair =
        nestedFieldType.get(fieldType);
    if (nestedFieldPair.getRight().size() == 2) {
      DescriptorProto mapSourceMessageDesc = nestedFieldPair.getLeft();
      List<FieldDescriptorProto> mapFieldList = nestedFieldPair.getRight();
      String nestedJavaType =
          "java.util.Map<" + findJavaType(packageName, mapSourceMessageDesc, mapFieldList.get(0))
              + "," + findJavaType(packageName, mapSourceMessageDesc, mapFieldList.get(1)) + ">";
      return nestedJavaType;
    } else {
      return null;
    }
  } else {
    return CommonUtils.findPojoTypeFromCache(field.getTypeName(), pojoTypeCache);
  }
}
 
Example #3
Source File: ExtensionPool.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
private void add(List<FieldDescriptorProto> extensions) {
  for (int i = 0; i < extensions.size(); i++) {
    pathSegments.push(i);
    FieldDescriptorProto extensionProto = extensions.get(i);
    String extendee = resolve(extensionProto.getExtendee());
    Multimap<String, Extension> messageExtensions = builder.get(extendee);
    if (messageExtensions == null) {
      messageExtensions = ArrayListMultimap.create();
      builder.put(extendee, messageExtensions);
    }
    String path = DOT_JOINER.join(pathSegments.descendingIterator());
    DescriptorProtos.SourceCodeInfo.Location location = locationMap.get(path).get(0);
    // Since paths are only unique within a file, we need a synthetic path to make them unique,
    // given that paths are used to uniquely identify elements in a ProtoFile, and we're
    // stuffing elements from another file into it.
    path = currentFile.getName() + ":" + path;
    Location fileLocation = new SimpleLocation(String.format(
        "%s:%d:%d", currentFile.getName(), location.getSpan(0) + 1, location.getSpan(1) + 1));
    Extension extension = new Extension(extensionProto, location, path, fileLocation);
    messageExtensions.put(getExtensionFieldName(extensionProto.getName()), extension);
    pathSegments.pop();
  }
}
 
Example #4
Source File: MessageType.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
private boolean checkCyclic(Set<MessageType> visited, MessageType message) {
  if (!visited.add(this)) {
    return false;
  }
  for (Field field : fields) {
    TypeRef type = field.getType();
    if (type.getKind() == FieldDescriptorProto.Type.TYPE_MESSAGE) {
      if (message == type.getMessageType()) {
        return true;
      }
      if (type.getMessageType().checkCyclic(visited, message)) {
        // If there is a cycle to message via this, then this is also cyclic. That's the nature
        // of a cycle.
        return true;
      }
    }
  }
  return false;
}
 
Example #5
Source File: ReferenceResolver.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
/**
 * Resolves a type based on the given partial name. This does not assume that the name, as
 * obtained from the descriptor, is in absolute form.
 */
private TypeRef resolveType(Location location, FieldDescriptorProto.Type kind, String name) {
  TypeRef type;
  switch (kind) {
    case TYPE_MESSAGE:
    case TYPE_ENUM:
    case TYPE_GROUP:
      type = symbolTable.resolveType(namespaces.peek(), name);
      break;
    default:
      type = TypeRef.of(kind);
  }
  if (type == null) {
    model.getDiagReporter().report(Diag.error(location, "Unresolved type '%s'", name));
  }
  return type;
}
 
Example #6
Source File: ProtobufDecompiler.java    From sql-layer with GNU Affero General Public License v3.0 6 votes vote down vote up
public void decompile(FileDescriptorProto fileDescriptor) throws IOException {
    if (fileDescriptor.hasPackage()) {
        indentedFormat("package %s;", fileDescriptor.getPackage());
        absolutePackage = "." + fileDescriptor.getPackage() + ".";
    }
    for (String dependency : fileDescriptor.getDependencyList()) {
        indentedFormat("import \"%s\";", dependency);
    }
    if (fileDescriptor.hasOptions()) {
        decompileOptions(fileDescriptor.getOptions());
    }
    decompileMembers(fileDescriptor.getEnumTypeList(),
                     fileDescriptor.getMessageTypeList(),
                     Collections.<FieldDescriptorProto>emptyList(),
                     Collections.<DescriptorProto.ExtensionRange>emptyList(),
                     fileDescriptor.getExtensionList());
    for (ServiceDescriptorProto serviceDescriptor : fileDescriptor.getServiceList()) {
        decompile(serviceDescriptor);
    }
    newline();
    flush();
}
 
Example #7
Source File: ExtensionPool.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
private Extension(FieldDescriptorProto proto, DescriptorProtos.SourceCodeInfo.Location location,
    String path, Location fileLocation) {
  this.proto = proto;
  this.location = location;
  this.path = path;
  this.fileLocation = fileLocation;
}
 
Example #8
Source File: PrintMessageFile.java    From saluki with Apache License 2.0 5 votes vote down vote up
@Override
protected List<String> collectFileData() {
  String sourePackageName = super.getSourcePackageName();
  String className = super.getClassName();
  String packageName = sourePackageName.toLowerCase();
  List<String> fileData = Lists.newArrayList();
  fileData.add("package " + packageName + ";");
  fileData.add(System.getProperty("line.separator"));
  fileData.add("import io.github.saluki.serializer.ProtobufAttribute;");
  fileData.add("import io.github.saluki.serializer.ProtobufEntity;");
  fileData.add(System.getProperty("line.separator"));
  fileData.add("@ProtobufEntity(" + sourePackageName + "." + className + ".class)");
  fileData.add("public class " + className + "{");
  for (int i = 0; i < messageFields.size(); i++) {
    FieldDescriptorProto messageField = messageFields.get(i);
    String javaType = findJavaType(packageName, sourceMessageDesc, messageField);
    if (messageField.getLabel() == Label.LABEL_REPEATED && javaType != null) {
      if (!javaType.contains("java.util.Map")) {
        javaType = "java.util.ArrayList<" + javaType + ">";
      }
    }
    String fieldName = messageField.getName();
    fileData.add(System.getProperty("line.separator"));
    fileData.add("    @ProtobufAttribute");
    fileData.add("    private " + javaType + " " + fieldName + ";");
    fileData.add(System.getProperty("line.separator"));
    fileData.add("    public " + javaType + " get" + captureName(fieldName) + "(){");
    fileData.add("        return this." + fieldName + ";");
    fileData.add("}");
    fileData.add(System.getProperty("line.separator"));
    fileData.add(
        "    public void set" + captureName(fieldName) + "(" + javaType + " " + fieldName + "){");
    fileData.add("        this." + fieldName + "=" + fieldName + ";");
    fileData.add("}");
    fileData.add(System.getProperty("line.separator"));
  }
  fileData.add("}");
  return fileData;

}
 
Example #9
Source File: TypesBuilderFromDescriptor.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * TODO (guptasu): only needed to create hard coded Types (Struct, ListValue, and Value). Check
 * if this can be removed. Create the Protobuf.Type instance from descriptorProto.
 */
private static Type createType(String typeName, DescriptorProto descriptorProto,
    String fileName) {
  Type.Builder coreTypeBuilder = Type.newBuilder().setName(typeName);

  int count = 1;
  for (FieldDescriptorProto fieldProto : descriptorProto.getFieldList()) {
    Field.Kind fieldKind = Field.Kind.valueOf(fieldProto.getType().getNumber());
    Cardinality cardinality = Cardinality.CARDINALITY_OPTIONAL;
    if (fieldProto.getLabel() == Label.LABEL_REPEATED) {
      cardinality = Cardinality.CARDINALITY_REPEATED;
    }
    Field.Builder coreFieldBuilder = Field
        .newBuilder()
        .setName(fieldProto.getName())
        .setNumber(count++)
        .setKind(fieldKind)
        .setCardinality(cardinality);
    if (fieldKind == Kind.TYPE_MESSAGE || fieldKind == Kind.TYPE_ENUM) {
      String typeFullName =
          fieldProto.getTypeName().startsWith(".") ? fieldProto.getTypeName().substring(1)
              : fieldProto.getTypeName();
      coreFieldBuilder.setTypeUrl(TYPE_SERVICE_BASE_URL + typeFullName);
    }
    coreTypeBuilder.addFields(coreFieldBuilder.build());
  }
  coreTypeBuilder.setSourceContext(SourceContext.newBuilder().setFileName(fileName));
  coreTypeBuilder.setSyntax(Syntax.SYNTAX_PROTO3);
  return coreTypeBuilder.build();
}
 
Example #10
Source File: BuilderVisitor.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
protected void addFieldToMessageAncestor(
    int generationsToSkip,
    FieldDescriptorProto.Builder fieldDesc,
    SourceCodeInfo.Location location) {
  BuilderVisitorNodeInfo ancestorInfo = getAncestorInfo(generationsToSkip);
  if (ancestorInfo instanceof MessageNodeInfo) {
    ((MessageNodeInfo) ancestorInfo).addNewField(fieldDesc, location);
    setModified(true);
  } else {
    throw new RuntimeException(
        String.format(
            "Tried to add a field to a %s, but can only add to %s",
            ancestorInfo.node().getClass(), DescriptorProto.Builder.class));
  }
}
 
Example #11
Source File: ProtobufDecompiler.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void findGroups(List<FieldDescriptorProto> fieldDescriptors,
                          Map<String,DescriptorProto> groups) {
    for (FieldDescriptorProto fieldDescriptor : fieldDescriptors) {
        if (fieldDescriptor.getType() == Type.TYPE_GROUP) {
            groups.put(fieldDescriptor.getTypeName(), null);
        }
    }
}
 
Example #12
Source File: ProtobufDecompiler.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void decompileFields(List<FieldDescriptorProto> fieldDescriptors,
                               Map<String,DescriptorProto> groups)
        throws IOException {
    for (FieldDescriptorProto fieldDescriptor : fieldDescriptors) {
        String label = LABELS.get(fieldDescriptor.getLabel());
        String type = TYPES.get(fieldDescriptor.getType());
        String name = fieldDescriptor.getName();
        if (fieldDescriptor.hasTypeName()) {
            type = fieldDescriptor.getTypeName();
            if ((absolutePackage != null) && type.startsWith(absolutePackage)) {
                type = type.substring(absolutePackage.length());
            }
        }
        DescriptorProto groupDescriptor = null;
        if (fieldDescriptor.getType() == Type.TYPE_GROUP) {
            groupDescriptor = groups.get(type);
            if (groupDescriptor != null) {
                name = type;
                type = "group";
            }
        }
        indentedFormat("%s %s %s = %d",
                       label, type, name, fieldDescriptor.getNumber());
        if (fieldDescriptor.hasOptions() || fieldDescriptor.hasDefaultValue()) {
            write(defaultAndOptions(fieldDescriptor.hasOptions() ? fieldDescriptor.getOptions() : null,
                                    fieldDescriptor.hasDefaultValue() ? fieldDescriptor.getDefaultValue() : null));
        }
        if (groupDescriptor == null) {
            write(";");
        }
        else {
            decompileMessageBody(groupDescriptor);
        }
    }
}
 
Example #13
Source File: AISToProtobuf.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void addColumn(Column column) {
    String fieldName = uniqueIdent(ident(column.getName(), false), fieldNames);
    fieldBuilder = messageBuilder.addFieldBuilder();
    fieldBuilder.setName(fieldName);
    fieldBuilder.setLabel(Label.LABEL_OPTIONAL);
    FieldOptions.Builder fieldBuilderOptions = FieldOptions.newBuilder();
    ColumnOptions.Builder columnOptions = ColumnOptions.newBuilder();
    if (!fieldName.equals(column.getName())) {
        columnOptions.setName(column.getName());
    }
    columnOptions.setSqlType(column.getTypeDescription().toUpperCase());
    columnOptions.setUuid(column.getUuid().toString());
    priorField = null;
    if (priorMessage != null) {
        for (FieldDescriptorProto field : priorMessage.getFieldList()) {
            FieldOptions options = field.getOptions();
            if ((options != null) &&
                (options.hasExtension(ColumnOptions.fdbsql))) {
                ColumnOptions coptions = options.getExtension(ColumnOptions.fdbsql);
                if (coptions.getUuid().equals(columnOptions.getUuid())) {
                    priorField = field;
                    break;
                }
            }
        }
    }
    setColumnType(column, columnOptions);
    setFieldNumber();
    fieldBuilderOptions.setExtension(ColumnOptions.fdbsql, columnOptions.build());
    fieldBuilder.setOptions(fieldBuilderOptions);
    if (column.getNullable() && 
        ((column.getDefaultValue() != null) ||
         (column.getDefaultFunction() != null))) {
        addNullForField(column.getName(), fieldBuilder.getNumber());
    }
}
 
Example #14
Source File: AISToProtobuf.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void addNullForField(String columnName, int forField) {
    String fieldName = uniqueIdent("_" + ident(columnName, false) + "_is_null", fieldNames);
    fieldBuilder = messageBuilder.addFieldBuilder();
    fieldBuilder.setName(fieldName);
    fieldBuilder.setType(Type.TYPE_BOOL);
    fieldBuilder.setLabel(Label.LABEL_OPTIONAL);
    FieldOptions.Builder fieldBuilderOptions = FieldOptions.newBuilder();
    ColumnOptions.Builder columnOptions = ColumnOptions.newBuilder();
    columnOptions.setNullForField(forField);
    priorField = null;
    if (priorMessage != null) {
        for (FieldDescriptorProto field : priorMessage.getFieldList()) {
            FieldOptions options = field.getOptions();
            if ((options != null) &&
                (options.hasExtension(ColumnOptions.fdbsql))) {
                ColumnOptions coptions = options.getExtension(ColumnOptions.fdbsql);
                if (coptions.hasNullForField() &&
                    (coptions.getNullForField() == forField)) {
                    priorField = field;
                    break;
                }
            }
        }
    }
    setFieldNumber();
    fieldBuilderOptions.setExtension(ColumnOptions.fdbsql, columnOptions.build());
    fieldBuilder.setOptions(fieldBuilderOptions);
}
 
Example #15
Source File: AISToProtobuf.java    From sql-layer with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void addChildTable(Table table) {
    String fieldName = uniqueIdent(ident(table.getName().getTableName(), false), fieldNames);
    fieldBuilder = messageBuilder.addFieldBuilder();
    fieldBuilder.setName(fieldName);
    fieldBuilder.setLabel(Label.LABEL_REPEATED);
    fieldBuilder.setType(Type.TYPE_MESSAGE);
    fieldBuilder.setTypeName(tableMessageNames.get(table));
    FieldOptions.Builder fieldBuilderOptions = FieldOptions.newBuilder();
    ColumnOptions.Builder columnOptions = ColumnOptions.newBuilder();
    columnOptions.setUuid(table.getUuid().toString());
    priorField = null;
    if (priorMessage != null) {
        for (FieldDescriptorProto field : priorMessage.getFieldList()) {
            FieldOptions options = field.getOptions();
            if ((options != null) &&
                (options.hasExtension(ColumnOptions.fdbsql))) {
                ColumnOptions coptions = options.getExtension(ColumnOptions.fdbsql);
                if (coptions.getUuid().equals(columnOptions.getUuid())) {
                    priorField = field;
                    break;
                }
            }
        }
    }
    setFieldNumber();
    fieldBuilderOptions.setExtension(ColumnOptions.fdbsql, columnOptions.build());
    fieldBuilder.setOptions(fieldBuilderOptions);
}
 
Example #16
Source File: DescriptorsTest.java    From travelguide with Apache License 2.0 5 votes vote down vote up
public void testFieldTypeEnumMapping() throws Exception {
  assertEquals(FieldDescriptor.Type.values().length,
      FieldDescriptorProto.Type.values().length);
  for (FieldDescriptor.Type type : FieldDescriptor.Type.values()) {
    FieldDescriptorProto.Type protoType = type.toProto();
    assertEquals("TYPE_" + type.name(), protoType.name());
    assertEquals(type, FieldDescriptor.Type.valueOf(protoType));
  }
}
 
Example #17
Source File: DescriptorsTest.java    From travelguide with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that the DescriptorValidationException works as intended.
 */
public void testDescriptorValidatorException() throws Exception {
  FileDescriptorProto fileDescriptorProto = FileDescriptorProto.newBuilder()
    .setName("foo.proto")
    .addMessageType(DescriptorProto.newBuilder()
    .setName("Foo")
      .addField(FieldDescriptorProto.newBuilder()
        .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL)
        .setType(FieldDescriptorProto.Type.TYPE_INT32)
        .setName("foo")
        .setNumber(1)
        .setDefaultValue("invalid")
        .build())
      .build())
    .build();
  try {
    Descriptors.FileDescriptor.buildFrom(fileDescriptorProto,
        new FileDescriptor[0]);
    fail("DescriptorValidationException expected");
  } catch (DescriptorValidationException e) {
    // Expected; check that the error message contains some useful hints
    assertTrue(e.getMessage().indexOf("foo") != -1);
    assertTrue(e.getMessage().indexOf("Foo") != -1);
    assertTrue(e.getMessage().indexOf("invalid") != -1);
    assertTrue(e.getCause() instanceof NumberFormatException);
    assertTrue(e.getCause().getMessage().indexOf("invalid") != -1);
  }
}
 
Example #18
Source File: DescriptorsTest.java    From travelguide with Apache License 2.0 5 votes vote down vote up
public void testHiddenDependency() throws Exception {
  FileDescriptorProto barProto = FileDescriptorProto.newBuilder()
      .setName("bar.proto")
      .addMessageType(DescriptorProto.newBuilder().setName("Bar"))
      .build();
  FileDescriptorProto forwardProto = FileDescriptorProto.newBuilder()
      .setName("forward.proto")
      .addDependency("bar.proto")
      .build();
  FileDescriptorProto fooProto = FileDescriptorProto.newBuilder()
      .setName("foo.proto")
      .addDependency("forward.proto")
      .addMessageType(DescriptorProto.newBuilder()
          .setName("Foo")
          .addField(FieldDescriptorProto.newBuilder()
              .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL)
              .setTypeName("Bar")
              .setName("bar")
              .setNumber(1)))
      .build();
  FileDescriptor barFile = Descriptors.FileDescriptor.buildFrom(
      barProto, new FileDescriptor[0]);
  FileDescriptor forwardFile = Descriptors.FileDescriptor.buildFrom(
      forwardProto, new FileDescriptor[] {barFile});

  try {
    Descriptors.FileDescriptor.buildFrom(
        fooProto, new FileDescriptor[] {forwardFile});
    fail("DescriptorValidationException expected");
  } catch (DescriptorValidationException e) {
    assertTrue(e.getMessage().indexOf("Bar") != -1);
    assertTrue(e.getMessage().indexOf("is not defined") != -1);
  }
}
 
Example #19
Source File: DescriptorsTest.java    From travelguide with Apache License 2.0 5 votes vote down vote up
public void testPublicDependency() throws Exception {
  FileDescriptorProto barProto = FileDescriptorProto.newBuilder()
      .setName("bar.proto")
      .addMessageType(DescriptorProto.newBuilder().setName("Bar"))
      .build();
  FileDescriptorProto forwardProto = FileDescriptorProto.newBuilder()
      .setName("forward.proto")
      .addDependency("bar.proto")
      .addPublicDependency(0)
      .build();
  FileDescriptorProto fooProto = FileDescriptorProto.newBuilder()
      .setName("foo.proto")
      .addDependency("forward.proto")
      .addMessageType(DescriptorProto.newBuilder()
          .setName("Foo")
          .addField(FieldDescriptorProto.newBuilder()
              .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL)
              .setTypeName("Bar")
              .setName("bar")
              .setNumber(1)))
      .build();
  FileDescriptor barFile = Descriptors.FileDescriptor.buildFrom(
      barProto, new FileDescriptor[0]);
  FileDescriptor forwardFile = Descriptors.FileDescriptor.buildFrom(
      forwardProto, new FileDescriptor[]{barFile});
  Descriptors.FileDescriptor.buildFrom(
      fooProto, new FileDescriptor[] {forwardFile});
}
 
Example #20
Source File: MessageDefinition.java    From protobuf-dynamic with Apache License 2.0 5 votes vote down vote up
private void addField(FieldDescriptorProto.Label label, String type, String name, int num, String defaultVal, OneofBuilder oneofBuilder) {
	FieldDescriptorProto.Builder fieldBuilder = FieldDescriptorProto.newBuilder();
	fieldBuilder.setLabel(label);
	FieldDescriptorProto.Type primType = sTypeMap.get(type);
	if (primType != null) fieldBuilder.setType(primType); else fieldBuilder.setTypeName(type);
	fieldBuilder.setName(name).setNumber(num);
	if (defaultVal != null) fieldBuilder.setDefaultValue(defaultVal);
	if (oneofBuilder != null) fieldBuilder.setOneofIndex(oneofBuilder.getIdx());
	mMsgTypeBuilder.addField(fieldBuilder.build());
}
 
Example #21
Source File: PrintMessageFile.java    From saluki with Apache License 2.0 5 votes vote down vote up
private String findJavaType(String packageName, DescriptorProto sourceMessageDesc,
    FieldDescriptorProto field) {
  switch (field.getType()) {
    case TYPE_ENUM:
      return getMessageJavaType(packageName, sourceMessageDesc, field);
    case TYPE_MESSAGE:
      String javaType = getMessageJavaType(packageName, sourceMessageDesc, field);
      return javaType;
    case TYPE_GROUP:
      logger.info("group have not support yet");
      return null;
    case TYPE_STRING:
      return "String";
    case TYPE_INT64:
      return "Long";
    case TYPE_INT32:
      return "Integer";
    case TYPE_BOOL:
      return "Boolean";
    case TYPE_DOUBLE:
      return "Double";
    case TYPE_FLOAT:
      return "Float";
    default:
      logger.info("have not support this type " + field.getType()
          + ",please contact [email protected] for support");
      return null;
  }
}
 
Example #22
Source File: ReferenceResolver.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
@VisitsBefore
void visit(Method method) {
  // Resolve input and output type of this method.
  TypeRef inputType = resolveType(method.getLocation(),
      FieldDescriptorProto.Type.TYPE_MESSAGE, method.getDescriptor().getInputTypeName());
  if (inputType != null) {
    method.setInputType(inputType);
  }
  TypeRef outputType = resolveType(method.getLocation(),
      FieldDescriptorProto.Type.TYPE_MESSAGE, method.getDescriptor().getOutputTypeName());
  if (outputType != null) {
    method.setOutputType(outputType);
  }
  findOptionTypes(method.getOptionFields());
}
 
Example #23
Source File: PrintMessageFile.java    From saluki with Apache License 2.0 5 votes vote down vote up
private Map<String, Pair<DescriptorProto, List<FieldDescriptorProto>>> transform(
    DescriptorProto sourceMessageDesc) {
  Map<String, Pair<DescriptorProto, List<FieldDescriptorProto>>> nestedFieldMap =
      Maps.newHashMap();
  sourceMessageDesc.getNestedTypeList().forEach(new Consumer<DescriptorProto>() {

    @Override
    public void accept(DescriptorProto t) {
      nestedFieldMap.put(t.getName(),
          new ImmutablePair<DescriptorProto, List<FieldDescriptorProto>>(t, t.getFieldList()));
    }

  });
  return nestedFieldMap;
}
 
Example #24
Source File: DescriptorNormalizer.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/** In proto3, repeated fields of scalar numeric types use packed encoding by default */
private boolean isDefaultPackedEncoding(Field field) {
  if (field.getSyntax() == Syntax.SYNTAX_PROTO3 && field.isRepeated()) {
    FieldDescriptorProto.Type fieldType = field.getProto().getType();
    if (fieldType != FieldDescriptorProto.Type.TYPE_GROUP
        && fieldType != FieldDescriptorProto.Type.TYPE_BYTES
        && fieldType != FieldDescriptorProto.Type.TYPE_STRING
        && fieldType != FieldDescriptorProto.Type.TYPE_MESSAGE) {
      return true;
    }
  }
  return false;
}
 
Example #25
Source File: DescriptorGenerator.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
private FieldDescriptorProto generateField(Field field) {
  FieldDescriptorProto.Builder builder = FieldDescriptorProto.newBuilder();
  builder.setName(getFieldName(field));
  builder.setNumber(field.getNumber());
  builder.setLabel(toLabel(field.getCardinality()));
  builder.setType(toType(field.getKind()));
  if (field.getKind() == Kind.TYPE_ENUM
      || field.getKind() == Kind.TYPE_MESSAGE
      || field.getKind() == Kind.TYPE_GROUP) {
    builder.setTypeName(getTypeName(field.getTypeUrl()));
  }
  // NOTE: extendee not supported
  // NOTE: default_value not supported
  if (field.getOneofIndex() != 0) {
    // Index in the containing type's oneof_decl is zero-based.
    // Index in google.protobuf.type.Field.oneof_index is one-based.
    builder.setOneofIndex(field.getOneofIndex() - 1);
  }
  if (!Strings.isNullOrEmpty(field.getDefaultValue())) {
    builder.setDefaultValue(field.getDefaultValue());
  }
  FieldOptions options = getFieldOptions(field);
  if (!options.equals(FieldOptions.getDefaultInstance())) {
    builder.setOptions(options);
  }
  return builder.build();
}
 
Example #26
Source File: Descriptors.java    From play-store-api with GNU General Public License v3.0 4 votes vote down vote up
public static Type valueOf(final FieldDescriptorProto.Type type) {
  return values()[type.getNumber() - 1];
}
 
Example #27
Source File: Descriptors.java    From play-store-api with GNU General Public License v3.0 4 votes vote down vote up
public FieldDescriptorProto.Type toProto() {
  return FieldDescriptorProto.Type.forNumber(ordinal() + 1);
}
 
Example #28
Source File: Descriptors.java    From play-store-api with GNU General Public License v3.0 4 votes vote down vote up
private FieldDescriptor(final FieldDescriptorProto proto,
                        final FileDescriptor file,
                        final Descriptor parent,
                        final int index,
                        final boolean isExtension)
                 throws DescriptorValidationException {
  this.index = index;
  this.proto = proto;
  fullName = computeFullName(file, parent, proto.getName());
  this.file = file;
  if (proto.hasJsonName()) {
    jsonName = proto.getJsonName();
  } else {
    jsonName = fieldNameToLowerCamelCase(proto.getName());
  }

  if (proto.hasType()) {
    type = Type.valueOf(proto.getType());
  }

  if (getNumber() <= 0) {
    throw new DescriptorValidationException(this,
      "Field numbers must be positive integers.");
  }

  if (isExtension) {
    if (!proto.hasExtendee()) {
      throw new DescriptorValidationException(this,
        "FieldDescriptorProto.extendee not set for extension field.");
    }
    containingType = null;  // Will be filled in when cross-linking
    if (parent != null) {
      extensionScope = parent;
    } else {
      extensionScope = null;
    }

    if (proto.hasOneofIndex()) {
      throw new DescriptorValidationException(this,
        "FieldDescriptorProto.oneof_index set for extension field.");
    }
    containingOneof = null;
  } else {
    if (proto.hasExtendee()) {
      throw new DescriptorValidationException(this,
        "FieldDescriptorProto.extendee set for non-extension field.");
    }
    containingType = parent;

    if (proto.hasOneofIndex()) {
      if (proto.getOneofIndex() < 0 ||
          proto.getOneofIndex() >= parent.toProto().getOneofDeclCount()) {
        throw new DescriptorValidationException(this,
          "FieldDescriptorProto.oneof_index is out of range for type "
          + parent.getName());
      }
      containingOneof = parent.getOneofs().get(proto.getOneofIndex());
      containingOneof.fieldCount++;
    } else {
      containingOneof = null;
    }
    extensionScope = null;
  }

  file.pool.addSymbol(this);
}
 
Example #29
Source File: Descriptors.java    From play-store-api with GNU General Public License v3.0 4 votes vote down vote up
/** See {@link FileDescriptor#setProto}. */
private void setProto(final FieldDescriptorProto proto) {
  this.proto = proto;
}
 
Example #30
Source File: DescriptorNormalizer.java    From api-compiler with Apache License 2.0 4 votes vote down vote up
private static Kind toCoreFieldKind(FieldDescriptorProto proto) {
  return Kind.valueOf(proto.getType().getNumber());
}