Java Code Examples for com.google.protobuf.Descriptors#EnumValueDescriptor

The following examples show how to use com.google.protobuf.Descriptors#EnumValueDescriptor . 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
private void writeEnumDescriptor(
    Descriptors.EnumDescriptor enumType, PathLocation parent, int indent) {
  PathLocation location = parent.addEnum(enumType);
  writeLeadingComment(commentIndexer.getLocation(location), indent);
  indent(indent);
  writer.print("enum ");
  writer.print(enumType.getName());
  writer.println(" {");
  writeOptionsForBlock(enumType.getOptions(), indent + 1, "Enum");
  for (Descriptors.EnumValueDescriptor value : enumType.getValues()) {
    indent(indent + 1);
    writer.print(value.getName());
    writer.print(" = ");
    writer.print(value.getNumber());
    writeOptionsForList(value.getOptions(), indent + 1, "EnumValue");
    writer.println(";");
  }
  indent(indent);
  writer.print("}");
  writeTrailingComment(commentIndexer.getLocation(location), indent);
}
 
Example 2
Source Project: metastore   File: ProtoDiff.java    License: Apache License 2.0 6 votes vote down vote up
private EnumValueChangeInfo diffEnumValue(
    Descriptors.EnumValueDescriptor f_ref, Descriptors.EnumValueDescriptor f_new) {
  diffOptionsFromEnumValue(f_ref, f_new);
  EnumValueChangeInfo.Builder builder = EnumValueChangeInfo.newBuilder();

  if (!f_ref.getName().equals(f_new.getName())) {
    builder.setChangeType(ChangeType.CHANGED);
    builder.setFromName(f_ref.getName());
    builder.setToName(f_new.getName());
  }
  if (isDeprecated(f_ref) != isDeprecated(f_new)) {
    builder.setChangeType(ChangeType.CHANGED);
    builder.setFromDeprecated(isDeprecated(f_ref));
    builder.setToDeprecated(isDeprecated(f_new));
  }

  if (builder.getChangeType().equals(ChangeType.CHANGED)) {
    return builder.build();
  }
  return null;
}
 
Example 3
Source Project: xresloader   File: DataDstPbHelper.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
static public void dumpConstIntoHashMap(String package_name, HashMap<String, Object> parent,
        Descriptors.EnumDescriptor enum_desc) {
    String enum_seg = enum_desc.getName();
    HashMap<String, Object> enum_root;
    if (parent.containsKey(enum_seg)) {
        Object node = parent.get(enum_seg);
        if (node instanceof HashMap) {
            enum_root = (HashMap<String, Object>) node;
        } else {
            ProgramOptions.getLoger().error("enum name %s.%s conflict.", package_name, enum_seg);
            return;
        }
    } else {
        enum_root = new HashMap<String, Object>();
        parent.put(enum_seg, enum_root);
    }

    // 写出所有常量值
    for (Descriptors.EnumValueDescriptor enum_val : enum_desc.getValues()) {
        enum_root.put(enum_val.getName(), enum_val.getNumber());
    }
}
 
Example 4
Source Project: xresloader   File: DataDstPb.java    License: MIT License 6 votes vote down vote up
static Descriptors.EnumValueDescriptor get_enum_value(PbInfoSet pbs, Descriptors.EnumDescriptor enum_desc,
        Integer val) {
    String name = enum_desc.getFullName();
    while (!name.isEmpty() && '.' == name.charAt(0)) {
        name = name.substring(1);
    }
    HashMap<Integer, Descriptors.EnumValueDescriptor> cache_set = pbs.enum_values_descs.getOrDefault(name, null);
    if (cache_set == null) {
        cache_set = new HashMap<Integer, Descriptors.EnumValueDescriptor>();
        pbs.enum_values_descs.put(name, cache_set);
        for (Descriptors.EnumValueDescriptor enum_val : enum_desc.getValues()) {
            cache_set.put(Integer.valueOf(enum_val.getNumber()), enum_val);
        }
    }

    return cache_set.getOrDefault(val, null);
}
 
Example 5
Source Project: fdb-record-layer   File: TupleTypeUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert a value into a type that can be stored within a {@link Tuple}.
 *
 * @param obj the value to convert
 * @return the value converted to some {@link Tuple}-encodable type
 */
