Java Code Examples for com.google.protobuf.Descriptors.FieldDescriptor#getType()

The following examples show how to use com.google.protobuf.Descriptors.FieldDescriptor#getType() . 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: AbstractMessage.java    From travelguide with Apache License 2.0 6 votes vote down vote up
public void writeTo(final CodedOutputStream output) throws IOException {
  final boolean isMessageSet =
      getDescriptorForType().getOptions().getMessageSetWireFormat();

  for (final Map.Entry<FieldDescriptor, Object> entry :
      getAllFields().entrySet()) {
    final FieldDescriptor field = entry.getKey();
    final Object value = entry.getValue();
    if (isMessageSet && field.isExtension() &&
        field.getType() == FieldDescriptor.Type.MESSAGE &&
        !field.isRepeated()) {
      output.writeMessageSetExtension(field.getNumber(), (Message) value);
    } else {
      FieldSet.writeField(field, value, output);
    }
  }

  final UnknownFieldSet unknownFields = getUnknownFields();
  if (isMessageSet) {
    unknownFields.writeAsMessageSetTo(output);
  } else {
    unknownFields.writeTo(output);
  }
}
 
Example 2
Source File: AbstractMessage.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void writeTo(final CodedOutputStream output) throws IOException {
  final boolean isMessageSet =
      getDescriptorForType().getOptions().getMessageSetWireFormat();

  for (final Map.Entry<FieldDescriptor, Object> entry :
      getAllFields().entrySet()) {
    final FieldDescriptor field = entry.getKey();
    final Object value = entry.getValue();
    if (isMessageSet && field.isExtension() &&
        field.getType() == FieldDescriptor.Type.MESSAGE &&
        !field.isRepeated()) {
      output.writeMessageSetExtension(field.getNumber(), (Message) value);
    } else {
      FieldSet.writeField(field, value, output);
    }
  }

  final UnknownFieldSet unknownFields = getUnknownFields();
  if (isMessageSet) {
    unknownFields.writeAsMessageSetTo(output);
  } else {
    unknownFields.writeTo(output);
  }
}
 
Example 3
Source File: AbstractMessage.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/** Get a hash code for given fields and values, using the given seed. */
@SuppressWarnings("unchecked")
protected static int hashFields(int hash, Map<FieldDescriptor, Object> map) {
  for (Map.Entry<FieldDescriptor, Object> entry : map.entrySet()) {
    FieldDescriptor field = entry.getKey();
    Object value = entry.getValue();
    hash = (37 * hash) + field.getNumber();
    if (field.getType() != FieldDescriptor.Type.ENUM){
      hash = (53 * hash) + value.hashCode();
    } else if (field.isRepeated()) {
      List<? extends EnumLite> list = (List<? extends EnumLite>) value;
      hash = (53 * hash) + Internal.hashEnumList(list);
    } else {
      hash = (53 * hash) + Internal.hashEnum((EnumLite) value);
    }
  }
  return hash;
}
 
Example 4
Source File: AbstractMessage.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Get a hash code for given fields and values, using the given seed. */
@SuppressWarnings("unchecked")
protected int hashFields(int hash, Map<FieldDescriptor, Object> map) {
  for (Map.Entry<FieldDescriptor, Object> entry : map.entrySet()) {
    FieldDescriptor field = entry.getKey();
    Object value = entry.getValue();
    hash = (37 * hash) + field.getNumber();
    if (field.getType() != FieldDescriptor.Type.ENUM){
      hash = (53 * hash) + value.hashCode();
    } else if (field.isRepeated()) {
      List<? extends EnumLite> list = (List<? extends EnumLite>) value;
      hash = (53 * hash) + hashEnumList(list);
    } else {
      hash = (53 * hash) + hashEnum((EnumLite) value);
    }
  }
  return hash;
}
 
