Java Code Examples for com.google.protobuf.Descriptors.EnumDescriptor#findValueByNumber()

The following examples show how to use com.google.protobuf.Descriptors.EnumDescriptor#findValueByNumber() . 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: ProtoFieldValueParser.java    From api-compiler with Apache License 2.0 6 votes vote down vote up
/**
 * Parse Enum value {@link EnumValueDescriptor} associated with given {@link EnumDescriptor} from
 * given text if found. Otherwise, throw a {@link ParseException}.
 *
 * <p>The text could be either enum value name or enum value number.
 */
static EnumValueDescriptor parseEnum(EnumDescriptor enumType, String text) {
  EnumValueDescriptor value = null;
  if (lookingAtNumber(text)) {
    int number = parseUInt32(text);
    value = enumType.findValueByNumber(number);
    if (value == null) {
      throw new ParseException(String.format(
          "Enum type '%s' has no value with number %d", enumType.getFullName(), number));
    }
  } else {
    value = enumType.findValueByName(text);
    if (value == null) {
      throw new ParseException(String.format(
          "Enum type '%s' has no value with name '%s'", enumType.getFullName(), text));
    }
  }
  return value;
}
 
Example 2
Source File: ProtoTypeAdapter.java    From gson with Apache License 2.0 6 votes vote down vote up
/**
 * Finds an enum value in the given {@link EnumDescriptor} that matches the given JSON element,
 * either by name if the current adapter is using {@link EnumSerialization#NAME}, otherwise by
 * number. If matching by name, it uses the extension value if it is defined, otherwise it uses
 * its default value.
 *
 * @throws IllegalArgumentException if a matching name/number was not found
 */
private EnumValueDescriptor findValueByNameAndExtension(EnumDescriptor desc,
    JsonElement jsonElement) {
  if (enumSerialization == EnumSerialization.NAME) {
    // With enum name
    for (EnumValueDescriptor enumDesc : desc.getValues()) {
      String enumValue = getCustSerializedEnumValue(enumDesc.getOptions(), enumDesc.getName());
      if (enumValue.equals(jsonElement.getAsString())) {
        return enumDesc;
      }
    }
    throw new IllegalArgumentException(
        String.format("Unrecognized enum name: %s", jsonElement.getAsString()));
  } else {
    // With enum value
    EnumValueDescriptor fieldValue = desc.findValueByNumber(jsonElement.getAsInt());
    if (fieldValue == null) {
      throw new IllegalArgumentException(
          String.format("Unrecognized enum value: %s", jsonElement.getAsInt()));
    }
    return fieldValue;
  }
}
 
Example 3
Source File: MetaDataEvolutionValidator.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
private void validateEnum(@Nonnull String fieldName, @Nonnull EnumDescriptor oldEnumDescriptor, @Nonnull EnumDescriptor newEnumDescriptor) {
    for (Descriptors.EnumValueDescriptor oldEnumValue : oldEnumDescriptor.getValues()) {
        Descriptors.EnumValueDescriptor newEnumValue = newEnumDescriptor.findValueByNumber(oldEnumValue.getNumber());
        if (newEnumValue == null) {
            throw new MetaDataException("enum removes value",
                    LogMessageKeys.FIELD_NAME, fieldName);
        }
    }
}
 
Example 4
Source File: SerializeSupport.java    From curiostack with MIT License 5 votes vote down vote up
public static void printEnum(int value, JsonGenerator gen, EnumDescriptor descriptor)
    throws IOException {
  EnumValueDescriptor valueDescriptor = descriptor.findValueByNumber(value);
  if (valueDescriptor == null) {
    gen.writeNumber(value);
  } else {
    gen.writeString(valueDescriptor.getName());
  }
}
 
