Search in sources :

Example 6 with Listener

use of io.grpc.ServerCall.Listener in project grpc-java by grpc.

the class ServerInterceptorsTest method typedMarshalledMessages.

@Test
@SuppressWarnings("unchecked")
public void typedMarshalledMessages() {
    final List<String> order = new ArrayList<>();
    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<>();
    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.internal.NoopServerCall) NoopServerCall(io.grpc.internal.NoopServerCall) Marshaller(io.grpc.MethodDescriptor.Marshaller) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) Test(org.junit.Test)

Example 7 with Listener

use of io.grpc.ServerCall.Listener in project grpc-java by grpc.

the class CompressingHelloWorldServerAllMethods method start.

private void start() throws IOException {
    /* The port on which the server should run */
    int port = 50051;
    server = ServerBuilder.forPort(port).intercept(new ServerInterceptor() {

        @Override
        public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
            call.setCompression("gzip");
            return next.startCall(call, headers);
        }
    }).addService(new GreeterImpl()).build().start();
    logger.info("Server started, listening on " + port);
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            // Use stderr here since the logger may have been reset by its JVM shutdown hook.
            System.err.println("*** shutting down gRPC server since JVM is shutting down");
            try {
                CompressingHelloWorldServerAllMethods.this.stop();
            } catch (InterruptedException e) {
                e.printStackTrace(System.err);
            }
            System.err.println("*** server shut down");
        }
    });
}
Also used : Listener(io.grpc.ServerCall.Listener) ServerInterceptor(io.grpc.ServerInterceptor) Metadata(io.grpc.Metadata)

Example 8 with Listener

use of io.grpc.ServerCall.Listener in project grpc-java by grpc.

the class HandlerRegistryBenchmark method setup.

/**
   * Set up the registry.
   */
@Setup(Level.Trial)
public void setup() throws Exception {
    registry = new MutableHandlerRegistry();
    fullMethodNames = new ArrayList<String>(serviceCount * methodCountPerService);
    for (int serviceIndex = 0; serviceIndex < serviceCount; ++serviceIndex) {
        String serviceName = randomString();
        ServerServiceDefinition.Builder serviceBuilder = ServerServiceDefinition.builder(new ServiceDescriptor(serviceName));
        for (int methodIndex = 0; methodIndex < methodCountPerService; ++methodIndex) {
            String methodName = randomString();
            MethodDescriptor<Void, Void> methodDescriptor = MethodDescriptor.<Void, Void>newBuilder().setType(MethodDescriptor.MethodType.UNKNOWN).setFullMethodName(MethodDescriptor.generateFullMethodName(serviceName, methodName)).setRequestMarshaller(TestMethodDescriptors.voidMarshaller()).setResponseMarshaller(TestMethodDescriptors.voidMarshaller()).build();
            serviceBuilder.addMethod(methodDescriptor, new ServerCallHandler<Void, Void>() {

                @Override
                public Listener<Void> startCall(ServerCall<Void, Void> call, Metadata headers) {
                    return null;
                }
            });
            fullMethodNames.add(methodDescriptor.getFullMethodName());
        }
        registry.addService(serviceBuilder.build());
    }
}
Also used : Listener(io.grpc.ServerCall.Listener) MutableHandlerRegistry(io.grpc.util.MutableHandlerRegistry) Metadata(io.grpc.Metadata) ServiceDescriptor(io.grpc.ServiceDescriptor) ServerServiceDefinition(io.grpc.ServerServiceDefinition) Setup(org.openjdk.jmh.annotations.Setup)

Example 9 with Listener

use of io.grpc.ServerCall.Listener in project grpc-java by grpc.

the class TransportCompressionTest method createChannelBuilder.

@Override
protected NettyChannelBuilder createChannelBuilder() {
    NettyChannelBuilder builder = NettyChannelBuilder.forAddress(getListenAddress()).maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE).decompressorRegistry(decompressors).compressorRegistry(compressors).intercept(new ClientInterceptor() {

        @Override
        public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
            final ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);
            return new ForwardingClientCall<ReqT, RespT>() {

                @Override
                protected ClientCall<ReqT, RespT> delegate() {
                    return call;
                }

                @Override
                public void start(final ClientCall.Listener<RespT> responseListener, Metadata headers) {
                    ClientCall.Listener<RespT> listener = new ForwardingClientCallListener<RespT>() {

                        @Override
                        protected io.grpc.ClientCall.Listener<RespT> delegate() {
                            return responseListener;
                        }

                        @Override
                        public void onHeaders(Metadata headers) {
                            super.onHeaders(headers);
                            if (expectFzip) {
                                String encoding = headers.get(GrpcUtil.MESSAGE_ENCODING_KEY);
                                assertEquals(encoding, FZIPPER.getMessageEncoding());
                            }
                        }
                    };
                    super.start(listener, headers);
                    setMessageCompression(true);
                }
            };
        }
    }).usePlaintext();
    // Disable the default census stats interceptor, use testing interceptor instead.
    InternalNettyChannelBuilder.setStatsEnabled(builder, false);
    return builder.intercept(createCensusStatsClientInterceptor());
}
Also used : ForwardingClientCallListener(io.grpc.ForwardingClientCallListener) Listener(io.grpc.ServerCall.Listener) Channel(io.grpc.Channel) ForwardingClientCall(io.grpc.ForwardingClientCall) Metadata(io.grpc.Metadata) CallOptions(io.grpc.CallOptions) ByteString(com.google.protobuf.ByteString) MethodDescriptor(io.grpc.MethodDescriptor) ClientCall(io.grpc.ClientCall) ForwardingClientCall(io.grpc.ForwardingClientCall) ClientInterceptor(io.grpc.ClientInterceptor) InternalNettyChannelBuilder(io.grpc.netty.InternalNettyChannelBuilder) NettyChannelBuilder(io.grpc.netty.NettyChannelBuilder) ForwardingClientCallListener(io.grpc.ForwardingClientCallListener)

