下面列出了怎么用com.google.protobuf.Internal的API类实例代码及写法,或者点击链接到github查看源代码。
private static Descriptors.FieldDescriptor.JavaType getJavaType(@Nonnull Object o) {
if (o instanceof Boolean) {
return JavaType.BOOLEAN;
} else if (o instanceof ByteString || o instanceof byte[]) {
return JavaType.BYTE_STRING;
} else if (o instanceof Double) {
return JavaType.DOUBLE;
} else if (o instanceof Float) {
return JavaType.FLOAT;
} else if (o instanceof Long) {
return JavaType.LONG;
} else if (o instanceof Integer) {
return JavaType.INT;
} else if (o instanceof String) {
return JavaType.STRING;
} else if (o instanceof Internal.EnumLite) {
return JavaType.ENUM;
} else {
throw new RecordCoreException(o.getClass() + " is an invalid type for a comparand");
}
}
private byte[] getAccountStateRootHash(long blockNumber) {
long latestNumber = blockNumber;
byte[] rootHash = null;
try {
BlockWrapper blockWrapper = manager.getBlockByNum(latestNumber);
ByteString value = blockWrapper.getInstance().getBlockHeader().getRawData()
.getAccountStateRoot();
rootHash = value == null ? null : value.toByteArray();
if (Arrays.equals(rootHash, Internal.EMPTY_BYTE_ARRAY)) {
rootHash = Hash.EMPTY_TRIE_HASH;
}
} catch (Exception e) {
logger.error("Get the {} block error.", latestNumber, e);
}
return rootHash;
}
public void preExecute(BlockWrapper blockWrapper) {
this.blockWrapper = blockWrapper;
this.execute = true;
this.allowGenerateRoot = manager.getDynamicPropertiesStore().allowAccountStateRoot();
if (!exe()) {
return;
}
byte[] rootHash = null;
try {
BlockWrapper parentBlockWrapper = manager.getBlockById(blockWrapper.getParentBlockId());
rootHash = parentBlockWrapper.getInstance().getBlockHeader().getRawData()
.getAccountStateRoot().toByteArray();
} catch (Exception e) {
logger.error("", e);
}
if (Arrays.equals(Internal.EMPTY_BYTE_ARRAY, rootHash)) {
rootHash = Hash.EMPTY_TRIE_HASH;
}
trie = new TrieImpl(db, rootHash);
}
public void testMessageOrBuilderInterfaceSingleFile() throws Exception {
SingleFile.Data1.InternalOrBuilder internalBuilder = SingleFile.Data1.Internal.newBuilder()
.setIntValue(24);
assertEquals(24, internalBuilder.getIntValue());
SingleFile.Data1OrBuilder builder = SingleFile.Data1.newBuilder().setIntValue(42);
assertTrue(builder.hasIntValue());
assertEquals(42, builder.getIntValue());
SingleFile.Data1OrBuilder data = SingleFile.Data1.newBuilder()
.setIntValue(42)
.addRepeatedString("foo")
.build();
assertTrue(data.hasIntValue());
assertEquals(42, data.getIntValue());
List<String> strList = data.getRepeatedStringList();
assertEquals(1, strList.size());
assertEquals("foo", strList.get(0));
}
/**
* 寻找protobuf枚举的映射信息
*
* @param clazz protoBuffer enum
* @return map
*/
public static <T extends ProtocolMessageEnum> Internal.EnumLiteMap<T> findMapper(@Nonnull Class<T> clazz) {
Objects.requireNonNull(clazz);
try {
final Method method = clazz.getDeclaredMethod("internalGetValueMap");
method.setAccessible(true);
@SuppressWarnings("unchecked") final Internal.EnumLiteMap<T> mapper = (Internal.EnumLiteMap<T>) method.invoke(null);
return mapper;
} catch (Exception e) {
throw new IllegalArgumentException("bad class " + clazz.getName(), e);
}
}
/**
* @param typeModelMapper 类型映射信息
* @param filter 由于{@link BinarySerializer}支持的消息类是确定的,不能加入,但是允许过滤删除
*/
@SuppressWarnings("unchecked")
public static BinarySerializer newInstance(TypeModelMapper typeModelMapper, Predicate<Class<?>> filter) {
final Set<Class<?>> supportedClassSet = getFilteredSupportedClasses(filter);
final List<PojoCodecImpl<?>> codecList = new ArrayList<>(supportedClassSet.size());
try {
for (Class<?> messageClazz : supportedClassSet) {
// protoBuf消息
if (Message.class.isAssignableFrom(messageClazz)) {
Parser<?> parser = ProtoUtils.findParser((Class<? extends Message>) messageClazz);
codecList.add(new ProtoMessageCodec(messageClazz, parser));
continue;
}
// protoBufEnum
if (ProtocolMessageEnum.class.isAssignableFrom(messageClazz)) {
final Internal.EnumLiteMap<?> mapper = ProtoUtils.findMapper((Class<? extends ProtocolMessageEnum>) messageClazz);
codecList.add(new ProtoEnumCodec(messageClazz, mapper));
continue;
}
// 带有DBEntity和SerializableClass注解的所有类,和手写Serializer的类
final Class<? extends PojoCodecImpl<?>> serializerClass = CodecScanner.getCodecClass(messageClazz);
if (serializerClass != null) {
final PojoCodecImpl<?> codec = createCodecInstance(serializerClass);
codecList.add(new CustomPojoCodec(codec));
continue;
}
throw new IllegalArgumentException("Unsupported class " + messageClazz.getName());
}
final CodecRegistry codecRegistry = CodecRegistrys.fromAppPojoCodecs(typeModelMapper, codecList);
return new BinarySerializer(codecRegistry);
} catch (Exception e) {
return ExceptionUtils.rethrow(e);
}
}
public ParameterComparison(@Nonnull Type type, String parameter, @Nullable Bindings.Internal internal) {
this.type = type;
this.parameter = parameter;
if (internal == null && Bindings.Internal.isInternal(parameter)) {
throw new RecordCoreException(
"Parameter is internal, parameters cannot start with \"" + Bindings.Internal.PREFIX + "\"");
}
if (type.isUnary()) {
throw new RecordCoreException("Unary comparison type " + type + " cannot be bound to a parameter");
}
}
/**
* Calculate hash code for object.
*
* @param a the a
* @return the int
*/
private static int calculateHashCodeForObject(Object a) {
if (a instanceof byte[]) {
return Internal.hashCode((byte[]) a);
}
// Enums should be stored as integers internally.
if (a instanceof EnumLite) {
throw new UnsupportedOperationException();
}
return a.hashCode();
}
public ProtoEnumCodec(Class<T> enumClass, Internal.EnumLiteMap<T> mapper) {
this.enumClass = enumClass;
this.mapper = mapper;
}
public static <T extends com.google.protobuf.Message> T parse(Class<T> clazz,
CodedInputStream codedInputStream) throws InvalidProtocolBufferException {
T defaultInstance = Internal.getDefaultInstance(clazz);
return (T) defaultInstance.getParserForType().parseFrom(codedInputStream);
}
public void testInternalEnumLite() throws Exception {
Object value = TypicalData.EnumType.VALUE9;
assertTrue(value instanceof Internal.EnumLite);
assertEquals(9, ((Internal.EnumLite) value).getNumber());
}
/**
* Write a field of arbitrary type, without its tag, to the stream.
*
* @param output The output stream.
* @param type The field's type.
* @param value Object representing the field's value. Must be of the exact type which would be returned by
* {@link Message#getField(Descriptors.FieldDescriptor)} for this field.
* @throws IOException Signals that an I/O exception has occurred.
*/
public static void writeElementNoTag(final CodedOutputStream output, final WireFormat.FieldType type,
final Object value) throws IOException {
switch (type) {
case DOUBLE:
output.writeDoubleNoTag((Double) value);
break;
case FLOAT:
output.writeFloatNoTag((Float) value);
break;
case INT64:
output.writeInt64NoTag((Long) value);
break;
case UINT64:
output.writeUInt64NoTag((Long) value);
break;
case INT32:
output.writeInt32NoTag((Integer) value);
break;
case FIXED64:
output.writeFixed64NoTag((Long) value);
break;
case FIXED32:
output.writeFixed32NoTag((Integer) value);
break;
case BOOL:
output.writeBoolNoTag((Boolean) value);
break;
case STRING:
output.writeStringNoTag((String) value);
break;
// group not support yet
// case GROUP : output.writeGroupNoTag ((MessageLite) value); break;
case MESSAGE:
writeObject(output, 0, FieldType.OBJECT, value, false, false);
break;
case BYTES:
if (value instanceof ByteString) {
output.writeBytesNoTag((ByteString) value);
} else {
byte[] v;
if (value instanceof Byte[]) {
v = toByteArray((Byte[]) value);
} else {
v = (byte[]) value;
}
output.writeByteArrayNoTag(v);
}
break;
case UINT32:
output.writeUInt32NoTag((Integer) value);
break;
case SFIXED32:
output.writeSFixed32NoTag((Integer) value);
break;
case SFIXED64:
output.writeSFixed64NoTag((Long) value);
break;
case SINT32:
output.writeSInt32NoTag((Integer) value);
break;
case SINT64:
output.writeSInt64NoTag((Long) value);
break;
case ENUM:
if (value instanceof Internal.EnumLite) {
output.writeEnumNoTag(((Internal.EnumLite) value).getNumber());
} else {
if (value instanceof EnumReadable) {
output.writeEnumNoTag(((EnumReadable) value).value());
} else if (value instanceof Enum) {
output.writeEnumNoTag(((Enum) value).ordinal());
} else {
output.writeEnumNoTag(((Integer) value).intValue());
}
}
break;
}
}
/**
* Compute the number of bytes that would be needed to encode a particular value of arbitrary type, excluding tag.
*
* @param type The field's type.
* @param value Object representing the field's value. Must be of the exact type which would be returned by
* {@link Message#getField(Descriptors.FieldDescriptor)} for this field.
* @return the int
*/
public static int computeElementSizeNoTag(final WireFormat.FieldType type, final Object value) {
switch (type) {
// Note: Minor violation of 80-char limit rule here because this would
// actually be harder to read if we wrapped the lines.
case DOUBLE:
return CodedOutputStream.computeDoubleSizeNoTag((Double) value);
case FLOAT:
return CodedOutputStream.computeFloatSizeNoTag((Float) value);
case INT64:
return CodedOutputStream.computeInt64SizeNoTag((Long) value);
case UINT64:
return CodedOutputStream.computeUInt64SizeNoTag((Long) value);
case INT32:
return CodedOutputStream.computeInt32SizeNoTag((Integer) value);
case FIXED64:
return CodedOutputStream.computeFixed64SizeNoTag((Long) value);
case FIXED32:
return CodedOutputStream.computeFixed32SizeNoTag((Integer) value);
case BOOL:
return CodedOutputStream.computeBoolSizeNoTag((Boolean) value);
case STRING:
return CodedOutputStream.computeStringSizeNoTag((String) value);
case GROUP:
return CodedOutputStream.computeGroupSizeNoTag((MessageLite) value);
case BYTES:
if (value instanceof ByteString) {
return CodedOutputStream.computeBytesSizeNoTag((ByteString) value);
} else {
if (value instanceof Byte[]) {
return computeLengthDelimitedFieldSize(((Byte[]) value).length);
}
return CodedOutputStream.computeByteArraySizeNoTag((byte[]) value);
}
case UINT32:
return CodedOutputStream.computeUInt32SizeNoTag((Integer) value);
case SFIXED32:
return CodedOutputStream.computeSFixed32SizeNoTag((Integer) value);
case SFIXED64:
return CodedOutputStream.computeSFixed64SizeNoTag((Long) value);
case SINT32:
return CodedOutputStream.computeSInt32SizeNoTag((Integer) value);
case SINT64:
return CodedOutputStream.computeSInt64SizeNoTag((Long) value);
case MESSAGE:
if (value instanceof LazyField) {
return CodedOutputStream.computeLazyFieldSizeNoTag((LazyField) value);
} else {
return computeObjectSizeNoTag(value);
}
case ENUM:
if (value instanceof Internal.EnumLite) {
return CodedOutputStream.computeEnumSizeNoTag(((Internal.EnumLite) value).getNumber());
} else {
if (value instanceof EnumReadable) {
return CodedOutputStream.computeEnumSizeNoTag(((EnumReadable) value).value());
} else if (value instanceof Enum) {
return CodedOutputStream.computeEnumSizeNoTag(((Enum) value).ordinal());
}
return CodedOutputStream.computeEnumSizeNoTag((Integer) value);
}
}
throw new RuntimeException("There is no way to get here, but the compiler thinks otherwise.");
}