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); } }
private void printMessage(List<DescriptorProto> messageDescList, String javaPackage, String outerClassName) { for (DescriptorProto messageDesc : messageDescList) { String pojoClassType = messageDesc.getName(); String pojoPackageName = javaPackage + "." + outerClassName; String fullpojoType = pojoPackageName.toLowerCase() + "." + pojoClassType; pojoTypes.put(pojoClassType, fullpojoType); PrintMessageFile messageFile = new PrintMessageFile(generatePath, pojoPackageName, pojoClassType); try { messageFile.setMessageFields(messageDesc.getFieldList()); messageFile.setPojoTypeCache(pojoTypes); messageFile.setSourceMessageDesc(messageDesc); } finally { messageFile.print(); } } }
Descriptor(final String fullname) throws DescriptorValidationException { String name = fullname; String packageName = ""; int pos = fullname.lastIndexOf('.'); if (pos != -1) { name = fullname.substring(pos + 1); packageName = fullname.substring(0, pos); } this.index = 0; this.proto = DescriptorProto.newBuilder().setName(name).addExtensionRange( DescriptorProto.ExtensionRange.newBuilder().setStart(1) .setEnd(536870912).build()).build(); this.fullName = fullname; this.containingType = null; this.nestedTypes = new Descriptor[0]; this.enumTypes = new EnumDescriptor[0]; this.fields = new FieldDescriptor[0]; this.extensions = new FieldDescriptor[0]; this.oneofs = new OneofDescriptor[0]; // Create a placeholder FileDescriptor to hold this message. this.file = new FileDescriptor(packageName, this); }
/** See {@link FileDescriptor#setProto}. */ private void setProto(final DescriptorProto proto) { this.proto = proto; for (int i = 0; i < nestedTypes.length; i++) { nestedTypes[i].setProto(proto.getNestedType(i)); } for (int i = 0; i < oneofs.length; i++) { oneofs[i].setProto(proto.getOneofDecl(i)); } for (int i = 0; i < enumTypes.length; i++) { enumTypes[i].setProto(proto.getEnumType(i)); } for (int i = 0; i < fields.length; i++) { fields[i].setProto(proto.getField(i)); } for (int i = 0; i < extensions.length; i++) { extensions[i].setProto(proto.getExtension(i)); } }
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(); }
public void testPackedEnumField() throws Exception { FileDescriptorProto fileDescriptorProto = FileDescriptorProto.newBuilder() .setName("foo.proto") .addEnumType(EnumDescriptorProto.newBuilder() .setName("Enum") .addValue(EnumValueDescriptorProto.newBuilder() .setName("FOO") .setNumber(1) .build()) .build()) .addMessageType(DescriptorProto.newBuilder() .setName("Message") .addField(FieldDescriptorProto.newBuilder() .setName("foo") .setTypeName("Enum") .setNumber(1) .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) .setOptions(DescriptorProtos.FieldOptions.newBuilder() .setPacked(true) .build()) .build()) .build()) .build(); Descriptors.FileDescriptor.buildFrom( fileDescriptorProto, new FileDescriptor[0]); }
private static Optional<String> getFullName(FileDescriptorProto descriptor, List<Integer> path) { String fullNameSoFar = descriptor.getPackage(); switch (path.get(0)) { case FileDescriptorProto.MESSAGE_TYPE_FIELD_NUMBER: DescriptorProto message = descriptor.getMessageType(path.get(1)); return appendMessageToFullName(message, path, fullNameSoFar); case FileDescriptorProto.ENUM_TYPE_FIELD_NUMBER: EnumDescriptorProto enumDescriptor = descriptor.getEnumType(path.get(1)); return Optional.of(appendEnumToFullName(enumDescriptor, path, fullNameSoFar)); case FileDescriptorProto.SERVICE_FIELD_NUMBER: ServiceDescriptorProto serviceDescriptor = descriptor.getService(path.get(1)); fullNameSoFar = appendNameComponent(fullNameSoFar, serviceDescriptor.getName()); if (path.size() > 2) { fullNameSoFar = appendFieldComponent( fullNameSoFar, serviceDescriptor.getMethod(path.get(3)).getName()); } return Optional.of(fullNameSoFar); default: return Optional.empty(); } }
private static Optional<String> appendToFullName( DescriptorProto messageDescriptor, List<Integer> path, String fullNameSoFar) { switch (path.get(0)) { case DescriptorProto.NESTED_TYPE_FIELD_NUMBER: DescriptorProto nestedMessage = messageDescriptor.getNestedType(path.get(1)); return appendMessageToFullName(nestedMessage, path, fullNameSoFar); case DescriptorProto.ENUM_TYPE_FIELD_NUMBER: EnumDescriptorProto enumDescriptor = messageDescriptor.getEnumType(path.get(1)); return Optional.of(appendEnumToFullName(enumDescriptor, path, fullNameSoFar)); case DescriptorProto.FIELD_FIELD_NUMBER: FieldDescriptorProto fieldDescriptor = messageDescriptor.getField(path.get(1)); return Optional.of(appendFieldComponent(fullNameSoFar, fieldDescriptor.getName())); default: return Optional.empty(); } }
Descriptor (final String fullname) throws DescriptorValidationException { String name = fullname; String packageName = ""; int pos = fullname.lastIndexOf ('.'); if (pos != -1) { name = fullname.substring (pos + 1); packageName = fullname.substring (0, pos); } this.index = 0; this.proto = DescriptorProto.newBuilder ().setName (name).addExtensionRange ( DescriptorProto.ExtensionRange.newBuilder ().setStart (1) .setEnd (536870912).build ()).build (); this.fullName = fullname; this.containingType = null; this.nestedTypes = new Descriptor[0]; this.enumTypes = new EnumDescriptor[0]; this.fields = new FieldDescriptor[0]; this.extensions = new FieldDescriptor[0]; this.oneofs = new OneofDescriptor[0]; // Create a placeholder FileDescriptor to hold this message. this.file = new FileDescriptor (packageName, this); }
/** * See {@link FileDescriptor#setProto}. */ private void setProto (final DescriptorProto proto) { this.proto = proto; for (int i = 0; i < nestedTypes.length; i++) { nestedTypes[i].setProto (proto.getNestedType (i)); } for (int i = 0; i < enumTypes.length; i++) { enumTypes[i].setProto (proto.getEnumType (i)); } for (int i = 0; i < fields.length; i++) { fields[i].setProto (proto.getField (i)); } for (int i = 0; i < extensions.length; i++) { extensions[i].setProto (proto.getExtension (i)); } }
private FileDescriptorProto makeCanonicalProto(final FileDescriptor fileDescriptor) { final FileDescriptorProto.Builder protoBuilder = FileDescriptorProto.newBuilder(fileDescriptor.toProto()); for (final FieldDescriptorProto.Builder field : protoBuilder.getExtensionBuilderList()) { makeCanonicalField(field, fileDescriptor.findExtensionByName(field.getName())); } for (final DescriptorProto.Builder message : protoBuilder.getMessageTypeBuilderList()) { makeCanonicalMessage(message, fileDescriptor.findMessageTypeByName(message.getName())); } // for (EnumDescriptorProto.Builder enumProto : // protoBuilder.getEnumTypeBuilderList()) { // makeCanonicalEnum(enumProto, // fileDescriptor.findEnumTypeByName(enumProto.getName())); // } for (final ServiceDescriptorProto.Builder serviceProto : protoBuilder.getServiceBuilderList()) { makeCanonicalService(serviceProto, fileDescriptor.findServiceByName(serviceProto.getName())); } // TODO: incorporate options' tree walking into canonicalization to eliminate double walking return OptionResolver.newBuilder().setCustomOptionsAsExtensions(false) .resolveAllOptionsFor(fileDescriptor, protoBuilder).build(); }
private void buildAllOptions(final FileDescriptorProto.Builder proto) { if (!buildOptions(proto.getOptionsBuilder())) { proto.clearOptions(); } for (final FieldDescriptorProto.Builder extensionProto : proto.getExtensionBuilderList()) { if (!buildOptions(extensionProto.getOptionsBuilder())) { extensionProto.clearOptions(); } } for (final EnumDescriptorProto.Builder enumProto : proto.getEnumTypeBuilderList()) { buildAllOptions(enumProto); } for (final ServiceDescriptorProto.Builder serviceProto : proto.getServiceBuilderList()) { buildAllOptions(serviceProto); } for (final DescriptorProto.Builder messageProto : proto.getMessageTypeBuilderList()) { buildAllOptions(messageProto); } }
private void buildAllOptions(final DescriptorProto.Builder proto) { if (!buildOptions(proto.getOptionsBuilder())) { proto.clearOptions(); } for (final FieldDescriptorProto.Builder fieldProto : proto.getFieldBuilderList()) { if (!buildOptions(fieldProto.getOptionsBuilder())) { fieldProto.clearOptions(); } } for (final FieldDescriptorProto.Builder extensionProto : proto.getExtensionBuilderList()) { if (!buildOptions(extensionProto.getOptionsBuilder())) { extensionProto.clearOptions(); } } for (final EnumDescriptorProto.Builder enumProto : proto.getEnumTypeBuilderList()) { buildAllOptions(enumProto); } for (final DescriptorProto.Builder messageProto : proto.getNestedTypeBuilderList()) { buildAllOptions(messageProto); } }
private FileDescriptorProto makeCanonicalProto(final FileDescriptor file) { final FileDescriptorProto.Builder protoBuilder = FileDescriptorProto.newBuilder(file.toProto()); for (final FieldDescriptorProto.Builder field : protoBuilder.getExtensionBuilderList()) { makeCanonicalField(field, file.findExtensionByName(field.getName())); } for (final DescriptorProto.Builder message : protoBuilder.getMessageTypeBuilderList()) { makeCanonicalMessage(message, file.findMessageTypeByName(message.getName())); } // for (EnumDescriptorProto.Builder enumProto : // protoBuilder.getEnumTypeBuilderList()) { // makeCanonicalEnum(enumProto, // file.findEnumTypeByName(enumProto.getName())); // } for (final ServiceDescriptorProto.Builder serviceProto : protoBuilder.getServiceBuilderList()) { makeCanonicalService(serviceProto, file.findServiceByName(serviceProto.getName())); } return OptionResolver.newBuilder().setCustomOptionsAsExtensions(reparseCustomOptions) .resolveAllOptionsFor(file, protoBuilder).build(); }
@SuppressWarnings("null") public static FileDescriptorProto.Builder makeProtoRefsRelative(final FileDescriptorProto proto, final FieldTypeRefsMode fieldTypeRefsMode) { if (fieldTypeRefsMode == FieldTypeRefsMode.AS_IS) { return FileDescriptorProto.newBuilder(proto); } final FileDescriptorProto.Builder protoBuilder = FileDescriptorProto.newBuilder(proto); final String packagePath = "." + proto.getPackage(); for (final FieldDescriptorProto.Builder field : protoBuilder.getExtensionBuilderList()) { makeFieldRefsRelative(packagePath, field, fieldTypeRefsMode, packagePath); } for (final DescriptorProto.Builder message : protoBuilder.getMessageTypeBuilderList()) { makeMessageRefsRelative(packagePath, message, fieldTypeRefsMode, packagePath); } return protoBuilder; }
@Test public void testTextFormatWithDescriptor() throws Exception { //TestUtil.getAllSet(); String allSet = TextFormat.printToString(TestUtil.getAllSet()); final DescriptorProto expectedAllSetProto = TestAllTypes.getDescriptor().toProto(); String allSetProto = TextFormat.printToString(expectedAllSetProto); log.debug("the message: {}", allSet); log.debug("the proto: {}", allSetProto); DynamicMessage.Builder builder = DynamicMessage.newBuilder(DescriptorProto.getDescriptor()); TextFormat.merge(allSetProto, builder); Message actualAllSetProto = builder.build(); assertThat(actualAllSetProto).isEqualTo(expectedAllSetProto); FieldDescriptor field = FileDescriptorProto.getDescriptor() .findFieldByNumber(FileDescriptorProto.MESSAGE_TYPE_FIELD_NUMBER); FileDescriptorProto fileProto = FileDescriptorProto.newBuilder().setName("my file1") .addRepeatedField(field, actualAllSetProto) .build(); FileDescriptor fileDescriptor = FileDescriptor.buildFrom(fileProto, new FileDescriptor[0]); Descriptor actualAllTypesDescriptor = fileDescriptor.findMessageTypeByName( TestAllTypes.getDescriptor().getFullName()); assertThat(actualAllTypesDescriptor, equalTo(TestAllTypes.getDescriptor())); }
private FileDescriptorProto.Builder addDeepMessageTypeToFile( FileDescriptorProto.Builder builder, Message descriptorProto) { //TODO delete this method!!! final FieldDescriptor field = FileDescriptorProto.getDescriptor() .findFieldByNumber(FileDescriptorProto.MESSAGE_TYPE_FIELD_NUMBER); final FieldDescriptor nestedTypeField = DescriptorProto.getDescriptor().findFieldByNumber( DescriptorProto.NESTED_TYPE_FIELD_NUMBER); builder.addRepeatedField(field, descriptorProto); for (Message nestedMessageType : (List<Message>) descriptorProto.getField(nestedTypeField)) { // builder.addRepeatedField(field, nestedMessageType); addDeepMessageTypeToFile(builder, nestedMessageType); } return builder; }
/** Used by the other overload, descends recursively into messages. */ private static boolean hasConflictingClassName(DescriptorProto messageDesc, String name) { if (name.equals(messageDesc.getName())) { return true; } for (EnumDescriptorProto enumDesc : messageDesc.getEnumTypeList()) { if (name.equals(enumDesc.getName())) { return true; } } for (DescriptorProto nestedMessageDesc : messageDesc.getNestedTypeList()) { if (hasConflictingClassName(nestedMessageDesc, name)) { return true; } } return false; }
/** Checks whether any generated classes conflict with the given name. */ private static boolean hasConflictingClassName(FileDescriptorProto file, String name) { for (EnumDescriptorProto enumDesc : file.getEnumTypeList()) { if (name.equals(enumDesc.getName())) { return true; } } for (ServiceDescriptorProto serviceDesc : file.getServiceList()) { if (name.equals(serviceDesc.getName())) { return true; } } for (DescriptorProto messageDesc : file.getMessageTypeList()) { if (hasConflictingClassName(messageDesc, name)) { return true; } } return false; }
public void testUnknownFieldsDenied() throws Exception { FileDescriptorProto fooProto = FileDescriptorProto.newBuilder() .setName("foo.proto") .addMessageType(DescriptorProto.newBuilder() .setName("Foo") .addField(FieldDescriptorProto.newBuilder() .setLabel(FieldDescriptorProto.Label.LABEL_OPTIONAL) .setTypeName("Bar") .setName("bar") .setNumber(1))) .build(); try { Descriptors.FileDescriptor.buildFrom(fooProto, new FileDescriptor[0]); fail("DescriptorValidationException expected"); } catch (DescriptorValidationException e) { assertTrue(e.getMessage().indexOf("Bar") != -1); assertTrue(e.getMessage().indexOf("is not defined") != -1); } }
public static TypeMap of(FileDescriptorProto protoFile) { ImmutableMap.Builder<String, JavaType> types = ImmutableMap.builder(); FileOptions options = protoFile.getOptions(); String protoPackage = "." + (protoFile.hasPackage() ? protoFile.getPackage() : ""); String javaPackage = options.hasJavaPackage() ? options.getJavaPackage() : protoFile.hasPackage() ? protoFile.getPackage() : null; String enclosingClass = options.getJavaMultipleFiles() ? null : options.hasJavaOuterClassname() ? options.getJavaOuterClassname() : createOuterJavaClassname(protoFile.getName()); for (DescriptorProto message : protoFile.getMessageTypeList()) { types.put(protoPackage + "." + message.getName(), new JavaType(javaPackage, enclosingClass, message.getName())); } return new TypeMap(types.build()); }
/** * 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); } }
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; }
private void doPrint(FileDescriptorProto fdp, String javaPackage, String outerClassName) { List<DescriptorProto> messageDescList = Lists.newArrayList(fdp.getMessageTypeList()); List<ServiceDescriptorProto> serviceDescList = Lists.newArrayList(fdp.getServiceList()); List<EnumDescriptorProto> enumDescList = Lists.newArrayList(fdp.getEnumTypeList()); messageDescList.stream().filter(temp -> temp.getEnumTypeList() != null) .forEach(temp -> enumDescList.addAll(temp.getEnumTypeList())); printEnum(enumDescList, javaPackage, outerClassName); printMessage(messageDescList, javaPackage, outerClassName); printService(serviceDescList, javaPackage); }
public CausalOrderProtobufSerializer(@NotNull final Serializer<T> objectSerializer) { this.objectSerializer = objectSerializer; try { final FileDescriptorProto timestampedMessageFile = FileDescriptorProto.newBuilder() .addMessageType( DescriptorProto.newBuilder() .setName(MESSAGE_NAME) .addField( FieldDescriptorProto.newBuilder() .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) .setName(IDS_FIELD_NAME) .setNumber(IDS_FIELD_NUMBER) .setType(FieldDescriptorProto.Type.TYPE_BYTES)) .addField( FieldDescriptorProto.newBuilder() .setLabel(FieldDescriptorProto.Label.LABEL_REPEATED) .setName(TIMESTAMPS_FIELD_NAME) .setNumber(TIMESTAMPS_FIELD_NUMBER) .setOptions(FieldOptions.newBuilder() .setPacked(true)) .setType(FieldDescriptorProto.Type.TYPE_UINT64)) .addField( FieldDescriptorProto.newBuilder() .setName(VALUE_FIELD_NAME) .setNumber(VALUE_FIELD_NUMBER) .setType(FieldDescriptorProto.Type.TYPE_BYTES))) .build(); this.messageDescriptor = FileDescriptor .buildFrom(timestampedMessageFile, new FileDescriptor[0]) .findMessageTypeByName(MESSAGE_NAME); this.ids = messageDescriptor.findFieldByName(IDS_FIELD_NAME); this.timestamps = messageDescriptor.findFieldByName(TIMESTAMPS_FIELD_NAME); this.value = messageDescriptor.findFieldByName(VALUE_FIELD_NAME); this.messageParser = DynamicMessage.newBuilder(messageDescriptor) .buildPartial() .getParserForType(); } catch (final DescriptorValidationException e) { throw new RuntimeException(e); } }
public SingleSourceFifoOrderProtobufSerializer(@NotNull final Serializer<T> objectSerializer) { this.objectSerializer = objectSerializer; try { final FileDescriptorProto timestampedMessageFile = FileDescriptorProto.newBuilder() .addMessageType( DescriptorProto.newBuilder() .setName(MESSAGE_NAME) .addField( FieldDescriptorProto.newBuilder() .setName(TIMESTAMP_FIELD_NAME) .setNumber(TIMESTAMP_FIELD_NUMBER) .setType(FieldDescriptorProto.Type.TYPE_INT64)) .addField( FieldDescriptorProto.newBuilder() .setName(VALUE_FIELD_NAME) .setNumber(VALUE_FIELD_NUMBER) .setType(FieldDescriptorProto.Type.TYPE_BYTES))) .build(); final Descriptor message = FileDescriptor .buildFrom(timestampedMessageFile, new FileDescriptor[0]) .findMessageTypeByName(MESSAGE_NAME); this.timestampedMessageField = message.findFieldByName(TIMESTAMP_FIELD_NAME); this.valueMessageField = message.findFieldByName(VALUE_FIELD_NAME); this.messageBuilder = DynamicMessage.newBuilder(message); this.messageParser = messageBuilder.buildPartial().getParserForType(); } catch (final DescriptorValidationException e) { throw new RuntimeException(e); } }
private void add(DescriptorProto message) { fullNameSegments.push(message.getName()); pathSegments.push(DescriptorProto.EXTENSION_FIELD_NUMBER); add(message.getExtensionList()); pathSegments.pop(); pathSegments.push(DescriptorProto.NESTED_TYPE_FIELD_NUMBER); for (int i = 0; i < message.getNestedTypeCount(); i++) { pathSegments.push(i); DescriptorProto nested = message.getNestedType(i); add(nested); pathSegments.pop(); } pathSegments.pop(); fullNameSegments.pop(); }
/** * Creates additional types (Value, Struct and ListValue) to be added to the Service config. * TODO (guptasu): Fix this hack. Find a better way to add the predefined types. * TODO (guptasu): Add them only when required and not in all cases. */ static Iterable<Type> createAdditionalServiceTypes() { Map<String, DescriptorProto> additionalMessages = Maps.newHashMap(); additionalMessages.put(Struct.getDescriptor().getFullName(), Struct.getDescriptor().toProto()); additionalMessages.put(Value.getDescriptor().getFullName(), Value.getDescriptor().toProto()); additionalMessages.put(ListValue.getDescriptor().getFullName(), ListValue.getDescriptor().toProto()); additionalMessages.put(Empty.getDescriptor().getFullName(), Empty.getDescriptor().toProto()); additionalMessages.put(Int32Value.getDescriptor().getFullName(), Int32Value.getDescriptor().toProto()); additionalMessages.put(DoubleValue.getDescriptor().getFullName(), DoubleValue.getDescriptor().toProto()); additionalMessages.put(BoolValue.getDescriptor().getFullName(), BoolValue.getDescriptor().toProto()); additionalMessages.put(StringValue.getDescriptor().getFullName(), StringValue.getDescriptor().toProto()); for (Descriptor descriptor : Struct.getDescriptor().getNestedTypes()) { additionalMessages.put(descriptor.getFullName(), descriptor.toProto()); } // TODO (guptasu): Remove this hard coding. Without this, creation of Model from Service throws. // Needs investigation. String fileName = "struct.proto"; List<Type> additionalTypes = Lists.newArrayList(); for (String typeName : additionalMessages.keySet()) { additionalTypes.add(TypesBuilderFromDescriptor.createType(typeName, additionalMessages.get(typeName), fileName)); } return additionalTypes; }
/** * 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(); }
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)); } }
@Accepts protected void accept(DescriptorProto.Builder message) { MessageNodeInfo messageInfo = (MessageNodeInfo) pushParent(BuilderVisitorNodeInfo.create(message, currentFile)); visitRepeated(DescriptorProto.FIELD_FIELD_NUMBER); visitRepeated(DescriptorProto.NESTED_TYPE_FIELD_NUMBER); visitRepeated(DescriptorProto.ENUM_TYPE_FIELD_NUMBER); visitRepeated(DescriptorProto.EXTENSION_FIELD_NUMBER); visit(message.getOptionsBuilder()); popExpectedParent(message); }
public void processAddedFields(DescriptorProto.Builder message, Iterable<FieldLocation> fields) { if (manageSourceCodeInfo) { ProtoPathWrapper messagePath = pathFromElement(message); if (messagePath == null) { throw new RuntimeException( String.format( "Internal error - couldn't find path for proto message %s", ProtoHelpers.getName(message))); } ProtoPathWrapper fieldsPath = ProtoHelpers.buildPath(messagePath, DescriptorProto.FIELD_FIELD_NUMBER); ProtoPathTree<SourceCodeInfo.Location> fieldsPathTree = pathToLocation.getSubtree(fieldsPath, true); for (FieldLocation field : fields) { Integer fieldIndex = fieldsPathTree.size(); if (fieldIndex > 0 && (fieldsPathTree.firstKey() != 0 || fieldsPathTree.lastKey() != (fieldIndex - 1))) { throw new RuntimeException( String.format( "BuilderVisitor internal error - non-contiguous field indexes found [%d..%d]\n", fieldsPathTree.firstKey(), fieldsPathTree.lastKey())); } fieldsPathTree.addDataElement( new ProtoPathWrapper(fieldIndex), // relative path of field within this message field.location()); elementToOriginalPath.put( field.fieldDescriptor(), ProtoHelpers.buildPath(fieldsPath, fieldIndex)); } } }
private void processAddedFields(FileNodeInfo currentFile) { if (!toBeAddedFields().isEmpty()) { DescriptorProto.Builder message = (DescriptorProto.Builder) node(); if (currentFile != null) { currentFile.processAddedFields(message, toBeAddedFields()); } for (FieldLocation fieldInfo : toBeAddedFields()) { message.addField(fieldInfo.fieldDescriptor()); } } }
/** Determines if the given field number is an extension. */ public boolean isExtensionNumber(final int number) { for (final DescriptorProto.ExtensionRange range : proto.getExtensionRangeList()) { if (range.getStart() <= number && number < range.getEnd()) { return true; } } return false; }
/** Determines if the given field number is reserved. */ public boolean isReservedNumber(final int number) { for (final DescriptorProto.ReservedRange range : proto.getReservedRangeList()) { if (range.getStart() <= number && number < range.getEnd()) { return true; } } return false; }
protected void decompileMessageBody(DescriptorProto messageDescriptor) throws IOException { indent++; if (messageDescriptor.hasOptions()) { decompileOptions(messageDescriptor.getOptions()); } decompileMembers(messageDescriptor.getEnumTypeList(), messageDescriptor.getNestedTypeList(), messageDescriptor.getFieldList(), messageDescriptor.getExtensionRangeList(), messageDescriptor.getExtensionList()); indent--; indentedFormat("}"); }