Search in sources :

Example 1 with Marshaller

use of io.grpc.MethodDescriptor.Marshaller in project grpc-java by grpc.

the class ServerInterceptorsTest method typedMarshalledMessages.

@Test
@SuppressWarnings("unchecked")
public void typedMarshalledMessages() {
    final List<String> order = new ArrayList<String>();
    Marshaller<Holder> marshaller = new Marshaller<Holder>() {

        @Override
        public InputStream stream(Holder value) {
            return value.get();
        }

        @Override
        public Holder parse(InputStream stream) {
            return new Holder(stream);
        }
    };
    ServerCallHandler<Holder, Holder> handler2 = new ServerCallHandler<Holder, Holder>() {

        @Override
        public Listener<Holder> startCall(final ServerCall<Holder, Holder> call, final Metadata headers) {
            return new Listener<Holder>() {

                @Override
                public void onMessage(Holder message) {
                    order.add("handler");
                    call.sendMessage(message);
                }
            };
        }
    };
    MethodDescriptor<Holder, Holder> wrappedMethod = MethodDescriptor.<Holder, Holder>newBuilder().setType(MethodType.UNKNOWN).setFullMethodName("basic/wrapped").setRequestMarshaller(marshaller).setResponseMarshaller(marshaller).build();
    ServerServiceDefinition serviceDef = ServerServiceDefinition.builder(new ServiceDescriptor("basic", wrappedMethod)).addMethod(wrappedMethod, handler2).build();
    ServerInterceptor interceptor1 = new ServerInterceptor() {

        @Override
        public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            ServerCall<ReqT, RespT> interceptedCall = new ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) {

                @Override
                public void sendMessage(RespT message) {
                    order.add("i1sendMessage");
                    assertTrue(message instanceof Holder);
                    super.sendMessage(message);
                }
            };
            ServerCall.Listener<ReqT> originalListener = next.startCall(interceptedCall, headers);
            return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(originalListener) {

                @Override
                public void onMessage(ReqT message) {
                    order.add("i1onMessage");
                    assertTrue(message instanceof Holder);
                    super.onMessage(message);
                }
            };
        }
    };
    ServerInterceptor interceptor2 = new ServerInterceptor() {

        @Override
        public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            ServerCall<ReqT, RespT> interceptedCall = new ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) {

                @Override
                public void sendMessage(RespT message) {
                    order.add("i2sendMessage");
                    assertTrue(message instanceof InputStream);
                    super.sendMessage(message);
                }
            };
            ServerCall.Listener<ReqT> originalListener = next.startCall(interceptedCall, headers);
            return new ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT>(originalListener) {

                @Override
                public void onMessage(ReqT message) {
                    order.add("i2onMessage");
                    assertTrue(message instanceof InputStream);
                    super.onMessage(message);
                }
            };
        }
    };
    ServerServiceDefinition intercepted = ServerInterceptors.intercept(serviceDef, interceptor1);
    ServerServiceDefinition inputStreamMessageService = ServerInterceptors.useInputStreamMessages(intercepted);
    ServerServiceDefinition intercepted2 = ServerInterceptors.intercept(inputStreamMessageService, interceptor2);
    ServerMethodDefinition<InputStream, InputStream> serverMethod = (ServerMethodDefinition<InputStream, InputStream>) intercepted2.getMethod("basic/wrapped");
    ServerCall<InputStream, InputStream> call2 = new NoopServerCall<InputStream, InputStream>();
    byte[] bytes = {};
    serverMethod.getServerCallHandler().startCall(call2, headers).onMessage(new ByteArrayInputStream(bytes));
    assertEquals(Arrays.asList("i2onMessage", "i1onMessage", "handler", "i1sendMessage", "i2sendMessage"), order);
}
Also used : Listener(io.grpc.ServerCall.Listener) ArrayList(java.util.ArrayList) NoopServerCall(io.grpc.testing.NoopServerCall) NoopServerCall(io.grpc.testing.NoopServerCall) Marshaller(io.grpc.MethodDescriptor.Marshaller) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) Test(org.junit.Test)

Example 2 with Marshaller

use of io.grpc.MethodDescriptor.Marshaller in project grpc-java by grpc.

the class ThriftUtils method marshaller.