@Nullable
static Object toTupleAppropriateValue(@Nullable Object obj) {
    if (obj instanceof Key.Evaluated.NullStandin) {
        return null;
    } else if (obj instanceof ByteString) {
        return ((ByteString) obj).toByteArray();
    } else if (obj instanceof List) {
        return toTupleAppropriateList((List<?>) obj);
    // Following two are both Internal.EnumLite, so could use that, too.
    } else if (obj instanceof ProtocolMessageEnum) {
        return ((ProtocolMessageEnum) obj).getNumber();
    } else if (obj instanceof Descriptors.EnumValueDescriptor) {
        return ((Descriptors.EnumValueDescriptor) obj).getNumber();
    } else if (obj instanceof FDBRecordVersion) {
        return ((FDBRecordVersion) obj).toVersionstamp(false);
    } else {
        return obj;
    }
}
 
Example 6
/**
 * set preparedstatement params
 * 
 * @param ps
 * @param args
 * @return
 * @throws SQLException
 */
private void populate(PreparedStatement ps, List<?> args)
		throws SQLException {
	for (int i = 0; i < args.size(); i++) {
		Object o = args.get(i);
		if (o instanceof Integer) {
			ps.setInt(i + 1, (int) o);
		} else if (o instanceof Long) {
			ps.setLong(i + 1, (long) o);
		} else if (o instanceof String) {
			ps.setString(i + 1, (String) o);
		} else if (o instanceof Date) {
			ps.setDate(i + 1, (Date) o);
		} else if (o instanceof Float) {
			ps.setFloat(i + 1, (Float) o);
		} else if (o instanceof Double) {
			ps.setDouble(i + 1, (Double) o);
		} else if (o instanceof Date) {
			ps.setDate(i + 1, (Date) o);
		} else if (o instanceof Timestamp) {
			ps.setTimestamp(i + 1, (Timestamp) o);
		} else if (o instanceof Descriptors.EnumValueDescriptor) {
			ps.setInt(i + 1,
					((Descriptors.EnumValueDescriptor) o).getNumber());
		} else if(o instanceof Boolean){
			ps.setBoolean(i+1, (Boolean)o);
		} else {
			ps.setObject(i+1, o);
		}
	}
}
 
Example 7
/**
 * Translates given parquet enum value to protocol buffer enum value.
 * @throws org.apache.parquet.io.InvalidRecordException is there is no corresponding value.
 * */
private Descriptors.EnumValueDescriptor translateEnumValue(Binary binaryValue) {
  Descriptors.EnumValueDescriptor protoValue = enumLookup.get(binaryValue);

  if (protoValue == null) {
    Set<Binary> knownValues = enumLookup.keySet();
    String msg = "Illegal enum value \"" + binaryValue + "\""
            + " in protocol buffer \"" + fieldType.getFullName() + "\""
            + " legal values are: \"" + knownValues + "\"";
    throw new InvalidRecordException(msg);
  }
  return protoValue;
}
 
Example 8
@Override
public void setDictionary(Dictionary dictionary) {
  dict = new  Descriptors.EnumValueDescriptor[dictionary.getMaxId() + 1];
  for (int i = 0; i <= dictionary.getMaxId(); i++) {
    Binary binaryValue = dictionary.decodeToBinary(i);
    dict[i] = translateEnumValue(binaryValue);
  }
}
 
Example 9
Source Project: beast   File: EnumField.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object getValue() {
    if (descriptor.isRepeated()) {
        List<Descriptors.EnumValueDescriptor> enumValues = ((List<Descriptors.EnumValueDescriptor>) (fieldValue));
        List<String> enumStrValues = new ArrayList<>();
        for (Descriptors.EnumValueDescriptor enumVal : enumValues) {
            enumStrValues.add(enumVal.toString());
        }
        return enumStrValues;
    }
    return fieldValue.toString();
}
 
Example 10
Source Project: garmadon   File: ProtoConcatenator.java    License: Apache License 2.0 5 votes vote down vote up
private static Object getRealFieldValue(Object valueObject) {
    if (valueObject != null && valueObject instanceof Descriptors.EnumValueDescriptor) {
        return ((Descriptors.EnumValueDescriptor) valueObject).getName();
    } else {
        return valueObject;
    }
}
 
