Java Code Examples for com.google.protobuf.Descriptors.Descriptor#findFieldByNumber()
The following examples show how to use
com.google.protobuf.Descriptors.Descriptor#findFieldByNumber() .
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: 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 2
Source File: CompatibilityTest.java From j2objc with Apache License 2.0 | 6 votes |
public void testGetAllFields() throws Exception { AbstractMessage data = TypicalData.newBuilder() .setMyInt(1) .addRepeatedInt32(2) .setExtension(Typical.myExtension, TypicalDataMessage.getDefaultInstance()) .setExtension(Typical.myPrimitiveExtension, 3) .build(); Map<FieldDescriptor, Object> allFields = data.getAllFields(); assertEquals(4, allFields.size()); assertNotNull(allFields.get(Typical.myExtension.getDescriptor())); assertEquals(4, data.toBuilder().getAllFields().size()); Descriptor descriptor = TypicalData.Builder.getDescriptor(); FieldDescriptor intField = descriptor.findFieldByNumber(1); assertEquals(1, allFields.get(intField)); assertEquals(3, allFields.get(Typical.myPrimitiveExtension.getDescriptor())); }
Example 3
Source File: CompatibilityTest.java From j2objc with Apache License 2.0 | 6 votes |
public void testFindFieldByNumber() throws Exception { Descriptor descriptor = TypicalData.Builder.getDescriptor(); Collection<FieldDescriptor> fields = descriptor.getFields(); for (FieldDescriptor field : fields) { FieldDescriptor.Type type = field.getType(); int fieldId = field.getNumber(); switch (fieldId) { case 1: assertEquals(Type.INT32, type); break; case 2: assertEquals(Type.BYTES, type); break; case 3: assertEquals(Type.ENUM, type); break; } FieldDescriptor result = descriptor.findFieldByNumber(fieldId); assertEquals(field.getNumber(), result.getNumber()); assertEquals(field.getName(), result.getName()); } }
Example 4
Source File: CompatibilityTest.java From j2objc with Apache License 2.0 | 6 votes |
public void testNewBuilderForField() throws Exception { Descriptor descriptor = TypicalData.Builder.getDescriptor(); FieldDescriptor fieldDescriptor = descriptor.findFieldByNumber(11); TypicalData.Builder dataBuilder = TypicalData.newBuilder(); TypicalDataMessage.Builder messageBuilder = (TypicalDataMessage.Builder) dataBuilder.newBuilderForField(fieldDescriptor); TypicalDataMessage message = messageBuilder.setMyMessageInt(10).build(); assertEquals(10, message.getMyMessageInt()); fieldDescriptor = descriptor.findFieldByNumber(1); try { dataBuilder.newBuilderForField(fieldDescriptor); fail("Expected UnsupportedOperationException"); } catch (UnsupportedOperationException e) { // Expected. } }
Example 5
Source File: CompatibilityTest.java From j2objc with Apache License 2.0 | 6 votes |
public void testClearFieldWithDescriptor() throws Exception { Descriptor descriptor = TypicalData.Builder.getDescriptor(); FieldDescriptor intField = descriptor.findFieldByNumber(1); FieldDescriptor repeatedIntField = descriptor.findFieldByNumber(4); TypicalData.Builder dataBuilder = TypicalData.newBuilder() .setMyInt(42) .addRepeatedInt32(43) .addRepeatedInt32(44); assertEquals(42, dataBuilder.getMyInt()); dataBuilder.clearField(intField); assertFalse(dataBuilder.hasMyInt()); assertEquals(2, dataBuilder.getRepeatedInt32Count()); dataBuilder.clearField(repeatedIntField); assertEquals(0, dataBuilder.getRepeatedInt32Count()); }
Example 6
Source File: MapsTest.java From j2objc with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public void testMixingMapAndListApi() throws Exception { Descriptor descriptor = MapMsg.Builder.getDescriptor(); FieldDescriptor field = descriptor.findFieldByNumber(1); MapMsg.Builder builder = getFilledMessage().toBuilder(); MapEntry<String, String> entry = (MapEntry<String, String>) builder.getRepeatedField(field, 0); entry = entry.toBuilder().setKey("cat").setValue("purr").build(); builder.setRepeatedField(field, 0, entry); assertEquals(2, builder.getRepeatedFieldCount(field)); assertEquals(1, builder.getStringStringCount()); assertEquals("meow", builder.getStringStringOrThrow("cat")); }
Example 7
Source File: FieldScopeLogic.java From curiostack with MIT License | 5 votes |
@Override public void validate( Descriptor rootDescriptor, FieldDescriptorValidator fieldDescriptorValidator) { super.validate(rootDescriptor, fieldDescriptorValidator); for (int fieldNumber : fieldNumbers) { FieldDescriptor fieldDescriptor = rootDescriptor.findFieldByNumber(fieldNumber); checkArgument( fieldDescriptor != null, "Message type %s has no field with number %s.", rootDescriptor.getFullName(), fieldNumber); fieldDescriptorValidator.validate(fieldDescriptor); } }
Example 8
Source File: ConfigRuleSet.java From api-compiler with Apache License 2.0 | 5 votes |
public ConfigRuleSet( Descriptor ruleDescriptor, List<RuleType> rules, Experiments experiments, ConfigLocationResolver configLocationResolver, DiagReporter diagReporter) { Preconditions.checkNotNull(ruleDescriptor, "ruleDescriptor"); this.experiments = Preconditions.checkNotNull(experiments, "experiments"); this.diagReporter = Preconditions.checkNotNull(diagReporter, "diagReporter"); this.configLocationResolver = Preconditions.checkNotNull(configLocationResolver, "configLocationResolver"); this.selectorFieldDesc = ruleDescriptor.findFieldByNumber(SELECTOR_FIELD_NUM); // Sanity check for selector field. Preconditions.checkArgument( selectorFieldDesc != null && selectorFieldDesc.getName().equals(SELECTOR_FIELD_NAME) && selectorFieldDesc.getType() == FieldDescriptor.Type.STRING && !selectorFieldDesc.isRepeated(), "Config rule selector field not present or has unexpected name, type, or cardinality."); this.rules = minimize(buildRules(rules)); for (RuleWrapper<RuleType> ruleWrapper : this.rules) { unmatchedRules.put(ruleWrapper, Sets.newHashSet(ruleWrapper.selectors)); } }
Example 9
Source File: CompatibilityTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testGetMessageType() throws Exception { Descriptor descriptor = TypicalData.Builder.getDescriptor(); FieldDescriptor fieldDescriptor = descriptor.findFieldByNumber(11); Descriptor messageDescriptor = fieldDescriptor.getMessageType(); assertNotNull(messageDescriptor); FieldDescriptor messageFieldDescriptor = messageDescriptor.findFieldByNumber(1); assertEquals(1, messageFieldDescriptor.getNumber()); }
Example 10
Source File: CompatibilityTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testGetJavaType() throws Exception { Descriptor descriptor = TypicalData.Builder.getDescriptor(); FieldDescriptor intField = descriptor.findFieldByNumber(1); assertEquals(FieldDescriptor.JavaType.INT, intField.getJavaType()); FieldDescriptor bytesField = descriptor.findFieldByNumber(2); assertEquals(FieldDescriptor.JavaType.BYTE_STRING, bytesField.getJavaType()); FieldDescriptor booleanField = descriptor.findFieldByNumber(5); assertEquals(FieldDescriptor.JavaType.BOOLEAN, booleanField.getJavaType()); FieldDescriptor stringField = descriptor.findFieldByNumber(8); assertEquals(FieldDescriptor.JavaType.STRING, stringField.getJavaType()); }
Example 11
Source File: CompatibilityTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testEnumDescriptor() throws Exception { Descriptor descriptor = TypicalData.Builder.getDescriptor(); FieldDescriptor fieldDescriptor = descriptor.findFieldByNumber(3); assertEquals(Type.ENUM, fieldDescriptor.getType()); EnumDescriptor enumDescriptor = fieldDescriptor.getEnumType(); assertNotNull(enumDescriptor); EnumValueDescriptor enumValueDescriptor = enumDescriptor.findValueByNumber(1); assertEquals(1, enumValueDescriptor.getNumber()); assertEquals("VALUE1", enumValueDescriptor.getName()); }
Example 12
Source File: CompatibilityTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testExtensionRegistry() throws Exception { ExtensionRegistry registry = ExtensionRegistry.newInstance(); Typical.registerAllExtensions(registry); Descriptor descriptor = TypicalData.Builder.getDescriptor(); FieldDescriptor fieldDescriptor = descriptor.findFieldByNumber(1); assertFalse(fieldDescriptor.isExtension()); ExtensionRegistry.ExtensionInfo extensionInfo = registry.findExtensionByNumber(descriptor, 1000); assertNotNull(extensionInfo); FieldDescriptor extensionFieldDescriptor = extensionInfo.descriptor; assertNotNull(extensionFieldDescriptor); assertEquals(1000, extensionFieldDescriptor.getNumber()); assertTrue(extensionFieldDescriptor.isExtension()); Message message = extensionInfo.defaultInstance; assertTrue(message instanceof TypicalDataMessage); TypicalDataMessage data = ((TypicalDataMessage.Builder) message.toBuilder()) .setMyMessageInt(100) .build(); assertEquals(100, data.getMyMessageInt()); // Primitive extension extensionInfo = registry.findExtensionByNumber(descriptor, 1001); assertNotNull(extensionInfo); extensionFieldDescriptor = extensionInfo.descriptor; assertNotNull(extensionFieldDescriptor); assertEquals(1001, extensionFieldDescriptor.getNumber()); assertTrue(extensionFieldDescriptor.isExtension()); assertNull(extensionInfo.defaultInstance); }
Example 13
Source File: CompatibilityTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testSetAndGetFieldWithFieldDescriptor() throws Exception { FieldDescriptor[] fields = new FieldDescriptor[19]; Descriptor descriptor = TypicalData.Builder.getDescriptor(); for (int i = 1; i <= 18; i++) { fields[i] = descriptor.findFieldByNumber(i); } TypicalData.Builder dataBuilder = TypicalData.newBuilder(); dataBuilder.setField(fields[1], new Integer(42)); dataBuilder.setField(fields[2], ByteString.copyFrom("foo".getBytes())); dataBuilder.setField(fields[3], TypicalData.EnumType.VALUE9.getValueDescriptor()); dataBuilder.setField(fields[11], TypicalDataMessage.newBuilder().build()); dataBuilder.setField(fields[12], Boolean.TRUE); dataBuilder.setField(fields[13], new Float(43.8)); dataBuilder.setField(fields[14], new Double(44.5)); dataBuilder.setField(fields[15], "bar"); dataBuilder.setField(fields[16], new Integer(24)); dataBuilder.setField(fields[17], new Long(4422)); dataBuilder.setField(fields[18], new Long(2244)); dataBuilder.addRepeatedField(fields[4], new Integer(72)); dataBuilder.addRepeatedField(fields[8], "aaa"); dataBuilder.addRepeatedField(fields[8], "bbb"); dataBuilder.setRepeatedField(fields[8], 1, "ccc"); ArrayList<Double> doubles = new ArrayList<Double>(); doubles.add(1.2); doubles.add(3.4); dataBuilder.setField(fields[7], doubles); checkGetters(dataBuilder.build(), fields); checkGetters(dataBuilder, fields); }
Example 14
Source File: MapsTest.java From j2objc with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") public void testMapFieldDescriptor() throws Exception { Descriptor descriptor = MapMsg.Builder.getDescriptor(); FieldDescriptor stringStringField = descriptor.findFieldByNumber(1); FieldDescriptor boolEnumField = descriptor.findFieldByNumber(7); assertEquals(Type.MESSAGE, stringStringField.getType()); assertTrue(stringStringField.isRepeated()); Descriptor entryDescriptor = stringStringField.getMessageType(); assertNotNull(entryDescriptor); assertEquals(2, entryDescriptor.getFields().size()); FieldDescriptor keyFieldDescriptor = entryDescriptor.findFieldByNumber(1); FieldDescriptor valueFieldDescriptor = entryDescriptor.findFieldByNumber(2); assertEquals("key", keyFieldDescriptor.getName()); assertEquals(Type.STRING, keyFieldDescriptor.getType()); assertEquals("value", valueFieldDescriptor.getName()); assertEquals(Type.STRING, valueFieldDescriptor.getType()); MapMsg msg = getFilledMessage(); Object rawValue = msg.getField(stringStringField); assertTrue(rawValue instanceof List); List<?> list = (List<?>) rawValue; assertEquals(2, list.size()); Object rawEntry = list.get(0); assertTrue(rawEntry instanceof MapEntry); MapEntry<?, ?> entry = (MapEntry<?, ?>) rawEntry; assertEquals("duck", entry.getKey()); assertEquals("quack", entry.getValue()); rawEntry = msg.getRepeatedField(stringStringField, 1); assertTrue(rawEntry instanceof MapEntry); entry = (MapEntry<?, ?>) rawEntry; assertEquals("cat", entry.getKey()); assertEquals("meow", entry.getValue()); list = (List<?>) msg.getField(boolEnumField); entry = (MapEntry<?, ?>) list.get(0); assertTrue(entry.getKey() instanceof Boolean); assertTrue(entry.getValue() instanceof Integer); assertEquals(Boolean.TRUE, entry.getKey()); assertEquals(Integer.valueOf(0), entry.getValue()); entry = (MapEntry<?, ?>) msg.getRepeatedField(boolEnumField, 1); assertTrue(entry.getKey() instanceof Boolean); assertTrue(entry.getValue() instanceof Integer); assertEquals(Boolean.FALSE, entry.getKey()); assertEquals(Integer.valueOf(2), entry.getValue()); MapMsg.Builder builder = msg.toBuilder(); MapEntry<String, String> stringStringEntry = ((List<MapEntry<String, String>>) msg.getField(stringStringField)).get(0); stringStringEntry = stringStringEntry.toBuilder().setValue("neigh").build(); builder.setRepeatedField(stringStringField, 0, stringStringEntry); stringStringEntry = stringStringEntry.toBuilder().setKey("cow").setValue("moo").build(); builder.addRepeatedField(stringStringField, stringStringEntry); assertEquals(3, builder.getStringStringCount()); assertEquals(3, builder.getRepeatedFieldCount(stringStringField)); assertEquals("moo", builder.getStringStringOrThrow("cow")); builder.clearField(stringStringField); assertEquals("default", builder.getStringStringOrDefault("cow", "default")); assertEquals(0, builder.getStringStringCount()); List<MapEntry<String, String>> newStringStringList = new ArrayList<>(); newStringStringList.add( stringStringEntry.toBuilder().setKey("parrot").setValue("squawk").build()); newStringStringList.add(stringStringEntry.toBuilder().setKey("pig").setValue("oink").build()); builder.setField(stringStringField, newStringStringList); assertEquals("squawk", builder.getStringStringOrThrow("parrot")); assertEquals("oink", builder.getStringStringOrThrow("pig")); }
Example 15
Source File: MetaDataEvolutionValidator.java From fdb-record-layer with Apache License 2.0 | 4 votes |
/** * Validate that the record types have all been evolved in a legal way. In particular, this makes sure that * each record type defined in the union descriptor is in the new union descriptor in the correct * place. It will then verify that each message type has been updated in a legal way, i.e., that it only * includes new fields. * * @param oldUnionDescriptor the union descriptor for the existing meta-data for some record store * @param newUnionDescriptor the new proposed meta-data */ @SuppressWarnings("PMD.CompareObjectsWithEquals") public void validateUnion(@Nonnull Descriptor oldUnionDescriptor, @Nonnull Descriptor newUnionDescriptor) { if (oldUnionDescriptor == newUnionDescriptor) { // Don't bother validating the record types if they are all the same. return; } final BiMap<Descriptor, Descriptor> updatedDescriptors = HashBiMap.create(oldUnionDescriptor.getFields().size()); final Set<Pair<Descriptor, Descriptor>> seenDescriptors = new HashSet<>(); for (FieldDescriptor oldUnionField : oldUnionDescriptor.getFields()) { if (!oldUnionField.getType().equals(FieldDescriptor.Type.MESSAGE)) { throw new MetaDataException("field in union is not a message type", LogMessageKeys.FIELD_NAME, oldUnionField.getName()); } int fieldNumber = oldUnionField.getNumber(); FieldDescriptor newUnionField = newUnionDescriptor.findFieldByNumber(fieldNumber); if (newUnionField != null) { if (!newUnionField.getType().equals(FieldDescriptor.Type.MESSAGE)) { throw new MetaDataException("field in new union is not a message type", LogMessageKeys.FIELD_NAME, newUnionField.getName()); } Descriptor oldRecord = oldUnionField.getMessageType(); Descriptor newRecord = newUnionField.getMessageType(); // Verify that all fields of the same type in the old union are also of the same type // in the new union (i.e., that there are no "splits" or "merges" of record types). Descriptor alreadySeenNewRecord = updatedDescriptors.get(oldRecord); if (alreadySeenNewRecord != null) { if (alreadySeenNewRecord != newRecord) { // A "split" -- the same type in the old union points to two different types in the new union throw new MetaDataException("record type corresponds to multiple types in new meta-data", LogMessageKeys.OLD_RECORD_TYPE, oldRecord.getName(), LogMessageKeys.NEW_RECORD_TYPE, newRecord.getName() + " & " + alreadySeenNewRecord.getName()); } } else { if (updatedDescriptors.containsValue(newRecord)) { // A "merge" -- two different types in the old union point to the same type in the new union final Descriptor alreadySeenOldRecord = updatedDescriptors.inverse().get(newRecord); throw new MetaDataException("record type corresponds to multiple types in old meta-data", LogMessageKeys.OLD_RECORD_TYPE, oldRecord.getName() + " & " + alreadySeenOldRecord.getName(), LogMessageKeys.NEW_RECORD_TYPE, newRecord.getName()); } } updatedDescriptors.put(oldRecord, newRecord); // Validate the form of the old and new record types validateMessage(oldRecord, newRecord, seenDescriptors); } else { throw new MetaDataException("record type removed from union", LogMessageKeys.RECORD_TYPE, oldUnionField.getMessageType()); } } }
Example 16
Source File: CompatibilityTest.java From j2objc with Apache License 2.0 | 4 votes |
public void testEmptyFieldOptions() { Descriptor descriptor = TypicalData.Builder.getDescriptor(); FieldDescriptor intField = descriptor.findFieldByNumber(1); assertNotNull(intField.getOptions()); }
Example 17
Source File: ProtobufJsonFormat.java From tajo with Apache License 2.0 | 4 votes |
/** * Parse a single field from {@code tokenizer} and merge it into {@code builder}. If a ',' is * detected after the field ends, the next field will be parsed automatically */ protected void mergeField(Tokenizer tokenizer, ExtensionRegistry extensionRegistry, Message.Builder builder) throws ParseException { FieldDescriptor field; Descriptor type = builder.getDescriptorForType(); ExtensionRegistry.ExtensionInfo extension = null; boolean unknown = false; String name = tokenizer.consumeIdentifier(); field = type.findFieldByName(name); // Group names are expected to be capitalized as they appear in the // .proto file, which actually matches their type names, not their field // names. if (field == null) { // Explicitly specify US locale so that this code does not break when // executing in Turkey. String lowerName = name.toLowerCase(Locale.US); field = type.findFieldByName(lowerName); // If the case-insensitive match worked but the field is NOT a group, if ((field != null) && (field.getType() != FieldDescriptor.Type.GROUP)) { field = null; } } // Again, special-case group names as described above. if ((field != null) && (field.getType() == FieldDescriptor.Type.GROUP) && !field.getMessageType().getName().equals(name)) { field = null; } // Last try to lookup by field-index if 'name' is numeric, // which indicates a possible unknown field if (field == null && TextUtils.isDigits(name)) { field = type.findFieldByNumber(Integer.parseInt(name)); unknown = true; } // Finally, look for extensions extension = extensionRegistry.findExtensionByName(name); if (extension != null) { if (extension.descriptor.getContainingType() != type) { throw tokenizer.parseExceptionPreviousToken("Extension \"" + name + "\" does not extend message type \"" + type.getFullName() + "\"."); } field = extension.descriptor; } // Disabled throwing exception if field not found, since it could be a different version. if (field == null) { handleMissingField(tokenizer, extensionRegistry, builder); //throw tokenizer.parseExceptionPreviousToken("Message type \"" + type.getFullName() // + "\" has no field named \"" + name // + "\"."); } if (field != null) { tokenizer.consume(":"); boolean array = tokenizer.tryConsume("["); if (array) { while (!tokenizer.tryConsume("]")) { handleValue(tokenizer, extensionRegistry, builder, field, extension, unknown); tokenizer.tryConsume(","); } } else { handleValue(tokenizer, extensionRegistry, builder, field, extension, unknown); } } if (tokenizer.tryConsume(",")) { // Continue with the next field mergeField(tokenizer, extensionRegistry, builder); } }
Example 18
Source File: JsonFormat.java From jigsaw-payment with Apache License 2.0 | 4 votes |
/** * Parse a single field from {@code tokenizer} and merge it into {@code builder}. If a ',' is * detected after the field ends, the next field will be parsed automatically */ protected void mergeField(Tokenizer tokenizer, ExtensionRegistry extensionRegistry, Message.Builder builder) throws ParseException { FieldDescriptor field; Descriptor type = builder.getDescriptorForType(); ExtensionRegistry.ExtensionInfo extension = null; boolean unknown = false; String name = tokenizer.consumeIdentifier(); field = type.findFieldByName(name); // Group names are expected to be capitalized as they appear in the // .proto file, which actually matches their type names, not their field // names. if (field == null) { // Explicitly specify US locale so that this code does not break when // executing in Turkey. String lowerName = name.toLowerCase(Locale.US); field = type.findFieldByName(lowerName); // If the case-insensitive match worked but the field is NOT a group, if ((field != null) && (field.getType() != FieldDescriptor.Type.GROUP)) { field = null; } } // Again, special-case group names as described above. if ((field != null) && (field.getType() == FieldDescriptor.Type.GROUP) && !field.getMessageType().getName().equals(name)) { field = null; } // Last try to lookup by field-index if 'name' is numeric, // which indicates a possible unknown field if (field == null && TextUtils.isDigits(name)) { field = type.findFieldByNumber(Integer.parseInt(name)); unknown = true; } // Finally, look for extensions extension = extensionRegistry.findExtensionByName(name); if (extension != null) { if (extension.descriptor.getContainingType() != type) { throw tokenizer.parseExceptionPreviousToken("Extension \"" + name + "\" does not extend message type \"" + type.getFullName() + "\"."); } field = extension.descriptor; } // Disabled throwing exception if field not found, since it could be a different version. if (field == null) { handleMissingField(tokenizer, extensionRegistry, builder); //throw tokenizer.parseExceptionPreviousToken("Message type \"" + type.getFullName() // + "\" has no field named \"" + name // + "\"."); } if (field != null) { tokenizer.consume(":"); boolean array = tokenizer.tryConsume("["); if (array) { while (!tokenizer.tryConsume("]")) { handleValue(tokenizer, extensionRegistry, builder, field, extension, unknown); tokenizer.tryConsume(","); } } else { handleValue(tokenizer, extensionRegistry, builder, field, extension, unknown); } } if (tokenizer.tryConsume(",")) { // Continue with the next field mergeField(tokenizer, extensionRegistry, builder); } }
Example 19
Source File: JsonJacksonFormat.java From jigsaw-payment with Apache License 2.0 | 4 votes |
/** * Parse a single field from {@code parser} and merge it into {@code builder}. If a ',' is * detected after the field ends, the next field will be parsed automatically * @throws IOException * @throws JsonParseException */ protected void mergeField(JsonParser parser, ExtensionRegistry extensionRegistry, Message.Builder builder) throws JsonParseException, IOException { FieldDescriptor field = null; Descriptor type = builder.getDescriptorForType(); boolean unknown = false; ExtensionRegistry.ExtensionInfo extension = null; JsonToken token = parser.getCurrentToken(); if (token != null) { String name = parser.getCurrentName(); if (name.contains(".")) { // should be an extension extension = extensionRegistry.findExtensionByName(name); if (extension == null) { throw new RuntimeException("Extension \"" + name + "\" not found in the ExtensionRegistry."); } else if (extension.descriptor.getContainingType() != type) { throw new RuntimeException("Extension \"" + name + "\" does not extend message type \"" + type.getFullName() + "\"."); } field = extension.descriptor; } else { field = type.findFieldByName(name); } // Group names are expected to be capitalized as they appear in the // .proto file, which actually matches their type names, not their field // names. if (field == null) { // Explicitly specify US locale so that this code does not break when // executing in Turkey. String lowerName = name.toLowerCase(Locale.US); field = type.findFieldByName(lowerName); // If the case-insensitive match worked but the field is NOT a group, if ((field != null) && (field.getType() != FieldDescriptor.Type.GROUP)) { field = null; } } // Again, special-case group names as described above. if ((field != null) && (field.getType() == FieldDescriptor.Type.GROUP) && !field.getMessageType().getName().equals(name) && !field.getMessageType().getFullName().equalsIgnoreCase(name) /* extension */) { field = null; } // Last try to lookup by field-index if 'name' is numeric, // which indicates a possible unknown field if (field == null && TextUtils.isDigits(name)) { field = type.findFieldByNumber(Integer.parseInt(name)); unknown = true; } // no throwing exceptions if field not found, since it could be a different version. if (field == null) { UnknownFieldSet.Builder unknownsBuilder = UnknownFieldSet.newBuilder(); handleMissingField(name, parser, extensionRegistry, unknownsBuilder); builder.setUnknownFields(unknownsBuilder.build()); } } if (field != null) { token = parser.nextToken(); boolean array = token.equals(JsonToken.START_ARRAY); if (array) { token = parser.nextToken(); while (!token.equals(JsonToken.END_ARRAY)) { handleValue(parser, extensionRegistry, builder, field, extension, unknown); token = parser.nextToken(); } } else { handleValue(parser, extensionRegistry, builder, field, extension, unknown); } } }
Example 20
Source File: JsonFormat.java From gsc-core with GNU Lesser General Public License v3.0 | 4 votes |
/** * Parse a single field from {@code tokenizer} and merge it into {@code builder}. If a ',' is * detected after the field ends, the next field will be parsed automatically */ protected static void mergeField(Tokenizer tokenizer, ExtensionRegistry extensionRegistry, Message.Builder builder, boolean selfType) throws ParseException { FieldDescriptor field; Descriptor type = builder.getDescriptorForType(); final ExtensionRegistry.ExtensionInfo extension; boolean unknown = false; String name = tokenizer.consumeIdentifier(); field = type.findFieldByName(name); // Group names are expected to be capitalized as they appear in the // .proto file, which actually matches their type names, not their field // names. if (field == null) { // Explicitly specify US locale so that this code does not break when // executing in Turkey. String lowerName = name.toLowerCase(Locale.US); field = type.findFieldByName(lowerName); // If the case-insensitive match worked but the field is NOT a group, if ((field != null) && (field.getType() != FieldDescriptor.Type.GROUP)) { field = null; } } // Again, special-case group names as described above. if ((field != null) && (field.getType() == FieldDescriptor.Type.GROUP) && !field.getMessageType().getName().equals(name)) { field = null; } // Last try to lookup by field-index if 'name' is numeric, // which indicates a possible unknown field if (field == null && DIGITS.matcher(name).matches()) { field = type.findFieldByNumber(Integer.parseInt(name)); unknown = true; } // Finally, look for extensions extension = extensionRegistry.findExtensionByName(name); if (extension != null) { if (extension.descriptor.getContainingType() != type) { throw tokenizer.parseExceptionPreviousToken("Extension \"" + name + "\" does not extend message type \"" + type.getFullName() + "\"."); } field = extension.descriptor; } // Disabled throwing exception if field not found, since it could be a different version. if (field == null) { handleMissingField(tokenizer, extensionRegistry, builder); //throw tokenizer.parseExceptionPreviousToken("Message type \"" + type.getFullName() // + "\" has no field named \"" + name // + "\"."); } if (field != null) { tokenizer.consume(":"); boolean array = tokenizer.tryConsume("["); if (array) { while (!tokenizer.tryConsume("]")) { handleValue(tokenizer, extensionRegistry, builder, field, extension, unknown, selfType); tokenizer.tryConsume(","); } } else { handleValue(tokenizer, extensionRegistry, builder, field, extension, unknown, selfType); } } if (tokenizer.tryConsume(",")) { // Continue with the next field mergeField(tokenizer, extensionRegistry, builder, selfType); } }