Example 5
Source File: ExtensionRegistry.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void add(final ExtensionInfo extension) {
  if (!extension.descriptor.isExtension()) {
    throw new IllegalArgumentException(
      "ExtensionRegistry.add() was given a FieldDescriptor for a regular " +
      "(non-extension) field.");
  }

  extensionsByName.put(extension.descriptor.getFullName(), extension);
  extensionsByNumber.put(
    new DescriptorIntPair(extension.descriptor.getContainingType(),
                          extension.descriptor.getNumber()),
    extension);

  final FieldDescriptor field = extension.descriptor;
  if (field.getContainingType().getOptions().getMessageSetWireFormat() &&
      field.getType() == FieldDescriptor.Type.MESSAGE &&
      field.isOptional() &&
      field.getExtensionScope() == field.getMessageType()) {
    // This is an extension of a MessageSet type defined within the extension
    // type's own scope.  For backwards-compatibility, allow it to be looked
    // up by type name.
    extensionsByName.put(field.getMessageType().getFullName(), extension);
  }
}
 
Example 6
Source File: DynamicMessage.java    From play-store-api with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Builder setField(FieldDescriptor field, Object value) {
  verifyContainingType(field);
  ensureIsMutable();
  // TODO(xiaofeng): This check should really be put in FieldSet.setField()
  // where all other such checks are done. However, currently
  // FieldSet.setField() permits Integer value for enum fields probably
  // because of some internal features we support. Should figure it out
  // and move this check to a more appropriate place.
  if (field.getType() == FieldDescriptor.Type.ENUM) {
    ensureEnumValueDescriptor(field, value);
  }
  OneofDescriptor oneofDescriptor = field.getContainingOneof();
  if (oneofDescriptor != null) {
    int index = oneofDescriptor.getIndex();
    FieldDescriptor oldField = oneofCases[index];
    if ((oldField != null) && (oldField != field)) {
      fields.clearField(oldField);
    }
    oneofCases[index] = field;
  }
  fields.setField(field, value);
  return this;
}
 
Example 7
Source File: AbstractMessage.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public int getSerializedSize() {
  int size = memoizedSize;
  if (size != -1) {
    return size;
  }

  size = 0;
  final boolean isMessageSet =
      getDescriptorForType().getOptions().getMessageSetWireFormat();

  for (final Map.Entry<FieldDescriptor, Object> entry :
      getAllFields().entrySet()) {
    final FieldDescriptor field = entry.getKey();
    final Object value = entry.getValue();
    if (isMessageSet && field.isExtension() &&
        field.getType() == FieldDescriptor.Type.MESSAGE &&
        !field.isRepeated()) {
      size += CodedOutputStream.computeMessageSetExtensionSize(
          field.getNumber(), (Message) value);
    } else {
      size += FieldSet.computeFieldSize(field, value);
    }
  }

  final UnknownFieldSet unknownFields = getUnknownFields();
  if (isMessageSet) {
    size += unknownFields.getSerializedSizeAsMessageSet();
  } else {
    size += unknownFields.getSerializedSize();
  }

  memoizedSize = size;
  return size;
}
 
Example 8
Source File: JsonJacksonFormat.java    From jigsaw-payment with Apache License 2.0 5 votes vote down vote up
private void printSingleField(FieldDescriptor field,
                                     Object value,
                                     JsonGenerator generator) throws IOException {
    if (field.isExtension()) {
        // We special-case MessageSet elements for compatibility with proto1.
        if (field.getContainingType().getOptions().getMessageSetWireFormat()
            && (field.getType() == FieldDescriptor.Type.MESSAGE) && (field.isOptional())
            // object equality
            && (field.getExtensionScope() == field.getMessageType())) {
            generator.writeFieldName(field.getMessageType().getFullName());
        } else {
        	// extensions will have '.' in them, while normal fields wont..
        	generator.writeFieldName(field.getFullName());
        }
    } else {
        if (field.getType() == FieldDescriptor.Type.GROUP) {
            // Groups must be serialized with their original capitalization.
            generator.writeFieldName(field.getMessageType().getName());
        } else {
            generator.writeFieldName(field.getName());
        }
    }

    // Done with the name, on to the value
    if (field.isRepeated()) {
        // Repeated field. Print each element.
        generator.writeStartArray();
        for (Iterator<?> iter = ((List<?>) value).iterator(); iter.hasNext();) {
            printFieldValue(field, iter.next(), generator);
        }
        generator.writeEndArray();
    } else {
        printFieldValue(field, value, generator);
    }
}
 
