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);
}
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");
}
});
}
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());
}
}
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());
}
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());
}
Aggregations