protected void mergeField(XMLEventReader parser, XMLEvent fieldEvent,
ExtensionRegistry extensionRegistry,
Message.Builder builder) throws XMLStreamException {
FieldDescriptor field = null;
Descriptor type = builder.getDescriptorForType();
boolean unknown = false;
ExtensionRegistry.ExtensionInfo extension = null;
String fieldName = fieldEvent.asStartElement().getName().getLocalPart();
XMLEvent event = parser.nextEvent();
if (event != null) {
if (fieldName.equalsIgnoreCase(EXTENSION_ELEMENT)) {
String extensionName = fieldEvent.asStartElement()
.getAttributeByName(new QName(EXTENSION_TYPE)).getValue();
// should be an extension
extension = extensionRegistry.findExtensionByName(extensionName);
if (extension == null) {
throw new RuntimeException("Extension \""
+ fieldName + "\" not found in the ExtensionRegistry.");
} else if (extension.descriptor.getContainingType() != type) {
throw new RuntimeException("Extension \"" + fieldName
+ "\" does not extend message type \""
+ type.getFullName() + "\".");
}
field = extension.descriptor;
} else {
field = type.findFieldByName(fieldName);
// 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 = fieldName.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(fieldName)
&& !field.getMessageType().getFullName().equalsIgnoreCase(fieldName) /* extension */) {
field = null;
}
// maybe an unknown-field
if (fieldName.equalsIgnoreCase(UNKNOWN_FIELD_ELEMENT)) {
String index = fieldEvent.asStartElement()
.getAttributeByName(new QName(UNKNOWN_FIELD_INDEX)).getValue();
if (index != null) {
fieldName = index; // digits to test next.
}
}
// Last try to lookup by field-index if 'name' is numeric,
// which indicates a possible unknown field
if (field == null && isDigits(fieldName)) {
field = type.findFieldByNumber(Integer.parseInt(fieldName));
unknown = true;
}
// no throwing exceptions if field not found, since it could be a different version.
if (field == null) {