|
17 | 17 | package io.grpc; |
18 | 18 |
|
19 | 19 | import com.google.common.base.Preconditions; |
| 20 | +import io.grpc.MethodDescriptor.Marshaller; |
| 21 | +import java.io.InputStream; |
20 | 22 | import java.util.ArrayList; |
21 | 23 | import java.util.Arrays; |
22 | 24 | import java.util.Collections; |
@@ -89,6 +91,56 @@ public static Channel intercept(Channel channel, List<? extends ClientIntercepto |
89 | 91 | return channel; |
90 | 92 | } |
91 | 93 |
|
| 94 | + /** |
| 95 | + * Creates a new ClientInterceptor that transforms requests into {@code WReqT} and responses into |
| 96 | + * {@code WRespT} before passing them into the {@code interceptor}. |
| 97 | + */ |
| 98 | + static <WReqT, WRespT> ClientInterceptor wrapClientInterceptor( |
| 99 | + final ClientInterceptor interceptor, |
| 100 | + final Marshaller<WReqT> reqMarshaller, |
| 101 | + final Marshaller<WRespT> respMarshaller) { |
| 102 | + return new ClientInterceptor() { |
| 103 | + @Override |
| 104 | + public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( |
| 105 | + final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { |
| 106 | + final MethodDescriptor<WReqT, WRespT> wrappedMethod = |
| 107 | + method.toBuilder(reqMarshaller, respMarshaller).build(); |
| 108 | + final ClientCall<WReqT, WRespT> wrappedCall = |
| 109 | + interceptor.interceptCall(wrappedMethod, callOptions, next); |
| 110 | + return new PartialForwardingClientCall<ReqT, RespT>() { |
| 111 | + @Override |
| 112 | + public void start(final Listener<RespT> responseListener, Metadata headers) { |
| 113 | + wrappedCall.start(new PartialForwardingClientCallListener<WRespT>() { |
| 114 | + @Override |
| 115 | + public void onMessage(WRespT wMessage) { |
| 116 | + InputStream bytes = respMarshaller.stream(wMessage); |
| 117 | + RespT message = method.getResponseMarshaller().parse(bytes); |
| 118 | + responseListener.onMessage(message); |
| 119 | + } |
| 120 | + |
| 121 | + @Override |
| 122 | + protected Listener<?> delegate() { |
| 123 | + return responseListener; |
| 124 | + } |
| 125 | + }, headers); |
| 126 | + } |
| 127 | + |
| 128 | + @Override |
| 129 | + public void sendMessage(ReqT message) { |
| 130 | + InputStream bytes = method.getRequestMarshaller().stream(message); |
| 131 | + WReqT wReq = reqMarshaller.parse(bytes); |
| 132 | + wrappedCall.sendMessage(wReq); |
| 133 | + } |
| 134 | + |
| 135 | + @Override |
| 136 | + protected ClientCall<?, ?> delegate() { |
| 137 | + return wrappedCall; |
| 138 | + } |
| 139 | + }; |
| 140 | + } |
| 141 | + }; |
| 142 | + } |
| 143 | + |
92 | 144 | private static class InterceptorChannel extends Channel { |
93 | 145 | private final Channel channel; |
94 | 146 | private final ClientInterceptor interceptor; |
|
0 commit comments