Example 9
Source File: YamlNodeReader.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
private void readField(ConfigSource.Builder builder, FieldDescriptor field, Node value,
    String path) {
  if (!helper.checkAndAddPath(path, value, field)){
    return;
  }
  if (field.getType() == FieldDescriptor.Type.MESSAGE) {
    handleMessageField(builder, field, value, path);
  } else {
    handleNonMessageField(builder, field, value);
  }
}
 
Example 10
Source File: JsonJacksonFormat.java    From jigsaw-payment with Apache License 2.0 4 votes vote down vote up
private Object handlePrimitive(JsonParser parser, FieldDescriptor field) throws IOException {
    Object value = null;

    JsonToken token = parser.getCurrentToken();

    if (token.equals(JsonToken.VALUE_NULL)) {
        return value;
    }

    switch (field.getType()) {
        case INT32:
        case SINT32:
        case SFIXED32:
        	value = parser.getIntValue();
            break;

        case INT64:
        case SINT64:
        case SFIXED64:
        	value = parser.getLongValue();
            break;

        case UINT32:
        case FIXED32:
        	long valueLong = parser.getLongValue();
        	if (valueLong < 0 || valueLong > MAX_UINT_VALUE) {
        		throw new NumberFormatException("Number must be positive: " + valueLong);
        	}
        	value = (int) valueLong;
            break;

        case UINT64:
        case FIXED64:
        	BigInteger valueBigInt = parser.getBigIntegerValue();
            // valueBigInt < 0 || valueBigInt > MAX_ULONG_VALUE
        	if (valueBigInt.compareTo(BigInteger.ZERO) == -1 || valueBigInt.compareTo(MAX_ULONG_VALUE) == 1) {
        		throw new NumberFormatException("Number must be positive: " + valueBigInt);
        	}
        	value = valueBigInt.longValue();
            break;

        case FLOAT:
        	value = parser.getFloatValue();
            break;

        case DOUBLE:
        	value = parser.getDoubleValue();
            break;

        case BOOL:
        	value = parser.getBooleanValue();
            break;

        case STRING:
        	value = parser.getText();
            break;

        case BYTES:
        	value = ByteString.copyFrom(parser.getBinaryValue());
            break;

        case ENUM: {
            EnumDescriptor enumType = field.getEnumType();
            if (token.equals(JsonToken.VALUE_NUMBER_INT)) {
                int number = parser.getIntValue();
                value = enumType.findValueByNumber(number);
                if (value == null) {
                    throw new RuntimeException("Enum type \""
                    		+ enumType.getFullName()
                    		+ "\" has no value with number "
                    		+ number + ".");
                }
            } else {
                String id = parser.getText();
                value = enumType.findValueByName(id);
                if (value == null) {
                	throw new RuntimeException("Enum type \""
                			+ enumType.getFullName()
                			+ "\" has no value named \""
                			+ id + "\".");
                }
            }
            break;
        }

        case MESSAGE:
        case GROUP:
            throw new RuntimeException("Can't get here.");
    }
    return value;
}
 
Example 11
Source File: TextFormat.java    From play-store-api with GNU General Public License v3.0 4 votes vote down vote up
private void printSingleField(final FieldDescriptor field,
                              final Object value,
                              final TextGenerator generator)
                              throws IOException {
  if (field.isExtension()) {
    generator.print("[");
    // We special-case MessageSet elements for compatibility with proto1.
    if (field.getContainingType().getOptions().getMessageSetWireFormat()
        && (field.getType() == FieldDescriptor.Type.MESSAGE)
        && (field.isOptional())
        // object equality
        && (field.getExtensionScope() == field.getMessageType())) {
      generator.print(field.getMessageType().getFullName());
    } else {
      generator.print(field.getFullName());
    }
    generator.print("]");
  } else {
    if (field.getType() == FieldDescriptor.Type.GROUP) {
      // Groups must be serialized with their original capitalization.
      generator.print(field.getMessageType().getName());
    } else {
      generator.print(field.getName());
    }
  }

  if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
    if (singleLineMode) {
      generator.print(" { ");
    } else {
      generator.print(" {\n");
      generator.indent();
    }
  } else {
    generator.print(": ");
  }

  printFieldValue(field, value, generator);

  if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
    if (singleLineMode) {
      generator.print("} ");
    } else {
      generator.outdent();
      generator.print("}\n");
    }
  } else {
    if (singleLineMode) {
      generator.print(" ");
    } else {
      generator.print("\n");
    }
  }
}
 
