@SuppressWarnings("unchecked") private static Object buildMessage(Builder builder, Map<String, Object> fields) { Descriptor descriptor = builder.getDescriptorForType(); for (Map.Entry<String, Object> entry : fields.entrySet()) { if (entry.getValue() == null) { continue; } FieldDescriptor field = getField(descriptor, entry.getKey()); if (entry.getValue() instanceof List<?>) { List<Object> values = (List<Object>) entry.getValue(); for (Object value : values) { builder.addRepeatedField(field, buildValue(builder, field, value)); } } else { builder.setField(field, buildValue(builder, field, entry.getValue())); } } return builder.build(); }
Message createProtoBuf( Descriptor descriptor, Message.Builder builder, Map<String, Object> input) { if (input == null) { return builder.build(); } for (FieldDescriptor field : descriptor.getFields()) { String fieldName = field.getName(); if (!input.containsKey(fieldName)) { // TODO: validate required fields continue; } if (field.isRepeated()) { List<Object> values = (List<Object>) input.get(fieldName); for (Object value : values) { builder.addRepeatedField(field, getValueForField(field, value, builder)); } } else { builder.setField(field, getValueForField(field, input.get(fieldName), builder)); } } return builder.build(); }
GqlInputConverter build() { HashBiMap<String, Descriptor> mapping = HashBiMap.create(); HashBiMap<String, EnumDescriptor> enumMapping = HashBiMap.create(getEnumMap(enumDescriptors)); LinkedList<Descriptor> loop = new LinkedList<>(descriptors); Set<FileDescriptor> fileDescriptorSet = ProtoRegistry.extractDependencies(fileDescriptors); for (FileDescriptor fileDescriptor : fileDescriptorSet) { loop.addAll(fileDescriptor.getMessageTypes()); enumMapping.putAll(getEnumMap(fileDescriptor.getEnumTypes())); } while (!loop.isEmpty()) { Descriptor descriptor = loop.pop(); if (!mapping.containsKey(descriptor.getFullName())) { mapping.put(getReferenceName(descriptor), descriptor); loop.addAll(descriptor.getNestedTypes()); enumMapping.putAll(getEnumMap(descriptor.getEnumTypes())); } } return new GqlInputConverter( ImmutableBiMap.copyOf(mapping), ImmutableBiMap.copyOf(enumMapping)); }
/** 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; }
ProtoFieldInfo(FieldDescriptor field, Message containingPrototype) { this.field = checkNotNull(field, "field"); this.containingPrototype = checkNotNull(containingPrototype, "containingPrototype"); builderClass = containingPrototype.newBuilderForType().getClass(); camelCaseName = underscoresToUpperCamelCase(field.getName()); if (field.isMapField()) { Descriptor mapType = field.getMessageType(); mapKeyField = new ProtoFieldInfo(mapType.findFieldByName("key"), containingPrototype); mapValueField = new ProtoFieldInfo(mapType.findFieldByName("value"), containingPrototype); } else { mapKeyField = null; mapValueField = null; } }
private void mergeMapField(FieldDescriptor field, JsonElement json, Message.Builder builder) throws InvalidProtocolBufferException { if (!(json instanceof JsonObject)) { throw new InvalidProtocolBufferException("Expect a map object but found: " + json); } Descriptor type = field.getMessageType(); FieldDescriptor keyField = type.findFieldByName("key"); FieldDescriptor valueField = type.findFieldByName("value"); if (keyField == null || valueField == null) { throw new InvalidProtocolBufferException("Invalid map field: " + field.getFullName()); } JsonObject object = (JsonObject) json; for (Map.Entry<String, JsonElement> entry : object.entrySet()) { Message.Builder entryBuilder = builder.newBuilderForField(field); Object key = parseFieldValue(keyField, new JsonPrimitive(entry.getKey()), entryBuilder); Object value = parseFieldValue(valueField, entry.getValue(), entryBuilder); if (value == null) { throw new InvalidProtocolBufferException("Map value cannot be null."); } entryBuilder.setField(keyField, key); entryBuilder.setField(valueField, value); builder.addRepeatedField(field, entryBuilder.build()); } }
/** * Construct a {@code DynamicMessage} using the given {@code FieldSet}. */ private DynamicMessage(Descriptor type, FieldSet<FieldDescriptor> fields, UnknownFieldSet unknownFields) { this.type = type; this.fields = fields; this.unknownFields = unknownFields; }
private void mergeListValue(JsonElement json, Message.Builder builder) throws InvalidProtocolBufferException { Descriptor descriptor = builder.getDescriptorForType(); FieldDescriptor field = descriptor.findFieldByName("values"); if (field == null) { throw new InvalidProtocolBufferException("Invalid ListValue type."); } mergeRepeatedField(field, json, builder); }
/** Parse a message of the given type from the given input stream. */ public static DynamicMessage parseFrom( Descriptor type, CodedInputStream input, ExtensionRegistry extensionRegistry) throws IOException { return newBuilder(type).mergeFrom(input, extensionRegistry).buildParsed(); }
private void mergeWrapper(JsonElement json, Message.Builder builder) throws InvalidProtocolBufferException { Descriptor type = builder.getDescriptorForType(); FieldDescriptor field = type.findFieldByName("value"); if (field == null) { throw new InvalidProtocolBufferException("Invalid wrapper type: " + type.getFullName()); } builder.setField(field, parseFieldValue(field, json, builder)); }
private static boolean isInitialized(Descriptor type, FieldSet<FieldDescriptor> fields) { // Check that all required fields are present. for (final FieldDescriptor field : type.getFields()) { if (field.isRequired()) { if (!fields.hasField(field)) { return false; } } } // Check that embedded messages are initialized. return fields.isInitialized(); }
private void mergeStruct(JsonElement json, Message.Builder builder) throws InvalidProtocolBufferException { Descriptor descriptor = builder.getDescriptorForType(); FieldDescriptor field = descriptor.findFieldByName("fields"); if (field == null) { throw new InvalidProtocolBufferException("Invalid Struct type."); } mergeMapField(field, json, builder); }
private void addMessage(Descriptor message) { for (Descriptor nestedType : message.getNestedTypes()) { addMessage(nestedType); } if (types.containsKey(message.getFullName())) { logger.warning("Type " + message.getFullName() + " is added multiple times."); return; } types.put(message.getFullName(), message); }
public void testFieldDescriptorDefault() throws Exception { Descriptor d = TestAllTypes.getDescriptor(); assertFalse(d.findFieldByName("optional_int32").hasDefaultValue()); assertEquals(0, d.findFieldByName("optional_int32").getDefaultValue()); assertTrue(d.findFieldByName("default_int32").hasDefaultValue()); assertEquals(41, d.findFieldByName("default_int32").getDefaultValue()); d = TestExtremeDefaultValues.getDescriptor(); assertEquals( ByteString.copyFrom( "\0\001\007\b\f\n\r\t\013\\\'\"\u00fe".getBytes("ISO-8859-1")), d.findFieldByName("escaped_bytes").getDefaultValue()); assertEquals(-1, d.findFieldByName("large_uint32").getDefaultValue()); assertEquals(-1L, d.findFieldByName("large_uint64").getDefaultValue()); }
/** * Adds message types and all types defined in the same .proto file as * well as all transitively imported .proto files to this {@link Builder}. */ public Builder add(Iterable<Descriptor> messageTypes) { if (types == null) { throw new IllegalStateException("A TypeRegistry.Builer can only be used once."); } for (Descriptor type : messageTypes) { addFile(type.getFile()); } return this; }
/** Prints google.protobuf.ListValue */ private void printListValue(MessageOrBuilder message) throws IOException { Descriptor descriptor = message.getDescriptorForType(); FieldDescriptor field = descriptor.findFieldByName("values"); if (field == null) { throw new InvalidProtocolBufferException("Invalid ListValue type."); } printRepeatedFieldValue(field, message.getField(field)); }
private void addFile(FileDescriptor file) { // Skip the file if it's already added. if (!files.add(file.getFullName())) { return; } for (FileDescriptor dependency : file.getDependencies()) { addFile(dependency); } for (Descriptor message : file.getMessageTypes()) { addMessage(message); } }
/** Prints wrapper types (e.g., google.protobuf.Int32Value) */ private void printWrapper(MessageOrBuilder message) throws IOException { Descriptor descriptor = message.getDescriptorForType(); FieldDescriptor valueField = descriptor.findFieldByName("value"); if (valueField == null) { throw new InvalidProtocolBufferException("Invalid Wrapper type."); } // When formatting wrapper types, we just print its value field instead of // the whole message. printSingleFieldValue(valueField, message.getField(valueField)); }
private Map<String, FieldDescriptor> getFieldNameMap(Descriptor descriptor) { if (!fieldNameMaps.containsKey(descriptor)) { Map<String, FieldDescriptor> fieldNameMap = new HashMap<String, FieldDescriptor>(); for (FieldDescriptor field : descriptor.getFields()) { fieldNameMap.put(field.getName(), field); fieldNameMap.put(field.getJsonName(), field); } fieldNameMaps.put(descriptor, fieldNameMap); return fieldNameMap; } return fieldNameMaps.get(descriptor); }
/** * Returns the built {@link MessageMarshaller}, generating {@link TypeSpecificMarshaller} for * all registered {@link Message} types. Any {@link Message} types that have not been registered * will not be usable with the returned {@link MessageMarshaller}. */ public MessageMarshaller build() { Map<Descriptor, TypeSpecificMarshaller<?>> builtParsers = new HashMap<>(); addStandardParser(BoolValueMarshaller.INSTANCE, builtParsers); addStandardParser(Int32ValueMarshaller.INSTANCE, builtParsers); addStandardParser(UInt32ValueMarshaller.INSTANCE, builtParsers); addStandardParser(Int64ValueMarshaller.INSTANCE, builtParsers); addStandardParser(UInt64ValueMarshaller.INSTANCE, builtParsers); addStandardParser(StringValueMarshaller.INSTANCE, builtParsers); addStandardParser(BytesValueMarshaller.INSTANCE, builtParsers); addStandardParser(FloatValueMarshaller.INSTANCE, builtParsers); addStandardParser(DoubleValueMarshaller.INSTANCE, builtParsers); addStandardParser(TimestampMarshaller.INSTANCE, builtParsers); addStandardParser(DurationMarshaller.INSTANCE, builtParsers); addStandardParser(FieldMaskMarshaller.INSTANCE, builtParsers); addStandardParser(StructMarshaller.INSTANCE, builtParsers); addStandardParser(ValueMarshaller.INSTANCE, builtParsers); addStandardParser(ListValueMarshaller.INSTANCE, builtParsers); AnyMarshaller anyParser = new AnyMarshaller(); addStandardParser(anyParser, builtParsers); for (Message prototype : prototypes) { TypeSpecificMarshaller.buildAndAdd( prototype, includingDefaultValueFields, preservingProtoFieldNames, ignoringUnknownFields, builtParsers); } MarshallerRegistry registry = new MarshallerRegistry(builtParsers); anyParser.setMarshallerRegistry(registry); return new MessageMarshaller( omittingInsignificantWhitespace ? null : new MessagePrettyPrinter(), registry); }
MarshallerRegistry(Map<Descriptor, TypeSpecificMarshaller<?>> descriptorRegistry) { this.descriptorRegistry = ImmutableMap.copyOf(descriptorRegistry); ImmutableMap.Builder<String, TypeSpecificMarshaller<?>> typeNameRegistry = ImmutableMap.builder(); for (Map.Entry<Descriptor, TypeSpecificMarshaller<?>> entry : descriptorRegistry.entrySet()) { typeNameRegistry.put(entry.getKey().getFullName(), entry.getValue()); } this.typeNameRegistry = typeNameRegistry.build(); }
static <T extends Message> void buildAndAdd( T prototype, boolean includingDefaultValueFields, boolean preservingProtoFieldNames, boolean ignoringUnknownFields, Map<Descriptor, TypeSpecificMarshaller<?>> builtMarshallers) { if (builtMarshallers.containsKey(prototype.getDescriptorForType())) { return; } buildOrFindMarshaller( prototype, includingDefaultValueFields, preservingProtoFieldNames, ignoringUnknownFields, builtMarshallers); Map<String, TypeSpecificMarshaller<?>> builtMarshallersByFieldName = new HashMap<>(); for (Map.Entry<Descriptor, TypeSpecificMarshaller<?>> entry : builtMarshallers.entrySet()) { builtMarshallersByFieldName.put( CodeGenUtil.fieldNameForNestedMarshaller(entry.getKey()), entry.getValue()); } // Wire up nested serializers. for (TypeSpecificMarshaller<?> m : builtMarshallers.values()) { for (Field field : m.getClass().getDeclaredFields()) { if (field.getName().startsWith("MARSHALLER_")) { try { TypeSpecificMarshaller<?> nested = builtMarshallersByFieldName.get(field.getName()); checkNotNull( nested, "nested marshaller could not be found for field: %s", field.getName()); field.set(m, nested); } catch (IllegalAccessException e) { throw new IllegalStateException( "Could not set marshaller field, which we know is accessible.", e); } } } } }
/** * Adds a message type and all types defined in the same .proto file as * well as all transitively imported .proto files to this {@link Builder}. */ public Builder add(Descriptor messageType) { if (types == null) { throw new IllegalStateException("A TypeRegistry.Builer can only be used once."); } addFile(messageType.getFile()); return this; }
/** Prints google.protobuf.Struct */ private void printStruct(MessageOrBuilder message) throws IOException { Descriptor descriptor = message.getDescriptorForType(); FieldDescriptor field = descriptor.findFieldByName("fields"); if (field == null) { throw new InvalidProtocolBufferException("Invalid Struct type."); } // Struct is formatted as a map object. printMapFieldValue(field, message.getField(field)); }
@SuppressWarnings("rawtypes") private void printMapFieldValue(FieldDescriptor field, Object value) throws IOException { Descriptor type = field.getMessageType(); FieldDescriptor keyField = type.findFieldByName("key"); FieldDescriptor valueField = type.findFieldByName("value"); if (keyField == null || valueField == null) { throw new InvalidProtocolBufferException("Invalid map field."); } generator.print("{" + blankOrNewLine); generator.indent(); boolean printedElement = false; for (Object element : (List) value) { Message entry = (Message) element; Object entryKey = entry.getField(keyField); Object entryValue = entry.getField(valueField); if (printedElement) { generator.print("," + blankOrNewLine); } else { printedElement = true; } // Key fields are always double-quoted. printSingleFieldValue(keyField, entryKey, true); generator.print(":" + blankOrSpace); printSingleFieldValue(valueField, entryValue); } if (printedElement) { generator.print(blankOrNewLine); } generator.outdent(); generator.print("}"); }