com.google.protobuf.Descriptors.Descriptor Java Examples
The following examples show how to use
com.google.protobuf.Descriptors.Descriptor.
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 |
/** 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: GqlInputConverter.java From rejoiner with Apache License 2.0 | 6 votes |
private Object getValueForField(FieldDescriptor field, Object value, Message.Builder builder) { // TODO: handle groups, oneof if (field.getType() == FieldDescriptor.Type.MESSAGE) { Descriptor fieldTypeDescriptor = descriptorMapping.get(getReferenceName(field.getMessageType())); return createProtoBuf( fieldTypeDescriptor, builder.newBuilderForField(field), (Map<String, Object>) value); } if (field.getType() == FieldDescriptor.Type.ENUM) { EnumDescriptor enumDescriptor = enumMapping.get(ProtoToGql.getReferenceName(field.getEnumType())); return enumDescriptor.findValueByName(value.toString()); } if (field.getType() == FieldDescriptor.Type.FLOAT) { if (value instanceof Double) { return ((Double) value).floatValue(); } } return value; }
Example #3
Source File: GeneratedMessage.java From android-chromium with BSD 2-Clause "Simplified" License | 6 votes |
/** 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 #4
Source File: ExtensionRegistryWrapper.java From jackson-datatype-protobuf with Apache License 2.0 | 6 votes |
private ExtensionRegistryWrapper(final ExtensionRegistry extensionRegistry) { this.extensionFunction = new Function<Descriptor, Set<ExtensionInfo>>() { private final Map<Descriptor, Set<ExtensionInfo>> extensionCache = new ConcurrentHashMap<>(); @Override public Set<ExtensionInfo> apply(Descriptor descriptor) { Set<ExtensionInfo> cached = extensionCache.get(descriptor); if (cached != null) { return cached; } Set<ExtensionInfo> extensions = extensionRegistry.getAllImmutableExtensionsByExtendedType(descriptor.getFullName()); extensionCache.put(descriptor, extensions); return extensions; } }; }
Example #5
Source File: GeneratedMessage.java From 365browser with Apache License 2.0 | 6 votes |
/** 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 #6
Source File: RuleBasedConfigAspect.java From api-compiler with Apache License 2.0 | 6 votes |
protected RuleBasedConfigAspect( Model model, Key<AttributeType> key, String aspectName, Descriptor ruleDescriptor, List<RuleType> rules, boolean alwaysEvaluate) { super(model, aspectName); this.alwaysEvaluate = alwaysEvaluate; this.key = key; this.rules = new ConfigRuleSet<>( ruleDescriptor, rules, model.getExperiments(), model.getLocationResolver(), model.getDiagReporter()); this.rules.reportBadSelectors(getAspectName()); }
Example #7
Source File: JsonInclusionTest.java From jackson-datatype-protobuf with Apache License 2.0 | 6 votes |
@BeforeClass public static void setup() { allFields = new HashSet<>(); arrayFields = new HashSet<>(); Descriptor descriptor = AllFields.getDescriptor(); for (FieldDescriptor field : descriptor.getFields()) { allFields.add(translate(field.getName())); if (field.isRepeated()) { arrayFields.add(translate(field.getName())); } } allExtensionFields = new HashSet<>(); arrayExtensionFields = new HashSet<>(); ExtensionRegistryWrapper extensionRegistry = ExtensionRegistryWrapper.wrap(EXTENSION_REGISTRY); for (ExtensionInfo extensionInfo : extensionRegistry.getExtensionsByDescriptor(descriptor)) { allExtensionFields.add(translate(extensionInfo.descriptor.getName())); if (extensionInfo.descriptor.isRepeated()) { arrayExtensionFields.add(translate(extensionInfo.descriptor.getName())); } } }
Example #8
Source File: OneofTest.java From j2objc with Apache License 2.0 | 6 votes |
public void testReflection() throws Exception { Descriptor descriptor = OneofMsg.getDescriptor(); FieldDescriptor stringField = descriptor.findFieldByNumber(6); FieldDescriptor intField = descriptor.findFieldByNumber(4); FieldDescriptor messageField = descriptor.findFieldByNumber(1); OneofMsg msg = getFilledMessage(OneofGroupCase.ONEOF_STRING); assertEquals("goodbye", msg.getField(stringField)); assertFalse(msg.hasField(intField)); assertFalse(msg.hasField(messageField)); OneofMsg.Builder builder = msg.toBuilder(); builder.setField(messageField, OneofFoo.newBuilder().setFoo("baz").build()); assertEquals("baz", builder.getOneofMessage().getFoo()); assertFalse(builder.hasOneofString()); assertFalse(builder.hasOneofInt()); }
Example #9
Source File: CodeGenerator.java From jprotobuf with Apache License 2.0 | 6 votes |
/** * generate <code>getDescriptor</code> method code * * @return source code */ private Object getGetDescriptorMethodCode() { StringBuilder code = new StringBuilder(); String descriptorClsName = ClassHelper.getInternalName(Descriptor.class.getCanonicalName()); code.append("public ").append(descriptorClsName); code.append(" getDescriptor() throws IOException {").append(LINE_BREAK); code.append("if (this.descriptor != null) {").append(LINE_BREAK); code.append("return this.descriptor").append(JAVA_LINE_BREAK); code.append("}").append(LINE_BREAK); code.append(descriptorClsName).append(" descriptor = "); code.append("CodedConstant.getDescriptor(").append(ClassHelper.getInternalName(cls.getCanonicalName())) .append(JAVA_CLASS_FILE_SUFFIX).append(")").append(JAVA_LINE_BREAK); code.append("return (this.descriptor = descriptor)").append(JAVA_LINE_BREAK); code.append("}").append(LINE_BREAK); return code.toString(); }
Example #10
Source File: DynamicProtoUtil.java From rejoiner with Apache License 2.0 | 6 votes |
/** * Encodes the data portion of an ExecutionResult as ByteString. * * <p>The FileDescriptorSet must contain a message with the name "{operationName}Response". This * message will be populated with data from the execution result and encoded as a ByteString. */ public static ByteString encodeResponse( String operationName, FileDescriptorSet fileDescriptorSet, ExecutionResult executionResult) { try { // TODO: Support multiple FileDescriptors in FileDescriptorSet FileDescriptor fileDescriptor = FileDescriptor.buildFrom(fileDescriptorSet.getFileList().get(0), new FileDescriptor[] {}); Descriptor messageType = fileDescriptor.findMessageTypeByName(operationName + "Response"); Message message = DynamicMessage.parseFrom(messageType, ByteString.EMPTY); Message responseData = QueryResponseToProto.buildMessage(message, executionResult.getData()); return responseData.toByteString(); } catch (DescriptorValidationException | InvalidProtocolBufferException e) { e.printStackTrace(); throw new RuntimeException(e); } }
Example #11
Source File: ProtobufSerializer.java From jackson-datatype-protobuf with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") protected void writeMap( FieldDescriptor field, Object entries, JsonGenerator generator, SerializerProvider serializerProvider ) throws IOException { Descriptor entryDescriptor = field.getMessageType(); FieldDescriptor keyDescriptor = entryDescriptor.findFieldByName("key"); FieldDescriptor valueDescriptor = entryDescriptor.findFieldByName("value"); generator.writeStartObject(); for (Message entry : (List<? extends Message>) entries) { // map keys can only be integers or strings so this should be fine generator.writeFieldName(entry.getField(keyDescriptor).toString()); Object value = entry.getField(valueDescriptor); // map values can't be maps or repeated so this should be fine writeValue(valueDescriptor, value, generator, serializerProvider); } generator.writeEndObject(); }
Example #12
Source File: OpenApiDefinitionHandler.java From grpc-swagger with MIT License | 5 votes |
private List<Parameter> parseParameters(Descriptor inputType) { List<Parameter> parameters = new ArrayList<>(); Parameter parameter = new Parameter(); parameter.setName(inputType.getName()); ParameterSchema parameterSchema = new ParameterSchema(); parameterSchema.setRef(findRefByType(inputType)); parameter.setSchema(parameterSchema); parameters.add(parameter); return parameters; }
Example #13
Source File: MapEntry.java From jprotobuf with Apache License 2.0 | 5 votes |
/** * Instantiates a new metadata. * * @param descriptor the descriptor * @param defaultInstance the default instance * @param keyType the key type * @param valueType the value type */ public Metadata(Descriptor descriptor, MapEntry<K, V> defaultInstance, WireFormat.FieldType keyType, WireFormat.FieldType valueType) { super(keyType, defaultInstance.key, valueType, defaultInstance.value); this.descriptor = descriptor; this.parser = new AbstractParser<MapEntry<K, V>>() { @Override public MapEntry<K, V> parsePartialFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException { return new MapEntry<K, V>(Metadata.this, input, extensionRegistry); } }; }
Example #14
Source File: Pst.java From incubator-retired-wave with Apache License 2.0 | 5 votes |
/** * Runs the code generation for all templates. */ public void run() throws PstException { List<PstException.TemplateException> exceptions = Lists.newArrayList(); for (File template : templates) { try { MessageProperties properties = createProperties(template); String groupName = stripSuffix(".st", template.getName()); String templateName = properties.hasTemplateName() ? properties.getTemplateName() : ""; StringTemplateGroup group = new StringTemplateGroup(groupName + "Group", dir(template)); StringTemplate st = group.getInstanceOf(groupName); for (Descriptor messageDescriptor : fd.getMessageTypes()) { Message message = new Message(messageDescriptor, templateName, properties); st.reset(); st.setAttribute("m", message); write(st, new File( outputDir.getPath() + File.separator + message.getFullJavaType().replace('.', File.separatorChar) + "." + (properties.hasFileExtension() ? properties.getFileExtension() : "java"))); } } catch (Exception e) { exceptions.add(new PstException.TemplateException(template.getPath(), e)); } } if (!exceptions.isEmpty()) { throw new PstException(exceptions); } }
Example #15
Source File: OpenApiDefinitionHandler.java From grpc-swagger with MIT License | 5 votes |
private Operation parseOperation(Descriptors.MethodDescriptor methodDescriptor) { Operation operation = new Operation(); Descriptor inputType = methodDescriptor.getInputType(); Descriptor outputType = methodDescriptor.getOutputType(); operation.setDescription(methodDescriptor.getName()); List<Parameter> parameters = parseParameters(inputType); parameters.add(buildHeaderParameter()); Map<String, ResponseObject> response = parseResponse(outputType); operation.setParameters(parameters); operation.setResponses(response); return operation; }
Example #16
Source File: OpenApiDefinitionHandler.java From grpc-swagger with MIT License | 5 votes |
/** * 解析字段属性 * 字段分为 primitive integer(int32, int64), float, double, string, * object类型 array类型 * object类型指向 lookupTable里的字段, 并使用$ref表示引用 * array类型,type是array,具体item是字段类型 */ public void processMessageFields() { typeLookupTable.forEach((typeName, definitionType) -> { Descriptor protocolDescriptor = definitionType.getProtocolDescriptor(); Map<String, FieldProperty> properties = definitionType.getProperties(); List<Descriptors.FieldDescriptor> fields = protocolDescriptor.getFields(); fields.forEach(fieldDescriptor -> { FieldProperty fieldProperty = parseFieldProperty(fieldDescriptor); properties.put(fieldDescriptor.getName(), fieldProperty); }); }); }
Example #17
Source File: OpenApiDefinitionHandler.java From grpc-swagger with MIT License | 5 votes |
@Nullable private String findRefByType(Descriptor typeDescriptor) { String fullName = typeDescriptor.getFullName(); DefinitionType definitionType = typeLookupTable.get(fullName); if (definitionType != null) { return DEFINITION_REF_PREFIX + fullName; } return null; }
Example #18
Source File: DynamicMessage.java From play-store-api with GNU General Public License v3.0 | 5 votes |
/** 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(); }
Example #19
Source File: Pst.java From swellrt with Apache License 2.0 | 5 votes |
/** * Runs the code generation for all templates. */ public void run() throws PstException { List<PstException.TemplateException> exceptions = Lists.newArrayList(); for (File template : templates) { try { MessageProperties properties = createProperties(template); String groupName = stripSuffix(".st", template.getName()); String templateName = properties.hasTemplateName() ? properties.getTemplateName() : ""; StringTemplateGroup group = new StringTemplateGroup(groupName + "Group", dir(template)); StringTemplate st = group.getInstanceOf(groupName); for (Descriptor messageDescriptor : fd.getMessageTypes()) { Message message = new Message(messageDescriptor, templateName, properties); st.reset(); st.setAttribute("m", message); write(st, new File( outputDir.getPath() + File.separator + message.getFullJavaType().replace('.', File.separatorChar) + "." + (properties.hasFileExtension() ? properties.getFileExtension() : "java"))); } } catch (Exception e) { exceptions.add(new PstException.TemplateException(template.getPath(), e)); } } if (!exceptions.isEmpty()) { throw new PstException(exceptions); } }
Example #20
Source File: OpenApiDefinitionHandler.java From grpc-swagger with MIT License | 5 votes |
private DefinitionType buildDefinitionType(Descriptor descriptor) { DefinitionType definitionType = new DefinitionType(); definitionType.setTitle(descriptor.getName()); definitionType.setType(FieldTypeEnum.OBJECT.getType()); definitionType.setProperties(new HashMap<>()); definitionType.setProtocolDescriptor(descriptor); return definitionType; }
Example #21
Source File: OpenApiDefinitionHandler.java From grpc-swagger with MIT License | 5 votes |
private void parseNestModelType(List<Descriptor> descriptors) { if (CollectionUtils.isEmpty(descriptors)) { return; } descriptors.forEach(d -> { boolean isMap = ofNullable(d.getOptions()).map(MessageOptions::getMapEntry).orElse(false); if (isMap) { return; } typeLookupTable.put(d.getFullName(), buildDefinitionType(d)); }); }
Example #22
Source File: FieldScopeLogic.java From curiostack with MIT License | 5 votes |
@Override public final void validate( Descriptor rootDescriptor, FieldDescriptorValidator fieldDescriptorValidator) { for (FieldScopeLogic elem : elements) { elem.validate(rootDescriptor, fieldDescriptorValidator); } }
Example #23
Source File: GrpcDocServicePlugin.java From armeria with Apache License 2.0 | 5 votes |
@VisibleForTesting StructInfo newStructInfo(Descriptor descriptor) { return new StructInfo( descriptor.getFullName(), descriptor.getFields().stream() .map(GrpcDocServicePlugin::newFieldInfo) .collect(toImmutableList())); }
Example #24
Source File: DynamicSchemaTest.java From protobuf-dynamic with Apache License 2.0 | 5 votes |
/** * testBasic - basic usage */ @Test public void testBasic() throws Exception { log("--- testBasic ---"); // Create dynamic schema DynamicSchema.Builder schemaBuilder = DynamicSchema.newBuilder(); schemaBuilder.setName("PersonSchemaDynamic.proto"); MessageDefinition msgDef = MessageDefinition.newBuilder("Person") // message Person .addField("required", "int32", "id", 1) // required int32 id = 1 .addField("required", "string", "name", 2) // required string name = 2 .addField("optional", "string", "email", 3) // optional string email = 3 .build(); schemaBuilder.addMessageDefinition(msgDef); DynamicSchema schema = schemaBuilder.build(); log(schema); // Create dynamic message from schema DynamicMessage.Builder msgBuilder = schema.newMessageBuilder("Person"); Descriptor msgDesc = msgBuilder.getDescriptorForType(); DynamicMessage msg = msgBuilder .setField(msgDesc.findFieldByName("id"), 1) .setField(msgDesc.findFieldByName("name"), "Alan Turing") .setField(msgDesc.findFieldByName("email"), "[email protected]") .build(); log(msg); // Create data object traditional way using generated code PersonSchema.Person person = PersonSchema.Person.newBuilder() .setId(1) .setName("Alan Turing") .setEmail("[email protected]") .build(); // Should be equivalent Assert.assertEquals(person.toString(), msg.toString()); }
Example #25
Source File: ProtobufUtil.java From beam with Apache License 2.0 | 5 votes |
private static void recursivelyAddDescriptors( FieldDescriptor field, Set<Descriptor> descriptors, ExtensionRegistry registry) { switch (field.getType()) { case BOOL: case BYTES: case DOUBLE: case ENUM: case FIXED32: case FIXED64: case FLOAT: case INT32: case INT64: case SFIXED32: case SFIXED64: case SINT32: case SINT64: case STRING: case UINT32: case UINT64: // Primitive types do not transitively access anything else. break; case GROUP: case MESSAGE: // Recursively adds all the fields from this nested Message. recursivelyAddDescriptors(field.getMessageType(), descriptors, registry); break; default: throw new UnsupportedOperationException( "Unexpected Protocol Buffers field type: " + field.getType()); } }
Example #26
Source File: Message.java From swellrt with Apache License 2.0 | 5 votes |
/** * @return the nested messages of the message */ public List<Message> getNestedMessages() { if (messages == null) { ImmutableList.Builder<Message> builder = ImmutableList.builder(); for (Descriptor d : descriptor.getNestedTypes()) { builder.add(adapt(d)); } messages = builder.build(); } return messages; }
Example #27
Source File: GeneratedMessage.java From android-chromium with BSD 2-Clause "Simplified" License | 5 votes |
/** * Construct a FieldAccessorTable for a particular message class without * initializing FieldAccessors. */ public FieldAccessorTable( final Descriptor descriptor, final String[] camelCaseNames) { this.descriptor = descriptor; this.camelCaseNames = camelCaseNames; fields = new FieldAccessor[descriptor.getFields().size()]; initialized = false; }
Example #28
Source File: Message.java From incubator-retired-wave with Apache License 2.0 | 5 votes |
/** * @return the nested messages of the message */ public List<Message> getNestedMessages() { if (messages == null) { ImmutableList.Builder<Message> builder = ImmutableList.builder(); for (Descriptor d : descriptor.getNestedTypes()) { builder.add(adapt(d)); } messages = builder.build(); } return messages; }
Example #29
Source File: DynamicProtoUtil.java From rejoiner with Apache License 2.0 | 5 votes |
/** * Returns a Map containing data from a ByteString that is parsed using the Proto Descriptor. * * <p>The FileDescriptorSet must contain a message with the name "{operationName}Request". This * message will be used to parse the ByteString, and the resulting message will be transformed and * returned as a Map. */ public static Map<String, Object> decodeVariables( String operationName, FileDescriptorSet fileDescriptorSet, ByteString encodedRequest) { try { // TODO: Support multiple FileDescriptors in FileDescriptorSet FileDescriptor fileDescriptor = FileDescriptor.buildFrom(fileDescriptorSet.getFileList().get(0), new FileDescriptor[] {}); Descriptor messageType = fileDescriptor.findMessageTypeByName(operationName + "Request"); Message message = DynamicMessage.parseFrom(messageType, encodedRequest); return ProtoToMap.messageToMap(message); } catch (DescriptorValidationException | InvalidProtocolBufferException e) { e.printStackTrace(); throw new RuntimeException(e); } }
Example #30
Source File: OpenApiDefinitionHandler.java From grpc-swagger with MIT License | 5 votes |
private DefinitionType buildDefinitionType(Descriptor descriptor) { DefinitionType definitionType = new DefinitionType(); definitionType.setTitle(descriptor.getName()); definitionType.setType(FieldTypeEnum.OBJECT.getType()); definitionType.setProperties(new HashMap<>()); definitionType.setProtocolDescriptor(descriptor); return definitionType; }