下面列出了怎么用io.grpc.MethodDescriptor.Marshaller的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
<T> void logRpcMessage(
long seq,
EventType eventType,
Marshaller<T> marshaller,
T message,
GrpcLogEntry.Logger logger,
long callId) {
Preconditions.checkArgument(
eventType == EventType.EVENT_TYPE_CLIENT_MESSAGE
|| eventType == EventType.EVENT_TYPE_SERVER_MESSAGE,
"event type must correspond to client message or server message");
if (marshaller != BYTEARRAY_MARSHALLER) {
throw new IllegalStateException("Expected the BinaryLog's ByteArrayMarshaller");
}
MaybeTruncated<Message.Builder> pair = createMessageProto((byte[]) message, maxMessageBytes);
GrpcLogEntry.Builder entryBuilder = newTimestampedBuilder()
.setSequenceIdWithinCall(seq)
.setType(eventType)
.setMessage(pair.proto)
.setPayloadTruncated(pair.truncated)
.setLogger(logger)
.setCallId(callId);
sink.write(entryBuilder.build());
}
@Override
<T> void logRpcMessage(
long seq,
EventType eventType,
Marshaller<T> marshaller,
T message,
GrpcLogEntry.Logger logger,
long callId) {
Preconditions.checkArgument(
eventType == EventType.EVENT_TYPE_CLIENT_MESSAGE
|| eventType == EventType.EVENT_TYPE_SERVER_MESSAGE,
"event type must correspond to client message or server message");
if (marshaller != BYTEARRAY_MARSHALLER) {
throw new IllegalStateException("Expected the BinaryLog's ByteArrayMarshaller");
}
MaybeTruncated<Message.Builder> pair = createMessageProto((byte[]) message, maxMessageBytes);
GrpcLogEntry.Builder entryBuilder = newTimestampedBuilder()
.setSequenceIdWithinCall(seq)
.setType(eventType)
.setMessage(pair.proto)
.setPayloadTruncated(pair.truncated)
.setLogger(logger)
.setCallId(callId);
sink.write(entryBuilder.build());
}
@Test
public void testMismatch() throws Exception {
Marshaller<Enum> enumMarshaller = ProtoLiteUtils.marshaller(Enum.getDefaultInstance());
// Enum's name and Type's name are both strings with tag 1.
Enum altProto = Enum.newBuilder().setName(proto.getName()).build();
assertEquals(proto, marshaller.parse(enumMarshaller.stream(altProto)));
}
@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());
}
@Test
public void testEmpty() throws IOException {
Marshaller<Empty> marshaller = ProtoLiteUtils.marshaller(Empty.getDefaultInstance());
InputStream is = marshaller.stream(Empty.getDefaultInstance());
assertEquals(0, is.available());
byte[] b = new byte[10];
assertEquals(-1, is.read(b));
assertArrayEquals(new byte[10], b);
// Do the same thing again, because the internal state may be different
assertEquals(-1, is.read(b));
assertArrayEquals(new byte[10], b);
assertEquals(-1, is.read());
assertEquals(0, is.available());
}
@Test
public void parseFromKnowLengthInputStream() throws Exception {
Marshaller<Type> marshaller = ProtoLiteUtils.marshaller(Type.getDefaultInstance());
Type expect = Type.newBuilder().setName("expected name").build();
Type result = marshaller.parse(new CustomKnownLengthInputStream(expect.toByteArray()));
assertEquals(expect, result);
}
/**
* Logs the message message. The number of bytes logged is determined by the binary
* logging configuration.
*/
abstract <T> void logRpcMessage(
long seq,
EventType eventType,
Marshaller<T> marshaller,
T message,
GrpcLogEntry.Logger logger,
long callId);
@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 getServiceName_extractsService() {
Marshaller<Void> marshaller = TestMethodDescriptors.voidMarshaller();
MethodDescriptor<?, ?> md = MethodDescriptor.newBuilder(marshaller, marshaller)
.setType(MethodType.UNARY)
.setFullMethodName("foo/bar")
.build();
assertEquals("foo", md.getServiceName());
}
@Test
public void getServiceName_returnsNull() {
Marshaller<Void> marshaller = TestMethodDescriptors.voidMarshaller();
MethodDescriptor<?, ?> md = MethodDescriptor.newBuilder(marshaller, marshaller)
.setType(MethodType.UNARY)
.setFullMethodName("foo-bar")
.build();
assertNull(md.getServiceName());
}
@Test
public void testMismatch() throws Exception {
Marshaller<Enum> enumMarshaller = ProtoLiteUtils.marshaller(Enum.getDefaultInstance());
// Enum's name and Type's name are both strings with tag 1.
Enum altProto = Enum.newBuilder().setName(proto.getName()).build();
assertEquals(proto, marshaller.parse(enumMarshaller.stream(altProto)));
}
@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());
}
@Test
public void testEmpty() throws IOException {
Marshaller<Empty> marshaller = ProtoLiteUtils.marshaller(Empty.getDefaultInstance());
InputStream is = marshaller.stream(Empty.getDefaultInstance());
assertEquals(0, is.available());
byte[] b = new byte[10];
assertEquals(-1, is.read(b));
assertArrayEquals(new byte[10], b);
// Do the same thing again, because the internal state may be different
assertEquals(-1, is.read(b));
assertArrayEquals(new byte[10], b);
assertEquals(-1, is.read());
assertEquals(0, is.available());
}
@Test
public void parseFromKnowLengthInputStream() throws Exception {
Marshaller<Type> marshaller = ProtoLiteUtils.marshaller(Type.getDefaultInstance());
Type expect = Type.newBuilder().setName("expected name").build();
Type result = marshaller.parse(new CustomKnownLengthInputStream(expect.toByteArray()));
assertEquals(expect, result);
}
/**
* Logs the message message. The number of bytes logged is determined by the binary
* logging configuration.
*/
abstract <T> void logRpcMessage(
long seq,
EventType eventType,
Marshaller<T> marshaller,
T message,
GrpcLogEntry.Logger logger,
long callId);
/**
* Create a {@code Marshaller} for json protos of the same type as {@code defaultInstance}.
*
* <p>This is an unstable API and has not been optimized yet for performance.
*/
public static <T extends Message> Marshaller<T> jsonMarshaller(final T defaultInstance) {
final Parser parser = JsonFormat.parser();
final Printer printer = JsonFormat.printer();
return jsonMarshaller(defaultInstance, parser, printer);
}
@Override
Marshaller<String> delegate() {
return StringMarshaller.INSTANCE;
}
@Override
Marshaller<Integer> delegate() {
return IntegerMarshaller.INSTANCE;
}
public static <ReqT, RespT> ClientInterceptor wrapClientInterceptor(
final ClientInterceptor interceptor,
final Marshaller<ReqT> reqMarshaller,
final Marshaller<RespT> respMarshaller) {
return ClientInterceptors.wrapClientInterceptor(interceptor, reqMarshaller, respMarshaller);
}
@Override
public <T> void serializeMessage(Marshaller<T> marshaller, T message, OutputStream os) throws IOException {
delegate.writeValue((Message) message, os);
}
private static MessageType marshallerType(Marshaller<?> marshaller) {
return marshaller instanceof PrototypeMarshaller ? MessageType.PROTOBUF : MessageType.UNKNOWN;
}
/**
* Create a {@code Marshaller} for json protos of the same type as {@code defaultInstance}.
*
* <p>This is an unstable API and has not been optimized yet for performance.
*/
public static <T extends Message> Marshaller<T> jsonMarshaller(final T defaultInstance) {
final Parser parser = JsonFormat.parser();
final Printer printer = JsonFormat.printer();
return jsonMarshaller(defaultInstance, parser, printer);
}
public static <ReqT, RespT> ClientInterceptor wrapClientInterceptor(
final ClientInterceptor interceptor,
final Marshaller<ReqT> reqMarshaller,
final Marshaller<RespT> respMarshaller) {
return ClientInterceptors.wrapClientInterceptor(interceptor, reqMarshaller, respMarshaller);
}
@Override
Marshaller<String> delegate() {
return StringMarshaller.INSTANCE;
}
@Override
Marshaller<Integer> delegate() {
return IntegerMarshaller.INSTANCE;
}
/**
* Create a {@link Marshaller} for protos of the same type as {@code defaultInstance}.
*
* @since 1.0.0
*/
public static <T extends Message> Marshaller<T> marshaller(final T defaultInstance) {
return ProtoLiteUtils.marshaller(defaultInstance);
}
/**
* Creates a {@link Marshaller} for protos of the same type as {@code defaultInstance}.
*
* @since 1.0.0
*/
public static <T extends MessageLite> Marshaller<T> marshaller(T defaultInstance) {
// TODO(ejona): consider changing return type to PrototypeMarshaller (assuming ABI safe)
return new MessageMarshaller<T>(defaultInstance);
}
/**
* Adapt {@code parser} to a {@link Marshaller}.
*
* @since 1.0.0
*/
public static <T extends MessageNano> Marshaller<T> marshaller(MessageNanoFactory<T> factory) {
return new MessageMarshaller<T>(factory);
}
/**
* Serializes a gRPC message into JSON.
*/
<T> void serializeMessage(Marshaller<T> marshaller, T message, OutputStream os) throws IOException;