下面列出了怎么用io.grpc.MethodDescriptor.PrototypeMarshaller的API类实例代码及写法,或者点击链接到github查看源代码。
public ByteBuf serializeRequest(I message) throws IOException {
switch (requestType) {
case PROTOBUF:
final PrototypeMarshaller<I> marshaller = (PrototypeMarshaller<I>) requestMarshaller;
return serializeProto(marshaller, (Message) message);
default:
final CompositeByteBuf out = alloc.compositeBuffer();
try (ByteBufOutputStream os = new ByteBufOutputStream(out)) {
if (isProto) {
ByteStreams.copy(method.streamRequest(message), os);
} else {
jsonMarshaller.serializeMessage(requestMarshaller, message, os);
}
}
return out;
}
}
public ByteBuf serializeResponse(O message) throws IOException {
switch (responseType) {
case PROTOBUF:
final PrototypeMarshaller<O> marshaller =
(PrototypeMarshaller<O>) method.getResponseMarshaller();
return serializeProto(marshaller, (Message) message);
default:
final CompositeByteBuf out = alloc.compositeBuffer();
try (ByteBufOutputStream os = new ByteBufOutputStream(out)) {
if (isProto) {
ByteStreams.copy(method.streamResponse(message), os);
} else {
jsonMarshaller.serializeMessage(responseMarshaller, message, os);
}
}
return out;
}
}
@Test
public void introspection() throws Exception {
Marshaller<Enum> enumMarshaller = ProtoLiteUtils.marshaller(Enum.getDefaultInstance());
PrototypeMarshaller<Enum> prototypeMarshaller = (PrototypeMarshaller<Enum>) enumMarshaller;
assertSame(Enum.getDefaultInstance(), prototypeMarshaller.getMessagePrototype());
assertSame(Enum.class, prototypeMarshaller.getMessageClass());
}
@Override
public <T> T deserializeMessage(Marshaller<T> marshaller, InputStream is) throws IOException {
final PrototypeMarshaller<T> prototypeMarshaller = (PrototypeMarshaller<T>) marshaller;
final Message prototype = (Message) prototypeMarshaller.getMessagePrototype();
final Message.Builder builder = prototype.newBuilderForType();
delegate.mergeValue(is, builder);
@SuppressWarnings("unchecked")
final T cast = (T) builder.build();
return cast;
}
@Nullable
private static Message marshallerPrototype(Marshaller<?> marshaller) {
if (marshaller instanceof PrototypeMarshaller) {
final Object prototype = ((PrototypeMarshaller<?>) marshaller).getMessagePrototype();
if (prototype instanceof Message) {
return (Message) prototype;
}
}
return null;
}
@Test
public void introspection() throws Exception {
Marshaller<Enum> enumMarshaller = ProtoLiteUtils.marshaller(Enum.getDefaultInstance());
PrototypeMarshaller<Enum> prototypeMarshaller = (PrototypeMarshaller<Enum>) enumMarshaller;
assertSame(Enum.getDefaultInstance(), prototypeMarshaller.getMessagePrototype());
assertSame(Enum.class, prototypeMarshaller.getMessageClass());
}
private static MessageType marshallerType(Marshaller<?> marshaller) {
return marshaller instanceof PrototypeMarshaller ? MessageType.PROTOBUF : MessageType.UNKNOWN;
}