/** Create a {@code Marshaller} for thrift messages. */
public static <T extends TBase<T, ?>> Marshaller<T> marshaller(final MessageFactory<T> factory) {
    return new Marshaller<T>() {

        @Override
        public InputStream stream(T value) {
            return new ThriftInputStream(value);
        }

        @Override
        public T parse(InputStream stream) {
            try {
                byte[] bytes = IoUtils.toByteArray(stream);
                TDeserializer deserializer = new TDeserializer();
                T message = factory.newInstance();
                deserializer.deserialize(message, bytes);
                return message;
            } catch (TException e) {
                throw Status.INTERNAL.withDescription("Invalid Stream").withCause(e).asRuntimeException();
            } catch (IOException e) {
                throw Status.INTERNAL.withDescription("failed to read stream").withCause(e).asRuntimeException();
            }
        }
    };
}
Also used : TException(org.apache.thrift.TException) Marshaller(io.grpc.MethodDescriptor.Marshaller) TDeserializer(org.apache.thrift.TDeserializer) InputStream(java.io.InputStream) IOException(java.io.IOException)

Example 3 with Marshaller

use of io.grpc.MethodDescriptor.Marshaller in project grpc-java by grpc.

the class NanoUtils method marshaller.

/** Adapt {@code parser} to a {@code Marshaller}. */
public static <T extends MessageNano> Marshaller<T> marshaller(final MessageNanoFactory<T> factory) {
    return new Marshaller<T>() {

        @Override
        public InputStream stream(T value) {
            return new NanoProtoInputStream(value);
        }

        @Override
        public T parse(InputStream stream) {
            try {
                // TODO(simonma): Investigate whether we can do 0-copy here. 
                CodedInputByteBufferNano input = CodedInputByteBufferNano.newInstance(ByteStreams.toByteArray(stream));
                input.setSizeLimit(Integer.MAX_VALUE);
                T message = factory.newInstance();
                message.mergeFrom(input);
                return message;
            } catch (IOException ipbe) {
                throw Status.INTERNAL.withDescription("Failed parsing nano proto message").withCause(ipbe).asRuntimeException();
            }
        }
    };
}
Also used : Marshaller(io.grpc.MethodDescriptor.Marshaller) InputStream(java.io.InputStream) CodedInputByteBufferNano(com.google.protobuf.nano.CodedInputByteBufferNano) IOException(java.io.IOException)

Example 4 with Marshaller

use of io.grpc.MethodDescriptor.Marshaller in project grpc-java by grpc.

the class ProtoUtils method jsonMarshaller.

/**
   * 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.
   */
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1786")
public static <T extends Message> Marshaller<T> jsonMarshaller(final T defaultInstance, final Parser parser, final Printer printer) {
    final Charset charset = Charset.forName("UTF-8");
    return new Marshaller<T>() {

        @Override
        public InputStream stream(T value) {
            try {
                return new ByteArrayInputStream(printer.print(value).getBytes(charset));
            } catch (InvalidProtocolBufferException e) {
                throw Status.INTERNAL.withCause(e).withDescription("Unable to print json proto").asRuntimeException();
            }
        }

        @SuppressWarnings("unchecked")
        @Override
        public T parse(InputStream stream) {
            Builder builder = defaultInstance.newBuilderForType();
            Reader reader = new InputStreamReader(stream, charset);
            T proto;
            try {
                parser.merge(reader, builder);
                proto = (T) builder.build();
                reader.close();
            } catch (InvalidProtocolBufferException e) {
                throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence").withCause(e).asRuntimeException();
            } catch (IOException e) {
                // Same for now, might be unavailable
                throw Status.INTERNAL.withDescription("Invalid protobuf byte sequence").withCause(e).asRuntimeException();
            }
            return proto;
        }
    };
}
Also used : Marshaller(io.grpc.MethodDescriptor.Marshaller) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Builder(com.google.protobuf.Message.Builder) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) Charset(java.nio.charset.Charset) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) ExperimentalApi(io.grpc.ExperimentalApi)

Aggregations

Marshaller (io.grpc.MethodDescriptor.Marshaller)4 InputStream (java.io.InputStream)4 IOException (java.io.IOException)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)1 Builder (com.google.protobuf.Message.Builder)1 CodedInputByteBufferNano (com.google.protobuf.nano.CodedInputByteBufferNano)1 ExperimentalApi (io.grpc.ExperimentalApi)1 Listener (io.grpc.ServerCall.Listener)1 NoopServerCall (io.grpc.testing.NoopServerCall)1 InputStreamReader (java.io.InputStreamReader)1 Reader (java.io.Reader)1 Charset (java.nio.charset.Charset)1 ArrayList (java.util.ArrayList)1 TDeserializer (org.apache.thrift.TDeserializer)1 TException (org.apache.thrift.TException)1 Test (org.junit.Test)1