Example 5
Source File: CompatibilityTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
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 6
Source File: JsonFormat.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static Object handlePrimitive(Tokenizer tokenizer, FieldDescriptor field,
                                      boolean selfType)
        throws ParseException {
    Object value = null;
    if ("null".equals(tokenizer.currentToken())) {
        tokenizer.consume("null");
        return value;
    }
    switch (field.getType()) {
        case INT32:
        case SINT32:
        case SFIXED32:
            value = tokenizer.consumeInt32();
            break;

        case INT64:
        case SINT64:
        case SFIXED64:
            value = tokenizer.consumeInt64();
            break;

        case UINT32:
        case FIXED32:
            value = tokenizer.consumeUInt32();
            break;

        case UINT64:
        case FIXED64:
            value = tokenizer.consumeUInt64();
            break;

        case FLOAT:
            value = tokenizer.consumeFloat();
            break;

        case DOUBLE:
            value = tokenizer.consumeDouble();
            break;

        case BOOL:
            value = tokenizer.consumeBoolean();
            break;

        case STRING:
            value = tokenizer.consumeString();
            break;

        case BYTES:
            value = tokenizer.consumeByteString(field.getFullName(), selfType);
            break;

        case ENUM: {
            EnumDescriptor enumType = field.getEnumType();

            if (tokenizer.lookingAtInteger()) {
                int number = tokenizer.consumeInt32();
                value = enumType.findValueByNumber(number);
                if (value == null) {
                    throw tokenizer.parseExceptionPreviousToken("Enum type \""
                            + enumType.getFullName()
                            + "\" has no value with number "
                            + number + ".");
                }
            } else {
                String id = tokenizer.consumeIdentifier();
                if (StringUtils.isAllLowerCase(id)) {
                    char b = id.charAt(0);
                    b = (char) (b + 'A' - 'a');
                    String s = id.substring(1);
                    id = b + s;
                }
                value = enumType.findValueByName(id);
                if (value == null) {
                    throw tokenizer.parseExceptionPreviousToken("Enum type \""
                            + enumType.getFullName()
                            + "\" has no value named \""
                            + id + "\".");
                }
            }

            break;
        }

        case MESSAGE:
        case GROUP:
            throw new RuntimeException("Can't get here.");
        default:
    }
    return value;
}
 
Example 7
Source File: MapToMessage.java    From krpc with Apache License 2.0 4 votes vote down vote up
static Object objToMessageObjInner(Builder b, Object value, FieldDescriptor field, boolean isRepeated) {

        switch (field.getType()) {
            case INT32:
            case SINT32:
            case SFIXED32:
                return TypeSafe.anyToInt(value);

            case INT64:
            case SINT64:
            case SFIXED64:
                if( value instanceof Date)
                    return ((Date)value).getTime();
                return TypeSafe.anyToLong(value);

            case BOOL:
                return TypeSafe.anyToBool(value);

            case FLOAT:
                return TypeSafe.anyToFloat(value);

            case DOUBLE:
                return TypeSafe.anyToDouble(value);

            case UINT32:
            case FIXED32:
                return (int) (TypeSafe.anyToLong(value) & 0x00000000FFFFFFFFL);

            case UINT64:
            case FIXED64:
                BigInteger bi = new BigInteger(value.toString());
                return bi.longValue();

            case STRING:
                if( value instanceof Date)
                    return formatDate((Date)value);
                return TypeSafe.anyToString(value);

            case BYTES: {
                    if (value instanceof ByteString) {
                        return value;
                    }
                    if (value instanceof String) {
                        byte[] bb = getBytes((String) value);
                        if (bb == null) return null;
                        return ByteString.copyFrom(bb);
                    }
                    if (value instanceof byte[]) {
                        return ByteString.copyFrom((byte[]) value);
                    }

                    return null;
                }

            case ENUM: {
                    EnumDescriptor ed = field.getEnumType();
                    EnumValueDescriptor evd = ed.findValueByName(value.toString());
                    if (evd == null) {
                        evd = ed.findValueByNumber(TypeSafe.anyToInt(value));
                    }
                    if (evd == null) return null;
                    return evd;
                }

            case MESSAGE:

                Map<String, Object> map = TypeSafe.anyToMap(value);
                if (map == null) {
                    if( value instanceof MapConvertable) {
                        map = ((MapConvertable)value).toMap();
                    }
                    if( map == null ) {
                        return null;
                    }
                }

                Builder b2 = isRepeated ?
                        getRepeatedFieldBuilder(b, field.getName()) :
                                getFieldBuilder(b, field);

                for (FieldDescriptor subfield : b2.getDescriptorForType().getFields()) {
                    String subName = subfield.getName();
                    Object subValue = getValue(map, null, subName);
                    if (subValue == null) continue;
                    if (subfield.isRepeated()) {
                        objToMessageObjRepeated(b2, subValue, subfield);
                    } else {
                        objToMessageObj(b2, subValue, subfield);
                    }
                }

                return isRepeated ? null : b2.build();

            default:
                return null;
        }
    }
 