Example 12
Source File: JsonJacksonFormat.java    From jigsaw-payment with Apache License 2.0 4 votes vote down vote up
/**
 * 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 13
Source File: TextFormat.java    From android-chromium with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void printFieldValue(final FieldDescriptor field,
                             final Object value,
                             final TextGenerator generator)
                             throws IOException {
  switch (field.getType()) {
    case INT32:
    case SINT32:
    case SFIXED32:
      generator.print(((Integer) value).toString());
      break;

    case INT64:
    case SINT64:
    case SFIXED64:
      generator.print(((Long) value).toString());
      break;

    case BOOL:
      generator.print(((Boolean) value).toString());
      break;

    case FLOAT:
      generator.print(((Float) value).toString());
      break;

    case DOUBLE:
      generator.print(((Double) value).toString());
      break;

    case UINT32:
    case FIXED32:
      generator.print(unsignedToString((Integer) value));
      break;

    case UINT64:
    case FIXED64:
      generator.print(unsignedToString((Long) value));
      break;

    case STRING:
      generator.print("\"");
      generator.print(escapeNonAscii ?
          escapeText((String) value) :
          (String) value);
      generator.print("\"");
      break;

    case BYTES:
      generator.print("\"");
      generator.print(escapeBytes((ByteString) value));
      generator.print("\"");
      break;

    case ENUM:
      generator.print(((EnumValueDescriptor) value).getName());
      break;

    case MESSAGE:
    case GROUP:
      print((Message) value, generator);
      break;
  }
}
 
Example 14
Source File: XmlFormat.java    From jigsaw-payment with Apache License 2.0 4 votes vote down vote up
private void printFieldValue(FieldDescriptor field, Object value, XmlGenerator generator) throws IOException {
    switch (field.getType()) {
        case INT32:
        case INT64:
        case SINT32:
        case SINT64:
        case SFIXED32:
        case SFIXED64:
        case FLOAT:
        case DOUBLE:
        case BOOL:
            // Good old toString() does what we want for these types.
            generator.print(value.toString());
            break;

        case UINT32:
        case FIXED32:
            generator.print(unsignedToString((Integer) value));
            break;

        case UINT64:
        case FIXED64:
            generator.print(unsignedToString((Long) value));
            break;

        case STRING:
            generator.print(escapeText((String) value));
            break;

        case BYTES: {
            generator.print(escapeBytes((ByteString) value));
            break;
        }

        case ENUM: {
            generator.print(((EnumValueDescriptor) value).getName());
            break;
        }

        case MESSAGE:
        case GROUP:
            print((Message) value, generator);
            break;
    }
}
 
Example 15
Source File: XmlFormat.java    From jigsaw-payment with Apache License 2.0 4 votes vote down vote up
private void printSingleField(FieldDescriptor field, Object value, XmlGenerator generator) throws IOException {
    if (field.isExtension()) {
        generator.print("<extension type=\"");
        // We special-case MessageSet elements for compatibility with
        // proto1.
        if (field.getContainingType().getOptions().getMessageSetWireFormat()
            && (field.getType() == FieldDescriptor.Type.MESSAGE) && (field.isOptional())
            // object equality
            && (field.getExtensionScope() == field.getMessageType())) {
            generator.print(field.getMessageType().getFullName());
        } else {
            generator.print(field.getFullName());
        }
        generator.print("\">");
    } else {
        generator.print("<");
        if (field.getType() == FieldDescriptor.Type.GROUP) {
            // Groups must be serialized with their original capitalization.
            generator.print(field.getMessageType().getName());
        } else {
            generator.print(field.getName());
        }
        generator.print(">");
    }

    printFieldValue(field, value, generator);

    if (!field.isExtension()) {
        generator.print("</");
        if (field.getType() == FieldDescriptor.Type.GROUP) {
            // Groups must be serialized with their original capitalization.
            generator.print(field.getMessageType().getName());
        } else {
            generator.print(field.getName());
        }
        generator.print(">");
    } else {
        generator.print("</extension>");
    }

}
 
Example 16
Source File: ProtobufDecompiler.java    From sql-layer with GNU Affero General Public License v3.0 4 votes vote down vote up
protected String defaultAndOptions(MessageOrBuilder options, String defaultValue) {
    StringBuilder str = new StringBuilder();
    boolean first = true;
    if (defaultValue != null) {
        str.append(" [default = ");
        str.append(defaultValue); // TODO: quote
        first = false;
    }
    if (options != null) {
        for (Map.Entry<FieldDescriptor,Object> entry : options.getAllFields().entrySet()) {
            FieldDescriptor field = entry.getKey();
            Object value = entry.getValue();
            String fieldName = field.getName();
            if (field.isExtension()) {
                fieldName = "(" + fieldName + ")";
            }
            if (field.getType() == FieldDescriptor.Type.MESSAGE) {
                for (Map.Entry<FieldDescriptor,Object> subentry : ((MessageOrBuilder)value).getAllFields().entrySet()) {
                    FieldDescriptor subfield = subentry.getKey();
                    Object subvalue = subentry.getValue();
                    if (first) {
                        str.append(" [");
                        first = false;
                    }
                    else {
                        str.append(", ");
                    }
                    str.append(fieldName).append(".").append(subfield.getName()).append(" = ").append(literal(subvalue, subfield.getType()));
                }
            }
            else {
                if (first) {
                    str.append(" [");
                    first = false;
                }
                else {
                    str.append(", ");
                }
                str.append(fieldName).append(" = ").append(literal(value, field.getType()));
            }
        }
    }
    if (!first) {
        str.append("]");
    }
    return str.toString();
}
 
Example 17
Source File: TextFormat.java    From android-chromium with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void printFieldValue(final FieldDescriptor field,
                             final Object value,
                             final TextGenerator generator)
                             throws IOException {
  switch (field.getType()) {
    case INT32:
    case SINT32:
    case SFIXED32:
      generator.print(((Integer) value).toString());
      break;

    case INT64:
    case SINT64:
    case SFIXED64:
      generator.print(((Long) value).toString());
      break;

    case BOOL:
      generator.print(((Boolean) value).toString());
      break;

    case FLOAT:
      generator.print(((Float) value).toString());
      break;

    case DOUBLE:
      generator.print(((Double) value).toString());
      break;

    case UINT32:
    case FIXED32:
      generator.print(unsignedToString((Integer) value));
      break;

    case UINT64:
    case FIXED64:
      generator.print(unsignedToString((Long) value));
      break;

    case STRING:
      generator.print("\"");
      generator.print(escapeNonAscii ?
          escapeText((String) value) :
          (String) value);
      generator.print("\"");
      break;

    case BYTES:
      generator.print("\"");
      generator.print(escapeBytes((ByteString) value));
      generator.print("\"");
      break;

    case ENUM:
      generator.print(((EnumValueDescriptor) value).getName());
      break;

    case MESSAGE:
    case GROUP:
      print((Message) value, generator);
      break;
  }
}
 
Example 18
Source File: JsonFormat.java    From jigsaw-payment with Apache License 2.0 4 votes vote down vote up
private void printSingleField(FieldDescriptor field,
                                     Object value,
                                     JsonGenerator generator) throws IOException {
    if (field.isExtension()) {
        generator.print("\"");
        // We special-case MessageSet elements for compatibility with proto1.
        if (field.getContainingType().getOptions().getMessageSetWireFormat()
            && (field.getType() == FieldDescriptor.Type.MESSAGE) && (field.isOptional())
            // object equality
            && (field.getExtensionScope() == field.getMessageType())) {
            generator.print(field.getMessageType().getFullName());
        } else {
            generator.print(field.getFullName());
        }
        generator.print("\"");
    } else {
        generator.print("\"");
        if (field.getType() == FieldDescriptor.Type.GROUP) {
            // Groups must be serialized with their original capitalization.
            generator.print(field.getMessageType().getName());
        } else {
            generator.print(field.getName());
        }
        generator.print("\"");
    }

    // Done with the name, on to the value

    if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
        generator.print(": ");
        generator.indent();
    } else {
        generator.print(": ");
    }


    if (field.isRepeated()) {
        // Repeated field. Print each element.
        generator.print("[");
        for (Iterator<?> iter = ((List<?>) value).iterator(); iter.hasNext();) {
            printFieldValue(field, iter.next(), generator);
            if (iter.hasNext()) {
                generator.print(",");
            }
        }
        generator.print("]");
    } else {
        printFieldValue(field, value, generator);
        if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
            generator.outdent();
        }
    }
}
 
Example 19
Source File: TextFormat.java    From android-chromium with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void printSingleField(final FieldDescriptor field,
                              final Object value,
                              final TextGenerator generator)
                              throws IOException {
  if (field.isExtension()) {
    generator.print("[");
    // We special-case MessageSet elements for compatibility with proto1.
    if (field.getContainingType().getOptions().getMessageSetWireFormat()
        && (field.getType() == FieldDescriptor.Type.MESSAGE)
        && (field.isOptional())
        // object equality
        && (field.getExtensionScope() == field.getMessageType())) {
      generator.print(field.getMessageType().getFullName());
    } else {
      generator.print(field.getFullName());
    }
    generator.print("]");
  } else {
    if (field.getType() == FieldDescriptor.Type.GROUP) {
      // Groups must be serialized with their original capitalization.
      generator.print(field.getMessageType().getName());
    } else {
      generator.print(field.getName());
    }
  }

  if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
    if (singleLineMode) {
      generator.print(" { ");
    } else {
      generator.print(" {\n");
      generator.indent();
    }
  } else {
    generator.print(": ");
  }

  printFieldValue(field, value, generator);

  if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
    if (singleLineMode) {
      generator.print("} ");
    } else {
      generator.outdent();
      generator.print("}\n");
    }
  } else {
    if (singleLineMode) {
      generator.print(" ");
    } else {
      generator.print("\n");
    }
  }
}
 
Example 20
Source File: JsonFormat.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void printSingleField(FieldDescriptor field,
                                     Object value, JsonGenerator generator, boolean selfType) throws IOException {
    if (field.isExtension()) {
        generator.print("\"");
        // We special-case MessageSet elements for compatibility with proto1.
        if (field.getContainingType().getOptions().getMessageSetWireFormat()
                && (field.getType() == FieldDescriptor.Type.MESSAGE) && (field.isOptional())
                // object equality
                && (field.getExtensionScope() == field.getMessageType())) {
            generator.print(field.getMessageType().getFullName());
        } else {
            generator.print(field.getFullName());
        }
        generator.print("\"");
    } else {
        generator.print("\"");
        if (field.getType() == FieldDescriptor.Type.GROUP) {
            // Groups must be serialized with their original capitalization.
            generator.print(field.getMessageType().getName());
        } else {
            generator.print(field.getName());
        }
        generator.print("\"");
    }

    // Done with the name, on to the value

    if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
        generator.print(": ");
        generator.indent();
    } else {
        generator.print(": ");
    }

    if (field.isRepeated()) {
        // Repeated field. Print each element.
        generator.print("[");
        for (Iterator<?> iter = ((List<?>) value).iterator(); iter.hasNext(); ) {
            printFieldValue(field, iter.next(), generator, selfType);
            if (iter.hasNext()) {
                generator.print(",");
            }
        }
        generator.print("]");
    } else {
        printFieldValue(field, value, generator, selfType);
        if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
            generator.outdent();
        }
    }
}