Example 11
Source Project: garmadon   File: ProtoConcatenatorTest.java    License: Apache License 2.0 5 votes vote down vote up
private static Object getProtoFieldValueByName(Message message, String fieldName) {
    Object field = message.getField(message.getDescriptorForType().findFieldByName(fieldName));
    if(field instanceof Descriptors.EnumValueDescriptor){
        return ((Descriptors.EnumValueDescriptor) field).getName();
    } else {
        return field;
    }
}
 
Example 12
public static Object toTupleItem(@Nullable Object item) {
    if (item instanceof ByteString) {
        return ((ByteString) item).toByteArray();
    // Following two are both Internal.EnumLite, so could use that, too.
    } else if (item instanceof ProtocolMessageEnum) {
        return ((ProtocolMessageEnum) item).getNumber();
    } else if (item instanceof Descriptors.EnumValueDescriptor) {
        return ((Descriptors.EnumValueDescriptor) item).getNumber();
    } else if (item instanceof FDBRecordVersion) {
        return ((FDBRecordVersion) item).toVersionstamp();
    } else {
        return item;
    }
}
 
Example 13
Source Project: fdb-record-layer   File: TupleTypeUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Normalize a value so that it compares equal to anything with the same {@link Tuple} representation.
 * The value that is returned cannot necessarily be packed by a {@code Tuple} (for example,
 * a <code>byte[]</code> is returned as a {@link ByteString}), but it does implement {@link Object#equals(Object)}
 * and {@link Object#hashCode()}, so the value can be used in hash-based data structures like
 * {@link java.util.HashSet HashSet}s and {@link java.util.HashMap HashMap}s. In other words, it should
 * bethe case that:
 *
 * <pre> {@code
 *   Objects.equals(toTupleEquivalentValue(value1), toTupleEquivalentValue(value2))
 *     == Arrays.equals(Tuple.from(value1).pack(), Tuple.from(value2).pack())
 * }</pre>
 *
 * <p>
 * for any two values {@code value1} and {@code value2}.
 * </p>
 *
 * <p>
 * This will only return {@code null} if {@link #toTupleAppropriateValue(Object)} would return {@code null}
 * on the same input. If the object is already in
 * </p>
 *
 * @param obj the value to normalize
 * @return a value that has the same representation when {@link Tuple}-encoded
 */
@Nullable
static Object toTupleEquivalentValue(@Nullable Object obj) {
    if (obj == null || obj instanceof Key.Evaluated.NullStandin) {
        return null;
    } else if (obj instanceof List<?>) {
        List<?> list = (List<?>)obj;
        return toTupleEquivalentList(list);
    } else if (obj instanceof Tuple) {
        return toTupleEquivalentList(((Tuple)obj).getItems());
    } else if (obj instanceof byte[]) {
        return ByteString.copyFrom((byte[]) obj);
    } else if ((obj instanceof Byte) || (obj instanceof Short) || (obj instanceof Integer)) {
        return ((Number)obj).longValue();
    } else if (obj instanceof BigInteger) {
        BigInteger bigInt = (BigInteger)obj;
        if (bigInt.compareTo(BIG_INT_MIN_LONG) > 0 && bigInt.compareTo(BIG_INT_MAX_LONG) < 0) {
            return bigInt.longValue();
        } else {
            return bigInt;
        }
    } else if (obj instanceof ProtocolMessageEnum) {
        return (long)((ProtocolMessageEnum)obj).getNumber();
    } else if (obj instanceof Descriptors.EnumValueDescriptor) {
        return (long)((Descriptors.EnumValueDescriptor)obj).getNumber();
    } else if (obj instanceof FDBRecordVersion) {
        return ((FDBRecordVersion)obj).toVersionstamp(false);
    } else {
        return obj;
    }
}
 
Example 14
@Test
public void duplicateEnumSubspaceKey() {
    // This exact use case is somewhat contrived, but one could imagine maintaining an enum with one entry per index
    RecordMetaDataBuilder metaData = RecordMetaData.newBuilder().setRecords(TestRecords1Proto.getDescriptor());
    final Descriptors.EnumValueDescriptor enumValueDescriptor = TestRecordsEnumProto.MyShapeRecord.Size.SMALL.getValueDescriptor();
    metaData.getIndex("MySimpleRecord$str_value_indexed").setSubspaceKey((long)enumValueDescriptor.getNumber());
    metaData.getIndex("MySimpleRecord$num_value_3_indexed").setSubspaceKey(enumValueDescriptor);
    assertInvalid("Same subspace key " + enumValueDescriptor.getNumber() + " used by both", metaData);
}
 
Example 15
PathLocation addEnunValue(Descriptors.EnumValueDescriptor type) {
  return add('e', type.getIndex());
}
 
Example 16
Source Project: metastore   File: ValidationResults.java    License: Apache License 2.0 4 votes vote down vote up
public void add(Descriptors.EnumValueDescriptor value, RuleInfo ruleInfo) {
  EnumValueResultContainer methodResultContainer = getOrCreateValueContainer(value);
  methodResultContainer.add(ruleInfo);
}
 
Example 17
Source Project: metastore   File: ValidationResults.java    License: Apache License 2.0 4 votes vote down vote up
public void addPatch(Descriptors.EnumValueDescriptor value, EnumValueChangeInfo patch) {
  EnumValueResultContainer valueResultContainer = getOrCreateValueContainer(value);
  valueResultContainer.addPatch(patch);
}
 
Example 18
Source Project: grpc-nebula-java   File: ClientCalls.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 根据请求参数获取对应参数列表的值
 * <p>
 * 目前的方法是将参数列表中的各参数值转化为String拼接起来。 <br>
 * 对于参数列表也有一定的限制,不支持参数在嵌套的层次中,即必须在第一层。 <br>
 * 如果客户端为未配置参数列表,或者参数值列表不正确,则取按照参数名升序获取第一个非嵌套类型参数的参数值返回。  <br>
 * </p>
 *
 * @author sxp
 * @since 2019/2/1
 */
public static Object getArgumentFromRequest(Object request) {
  Map<String, Boolean> validArgs = ConsistentHashArguments.getValidArgs();

  boolean isGetFirst = false;
  if (validArgs.size() == 0) {
    isGetFirst = true;
  }

  // 遍历入参的所有参数,取出参数列表对应的参数值
  GeneratedMessageV3 param;
  try {
    param = GeneratedMessageV3.class.cast(request);
  } catch (ClassCastException e) {
    return ConsistentHashArguments.NULL_VALUE;// 入参不是GeneratedMessageV3的子类
  }

  Map<Descriptors.FieldDescriptor, Object> fieldMap = param.getAllFields();
  Descriptors.FieldDescriptor field;
  String name;
  String value;
  Descriptors.FieldDescriptor.JavaType type;
  StringBuilder sb = new StringBuilder();

  for (Iterator<Descriptors.FieldDescriptor> keys = fieldMap.keySet().iterator(); keys.hasNext(); ) {
    field = keys.next();
    name = field.getName();

    if (!validArgs.containsKey(name) && !isGetFirst) {
      continue;
    }

    type = field.getJavaType();
    if (type.equals(Descriptors.FieldDescriptor.JavaType.MESSAGE)) {
      // 嵌套数据类型
    } else if (type.equals(Descriptors.FieldDescriptor.JavaType.ENUM)) {
      Descriptors.EnumValueDescriptor en = (Descriptors.EnumValueDescriptor) fieldMap.get(field);
      value = String.valueOf(en.toProto().getNumber());
      sb.append(value);
    } else {
      value = String.valueOf(fieldMap.get(field));
      sb.append(value);
    }

    if (isGetFirst && sb.length() > 0) {
      break;
    }
  }

  String result = sb.toString();

  if (StringUtils.isEmpty(result)) {
    return String.valueOf(System.currentTimeMillis());
  } else {
    return result;
  }
}
 
Example 19
@Override
final public void addBinary(Binary binaryValue) {
  Descriptors.EnumValueDescriptor protoValue = translateEnumValue(binaryValue);
  parent.add(protoValue);
}
 
Example 20
Source Project: krpc   File: BeanToMessage.java    License: Apache License 2.0 4 votes vote down vote up
static Object objToMessageObjInner(Builder b, Object value, Descriptors.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:
                Descriptors.EnumDescriptor ed = field.getEnumType();
                Descriptors.EnumValueDescriptor evd = ed.findValueByName(value.toString());
                if (evd == null) {
                    evd = ed.findValueByNumber(TypeSafe.anyToInt(value));
                }
                if (evd == null) return null;
                return evd;

            case MESSAGE:

                Object bean = value;

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

                for (Descriptors.FieldDescriptor subfield : b2.getDescriptorForType().getFields()) {
                    String subName = subfield.getName();
                    Object subValue = getValue(bean, 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;
        }
    }