Example 8
Source File: XmlJavaxFormat.java    From jigsaw-payment with Apache License 2.0 4 votes vote down vote up
private Object handlePrimitive(XMLEventReader parser, FieldDescriptor field, String value) {
    Object result = null;

    if (value == null) // precondition check
        return result;
    
    switch (field.getType()) {
        case INT32:
        case SINT32:
        case SFIXED32:
        	result = parseInt32(value);
            break;

        case INT64:
        case SINT64:
        case SFIXED64:
        	result = parseInt64(value);
            break;

        case UINT32:
        case FIXED32:
            result = parseUInt32(value);
            break;

        case UINT64:
        case FIXED64:
            result = parseUInt64(value);
            break;

        case FLOAT:
            result = parseFloat(value);
            break;

        case DOUBLE:
            result = parseDouble(value);
            break;

        case BOOL:
            result = parseBoolean(value);
            break;

        case STRING:
            result = value;
            break;

        case BYTES:
            result = unescapeBytes(value);
            break;

        case ENUM: {
            EnumDescriptor enumType = field.getEnumType();
            if (isDigits(value)) {
                int number = parseInt32(value);
                result = enumType.findValueByNumber(number);
                if (result == null) {
                    throw new RuntimeException("Enum type \""
                    		+ enumType.getFullName()
                    		+ "\" has no value with number "
                    		+ number + ".");
                }
            } else {
                String id = value;
                result = enumType.findValueByName(id);
                if (result == 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 result;
}
 
Example 9
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 10
Source File: JsonFormat.java    From jigsaw-payment with Apache License 2.0 4 votes vote down vote up
private Object handlePrimitive(Tokenizer tokenizer, FieldDescriptor field) throws ParseException {
    Object value = null;
    if ("null".equals(tokenizer.currentToken())) {
        tokenizer.consume("null");
        return value;
    }
    switch (field.getType()) {
        case INT32:
        case SINT32:
        case SFIXED32:
            value = tokenizer.consumeInt32();
            break;

        case INT64:
        case SINT64:
        case SFIXED64:
            value = tokenizer.consumeInt64();
            break;

        case UINT32:
        case FIXED32:
            value = tokenizer.consumeUInt32();
            break;

        case UINT64:
        case FIXED64:
            value = tokenizer.consumeUInt64();
            break;

        case FLOAT:
            value = tokenizer.consumeFloat();
            break;

        case DOUBLE:
            value = tokenizer.consumeDouble();
            break;

        case BOOL:
            value = tokenizer.consumeBoolean();
            break;

        case STRING:
            value = tokenizer.consumeString();
            break;

        case BYTES:
            value = tokenizer.consumeByteString();
            break;

        case ENUM: {
            EnumDescriptor enumType = field.getEnumType();

            if (tokenizer.lookingAtInteger()) {
                int number = tokenizer.consumeInt32();
                value = enumType.findValueByNumber(number);
                if (value == null) {
                    throw tokenizer.parseExceptionPreviousToken("Enum type \""
                                                                + enumType.getFullName()
                                                                + "\" has no value with number "
                                                                + number + ".");
                }
            } else {
                String id = tokenizer.consumeIdentifier();
                value = enumType.findValueByName(id);
                if (value == null) {
                    throw tokenizer.parseExceptionPreviousToken("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: ProtobufJsonFormat.java    From tajo with Apache License 2.0 4 votes vote down vote up
private Object handlePrimitive(Tokenizer tokenizer, FieldDescriptor field) throws ParseException {
  Object value = null;
  if ("null".equals(tokenizer.currentToken())) {
    tokenizer.consume("null");
    return value;
  }
  switch (field.getType()) {
    case INT32:
    case SINT32:
    case SFIXED32:
      value = tokenizer.consumeInt32();
      break;

    case INT64:
    case SINT64:
    case SFIXED64:
      value = tokenizer.consumeInt64();
      break;

    case UINT32:
    case FIXED32:
      value = tokenizer.consumeUInt32();
      break;

    case UINT64:
    case FIXED64:
      value = tokenizer.consumeUInt64();
      break;

    case FLOAT:
      value = tokenizer.consumeFloat();
      break;

    case DOUBLE:
      value = tokenizer.consumeDouble();
      break;

    case BOOL:
      value = tokenizer.consumeBoolean();
      break;

    case STRING:
      value = tokenizer.consumeString();
      break;

    case BYTES:
      value = tokenizer.consumeByteString();
      break;

    case ENUM: {
      EnumDescriptor enumType = field.getEnumType();

      if (tokenizer.lookingAtInteger()) {
        int number = tokenizer.consumeInt32();
        value = enumType.findValueByNumber(number);
        if (value == null) {
          throw tokenizer.parseExceptionPreviousToken("Enum type \""
              + enumType.getFullName()
              + "\" has no value with number "
              + number + ".");
        }
      } else {
        String id = tokenizer.consumeIdentifier();
        value = enumType.findValueByName(id);
        if (value == null) {
          throw tokenizer.parseExceptionPreviousToken("Enum type \""
              + enumType.getFullName()
              + "\" has no value named \""
              + id + "\".");
        }
      }

      break;
    }

    case MESSAGE:
    case GROUP:
      throw new RuntimeException("Can't get here.");
  }
  return value;
}
 
Example 12
Source File: ProtobufJsonFormat.java    From incubator-tajo with Apache License 2.0 4 votes vote down vote up
private Object handlePrimitive(Tokenizer tokenizer, FieldDescriptor field) throws ParseException {
  Object value = null;
  if ("null".equals(tokenizer.currentToken())) {
    tokenizer.consume("null");
    return value;
  }
  switch (field.getType()) {
    case INT32:
    case SINT32:
    case SFIXED32:
      value = tokenizer.consumeInt32();
      break;

    case INT64:
    case SINT64:
    case SFIXED64:
      value = tokenizer.consumeInt64();
      break;

    case UINT32:
    case FIXED32:
      value = tokenizer.consumeUInt32();
      break;

    case UINT64:
    case FIXED64:
      value = tokenizer.consumeUInt64();
      break;

    case FLOAT:
      value = tokenizer.consumeFloat();
      break;

    case DOUBLE:
      value = tokenizer.consumeDouble();
      break;

    case BOOL:
      value = tokenizer.consumeBoolean();
      break;

    case STRING:
      value = tokenizer.consumeString();
      break;

    case BYTES:
      value = tokenizer.consumeByteString();
      break;

    case ENUM: {
      EnumDescriptor enumType = field.getEnumType();

      if (tokenizer.lookingAtInteger()) {
        int number = tokenizer.consumeInt32();
        value = enumType.findValueByNumber(number);
        if (value == null) {
          throw tokenizer.parseExceptionPreviousToken("Enum type \""
              + enumType.getFullName()
              + "\" has no value with number "
              + number + ".");
        }
      } else {
        String id = tokenizer.consumeIdentifier();
        value = enumType.findValueByName(id);
        if (value == null) {
          throw tokenizer.parseExceptionPreviousToken("Enum type \""
              + enumType.getFullName()
              + "\" has no value named \""
              + id + "\".");
        }
      }

      break;
    }

    case MESSAGE:
    case GROUP:
      throw new RuntimeException("Can't get here.");
  }
  return value;
}
 
Example 13
Source File: DynamicSchema.java    From protobuf-dynamic with Apache License 2.0 2 votes vote down vote up
/**
 * Gets the enum value for the given enum type and number
 * 
 * @param enumTypeName the enum type name
 * @param enumNumber the enum number
 * @return the enum value descriptor (null if not found)
 */
public EnumValueDescriptor getEnumValue(String enumTypeName, int enumNumber) {
	EnumDescriptor enumType = getEnumDescriptor(enumTypeName);
	if (enumType == null) return null;
	return enumType.findValueByNumber(enumNumber);
}