Example 10 with Listener

use of io.grpc.ServerCall.Listener in project grpc-java by grpc.

the class ServerImplTest method testCallContextIsBoundInListenerCallbacks.

@Test
public void testCallContextIsBoundInListenerCallbacks() throws Exception {
    createAndStartServer();
    final AtomicBoolean onReadyCalled = new AtomicBoolean(false);
    final AtomicBoolean onMessageCalled = new AtomicBoolean(false);
    final AtomicBoolean onHalfCloseCalled = new AtomicBoolean(false);
    final AtomicBoolean onCancelCalled = new AtomicBoolean(false);
    mutableFallbackRegistry.addService(ServerServiceDefinition.builder(new ServiceDescriptor("Waiter", METHOD)).addMethod(METHOD, new ServerCallHandler<String, Integer>() {

        @Override
        public ServerCall.Listener<String> startCall(ServerCall<String, Integer> call, Metadata headers) {
            // Check that the current context is a descendant of SERVER_CONTEXT
            final Context initial = Context.current();
            assertEquals("yes", SERVER_ONLY.get(initial));
            assertNotSame(SERVER_CONTEXT, initial);
            assertFalse(initial.isCancelled());
            return new ServerCall.Listener<String>() {

                @Override
                public void onReady() {
                    checkContext();
                    onReadyCalled.set(true);
                }

                @Override
                public void onMessage(String message) {
                    checkContext();
                    onMessageCalled.set(true);
                }

                @Override
                public void onHalfClose() {
                    checkContext();
                    onHalfCloseCalled.set(true);
                }

                @Override
                public void onCancel() {
                    checkContext();
                    onCancelCalled.set(true);
                }

                @Override
                public void onComplete() {
                    checkContext();
                }

                private void checkContext() {
                    // Check that the bound context is the same as the initial one.
                    assertSame(initial, Context.current());
                }
            };
        }
    }).build());
    ServerTransportListener transportListener = transportServer.registerNewServerTransport(new SimpleServerTransport());
    transportListener.transportReady(Attributes.EMPTY);
    Metadata requestHeaders = new Metadata();
    StatsTraceContext statsTraceCtx = StatsTraceContext.newServerContext(streamTracerFactories, "Waitier/serve", requestHeaders);
    when(stream.statsTraceContext()).thenReturn(statsTraceCtx);
    transportListener.streamCreated(stream, "Waiter/serve", requestHeaders);
    verify(stream).setListener(streamListenerCaptor.capture());
    ServerStreamListener streamListener = streamListenerCaptor.getValue();
    assertNotNull(streamListener);
    streamListener.onReady();
    assertEquals(1, executor.runDueTasks());
    assertTrue(onReadyCalled.get());
    streamListener.messagesAvailable(new SingleMessageProducer(new ByteArrayInputStream(new byte[0])));
    assertEquals(1, executor.runDueTasks());
    assertTrue(onMessageCalled.get());
    streamListener.halfClosed();
    assertEquals(1, executor.runDueTasks());
    assertTrue(onHalfCloseCalled.get());
    streamListener.closed(Status.CANCELLED);
    assertEquals(1, executor.numPendingTasks(CONTEXT_CLOSER_TASK_FITLER));
    assertEquals(2, executor.runDueTasks());
    assertTrue(onCancelCalled.get());
    // Close should never be called if asserts in listener pass.
    verify(stream, times(0)).close(isA(Status.class), ArgumentMatchers.<Metadata>isNotNull());
}
Also used : Context(io.grpc.Context) Status(io.grpc.Status) JumpToApplicationThreadServerStreamListener(io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener) Listener(io.grpc.ServerCall.Listener) Metadata(io.grpc.Metadata) SingleMessageProducer(io.grpc.internal.testing.SingleMessageProducer) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServiceDescriptor(io.grpc.ServiceDescriptor) ServerCall(io.grpc.ServerCall) ByteArrayInputStream(java.io.ByteArrayInputStream) JumpToApplicationThreadServerStreamListener(io.grpc.internal.ServerImpl.JumpToApplicationThreadServerStreamListener) Test(org.junit.Test)

Aggregations

Listener (io.grpc.ServerCall.Listener)10 Metadata (io.grpc.Metadata)8 ForwardingClientCallListener (io.grpc.ForwardingClientCallListener)4 ServerInterceptor (io.grpc.ServerInterceptor)3 ByteString (com.google.protobuf.ByteString)2 DefaultRequest (com.weibo.api.motan.rpc.DefaultRequest)2 Response (com.weibo.api.motan.rpc.Response)2 CallOptions (io.grpc.CallOptions)2 Channel (io.grpc.Channel)2 ClientCall (io.grpc.ClientCall)2 ClientInterceptor (io.grpc.ClientInterceptor)2 ForwardingClientCall (io.grpc.ForwardingClientCall)2 MethodDescriptor (io.grpc.MethodDescriptor)2 ServiceDescriptor (io.grpc.ServiceDescriptor)2 NettyChannelBuilder (io.grpc.netty.NettyChannelBuilder)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 Test (org.junit.Test)2 MotanBizException (com.weibo.api.motan.exception.MotanBizException)1 MotanFrameworkException (com.weibo.api.motan.exception.MotanFrameworkException)1 Context (io.grpc.Context)1