io.grpc.Channel Java Examples
The following examples show how to use
io.grpc.Channel.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ByteStreamServiceTest.java From bazel-buildfarm with Apache License 2.0 | 6 votes |
@Test public void missingBlobReadIsNotFound() { ByteString helloWorld = ByteString.copyFromUtf8("Hello, World!"); Digest digest = DIGEST_UTIL.compute(helloWorld); Channel channel = InProcessChannelBuilder.forName(fakeServerName).directExecutor().build(); ByteStreamBlockingStub service = ByteStreamGrpc.newBlockingStub(channel); when(simpleBlobStore.get(eq(digest.getHash()), any(OutputStream.class))) .thenReturn(immediateFuture(false)); ReadRequest request = ReadRequest.newBuilder().setResourceName(createBlobDownloadResourceName(digest)).build(); StatusRuntimeException notFoundException = null; try { if (service.read(request).hasNext()) { fail("no responses should be available"); } } catch (StatusRuntimeException e) { assertThat(Status.fromThrowable(e).getCode()).isEqualTo(Code.NOT_FOUND); notFoundException = e; } assertThat(notFoundException).isNotNull(); }
Example #2
Source File: CensusStatsModule.java From grpc-java with Apache License 2.0 | 6 votes |
@Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { // New RPCs on client-side inherit the tag context from the current Context. TagContext parentCtx = tagger.getCurrentTagContext(); final ClientCallTracer tracerFactory = newClientCallTracer(parentCtx, method.getFullMethodName()); ClientCall<ReqT, RespT> call = next.newCall(method, callOptions.withStreamTracerFactory(tracerFactory)); return new SimpleForwardingClientCall<ReqT, RespT>(call) { @Override public void start(Listener<RespT> responseListener, Metadata headers) { delegate().start( new SimpleForwardingClientCallListener<RespT>(responseListener) { @Override public void onClose(Status status, Metadata trailers) { tracerFactory.callEnded(status); super.onClose(status, trailers); } }, headers); } }; }
Example #3
Source File: BookstoreClient.java From java-docs-samples with Apache License 2.0 | 6 votes |
@Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( MethodDescriptor<ReqT,RespT> method, CallOptions callOptions, Channel next) { LOGGER.info("Intercepted " + method.getFullMethodName()); ClientCall<ReqT, RespT> call = next.newCall(method, callOptions); call = new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(call) { @Override public void start(Listener<RespT> responseListener, Metadata headers) { if (apiKey != null && !apiKey.isEmpty()) { LOGGER.info("Attaching API Key: " + apiKey); headers.put(API_KEY_HEADER, apiKey); } if (authToken != null && !authToken.isEmpty()) { System.out.println("Attaching auth token"); headers.put(AUTHORIZATION_HEADER, "Bearer " + authToken); } super.start(responseListener, headers); } }; return call; }
Example #4
Source File: GRPCChannel.java From skywalking with Apache License 2.0 | 6 votes |
private GRPCChannel(String host, int port, List<ChannelBuilder> channelBuilders, List<ChannelDecorator> decorators) throws Exception { ManagedChannelBuilder channelBuilder = NettyChannelBuilder.forAddress(host, port); for (ChannelBuilder builder : channelBuilders) { channelBuilder = builder.build(channelBuilder); } this.originChannel = channelBuilder.build(); Channel channel = originChannel; for (ChannelDecorator decorator : decorators) { channel = decorator.build(channel); } channelWithDecorators = channel; }
Example #5
Source File: HeaderServerInterceptorTest.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
@Test public void serverHeaderDeliveredToClient() { class SpyingClientInterceptor implements ClientInterceptor { ClientCall.Listener<?> spyListener; @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) { @Override public void start(Listener<RespT> responseListener, Metadata headers) { spyListener = responseListener = mock(ClientCall.Listener.class, delegatesTo(responseListener)); super.start(responseListener, headers); } }; } } SpyingClientInterceptor clientInterceptor = new SpyingClientInterceptor(); GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(channel) .withInterceptors(clientInterceptor); ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class); blockingStub.sayHello(HelloRequest.getDefaultInstance()); assertNotNull(clientInterceptor.spyListener); verify(clientInterceptor.spyListener).onHeaders(metadataCaptor.capture()); assertEquals( "customRespondValue", metadataCaptor.getValue().get(HeaderServerInterceptor.CUSTOM_HEADER_KEY)); }
Example #6
Source File: ChannelFactory.java From grpc-swagger with MIT License | 6 votes |
private static ClientInterceptor metadataInterceptor(Map<String, Object> metaDataMap) { return new ClientInterceptor() { @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, final Channel next) { return new CheckedForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) { @Override protected void checkedStart(Listener<RespT> responseListener, Metadata headers) { metaDataMap.forEach((k, v) -> { Key<String> mKey = Key.of(k, ASCII_STRING_MARSHALLER); headers.put(mKey, String.valueOf(v)); }); delegate().start(responseListener, headers); } }; } }; }
Example #7
Source File: ClientRandomStubTest.java From dgraph4j with Apache License 2.0 | 6 votes |
@Test public void testClientRandomStubTest() throws IllegalAccessException { int NUM_ITER = 1000; HashMap<String, Integer> counts = new HashMap<>(); for (int i = 0; i < NUM_ITER; i++) { Transaction txn = dgraphClient.newTransaction(); Channel channel = (Channel) channelField.get(stubField.get(asyncTransactionField.get(txn))); String endpoint = channel.authority(); counts.put(endpoint, counts.getOrDefault(endpoint, 0) + 1); } // Ensure that we got all the clients assertEquals(counts.size(), 3); int sum = 0; for (Map.Entry<String, Integer> ep : counts.entrySet()) { assertTrue(ep.getValue() > 300); sum += ep.getValue(); } assertEquals(sum, NUM_ITER); }
Example #8
Source File: GrpcWorker.java From pampas with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { GrpcWorker worker = new GrpcWorker(); //"test.proto" // String protilFileName = "test.proto"; // ProtoFile protoFile = worker.parserProtoFile(protilFileName); // // "/v1/example/hello" // worker.listProtoServiceInProtoFile(protoFile); // GrpcServiceDefine grpcService = worker.findGrpcService("/v1/example/hello", "post"); // System.out.println("grpcService:" + grpcService); DynamicMultiClassLoader loader = DynamicMultiClassLoader.getLoader(URLTools.toUrl(Consts.JAVA_OUT_DIR)); Class grpc = loader.loadClass("df.open.grpc.hello.HelloServiceGrpc"); Class proto = loader.loadClass("df.open.grpc.hello.HelloServiceProto"); Method newBlockingStub = grpc.getMethod("newBlockingStub", Channel.class); System.out.println(newBlockingStub); AbstractStub stub = (AbstractStub) newBlockingStub.invoke(grpc, channel); System.out.println(stub); }
Example #9
Source File: SpeechService.java From android-docs-samples with Apache License 2.0 | 6 votes |
@Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, final Channel next) { return new ClientInterceptors.CheckedForwardingClientCall<ReqT, RespT>( next.newCall(method, callOptions)) { @Override protected void checkedStart(Listener<RespT> responseListener, Metadata headers) throws StatusException { Metadata cachedSaved; URI uri = serviceUri(next, method); synchronized (this) { Map<String, List<String>> latestMetadata = getRequestMetadata(uri); if (mLastMetadata == null || mLastMetadata != latestMetadata) { mLastMetadata = latestMetadata; mCached = toHeaders(mLastMetadata); } cachedSaved = mCached; } headers.merge(cachedSaved); delegate().start(responseListener, headers); } }; }
Example #10
Source File: BaseITTracingClientInterceptor.java From brave with Apache License 2.0 | 6 votes |
@Test public void userInterceptor_throwsOnHalfClose() { closeClient(client); client = newClient(new ClientInterceptor() { @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions, Channel channel) { ClientCall<ReqT, RespT> call = channel.newCall(methodDescriptor, callOptions); return new SimpleForwardingClientCall<ReqT, RespT>(call) { @Override public void halfClose() { throw new IllegalStateException("I'm a bad interceptor."); } }; } }, grpcTracing.newClientInterceptor()); assertThatThrownBy(() -> GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST)) .isInstanceOf(IllegalStateException.class); testSpanHandler.takeRemoteSpanWithErrorMessage(CLIENT, "I'm a bad interceptor."); }
Example #11
Source File: GrpcReflectionUtils.java From grpc-swagger with MIT License | 6 votes |
public static FileDescriptorSet resolveService(Channel channel, String serviceName) { ServerReflectionClient reflectionClient = ServerReflectionClient.create(channel); try { List<String> serviceNames = reflectionClient.listServices().get(); if (!serviceNames.contains(serviceName)) { throw Status.NOT_FOUND.withDescription( String.format("Remote server does not have service %s. Services: %s", serviceName, serviceNames)) .asRuntimeException(); } return reflectionClient.lookupService(serviceName).get(); } catch (InterruptedException | ExecutionException e) { logger.error("Resolve services get error", e); throw new RuntimeException(e); } }
Example #12
Source File: AltsProtocolNegotiator.java From grpc-java with Apache License 2.0 | 6 votes |
/** * Creates a protocol negotiator for ALTS on the server side. */ public static ProtocolNegotiator serverAltsProtocolNegotiator( ObjectPool<Channel> handshakerChannelPool) { final LazyChannel lazyHandshakerChannel = new LazyChannel(handshakerChannelPool); final class ServerTsiHandshakerFactory implements TsiHandshakerFactory { @Override public TsiHandshaker newHandshaker(@Nullable String authority) { assert authority == null; return AltsTsiHandshaker.newServer( HandshakerServiceGrpc.newStub(lazyHandshakerChannel.get()), new AltsHandshakerOptions(RpcProtocolVersionsUtil.getRpcProtocolVersions())); } } return new ServerAltsProtocolNegotiator( new ServerTsiHandshakerFactory(), lazyHandshakerChannel); }
Example #13
Source File: GrpcClient.java From rapid with Apache License 2.0 | 6 votes |
public GrpcClient(final Endpoint address, final SharedResources sharedResources, final ISettings settings) { this.address = address; this.settings = settings; this.grpcExecutor = sharedResources.getClientChannelExecutor(); this.backgroundExecutor = sharedResources.getBackgroundExecutor(); this.eventLoopGroup = settings.getUseInProcessTransport() ? null : sharedResources.getEventLoopGroup(); final RemovalListener<Endpoint, Channel> removalListener = removal -> shutdownChannel((ManagedChannel) removal.getValue()); this.channelMap = CacheBuilder.newBuilder() .expireAfterAccess(30, TimeUnit.SECONDS) .removalListener(removalListener) .build(new CacheLoader<Endpoint, Channel>() { @Override public Channel load(final Endpoint endpoint) { return getChannel(endpoint); } }); }
Example #14
Source File: GrpcClient.java From sofa-jraft with Apache License 2.0 | 5 votes |
@Override public void invokeAsync(final Endpoint endpoint, final Object request, final InvokeContext ctx, final InvokeCallback callback, final long timeoutMs) { Requires.requireNonNull(endpoint, "endpoint"); Requires.requireNonNull(request, "request"); final Channel ch = getChannel(endpoint); final MethodDescriptor<Message, Message> method = getCallMethod(request); final CallOptions callOpts = CallOptions.DEFAULT.withDeadlineAfter(timeoutMs, TimeUnit.MILLISECONDS); final Executor executor = callback.executor() != null ? callback.executor() : DirectExecutor.INSTANCE; ClientCalls.asyncUnaryCall(ch.newCall(method, callOpts), (Message) request, new StreamObserver<Message>() { @Override public void onNext(final Message value) { executor.execute(() -> callback.complete(value, null)); } @Override public void onError(final Throwable throwable) { executor.execute(() -> callback.complete(null, throwable)); } @Override public void onCompleted() { // NO-OP } }); }
Example #15
Source File: BaseITTracingClientInterceptor.java From brave with Apache License 2.0 | 5 votes |
/** * NOTE: for this to work, the tracing interceptor must be last (so that it executes first) * * <p>Also notice that we are only making the current context available in the request side. */ @Test public void currentSpanVisibleToUserInterceptors() { closeClient(client); client = newClient( new ClientInterceptor() { @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) { @Override public void start(Listener<RespT> responseListener, Metadata headers) { tracing.tracer().currentSpanCustomizer().annotate("start"); super.start(responseListener, headers); } @Override public void sendMessage(ReqT message) { tracing.tracer().currentSpanCustomizer().annotate("sendMessage"); super.sendMessage(message); } }; } }, grpcTracing.newClientInterceptor() ); GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST); assertThat(testSpanHandler.takeRemoteSpan(CLIENT).annotations()) .extracting(Entry::getValue) .containsOnly("start", "sendMessage"); }
Example #16
Source File: ThrottlingBlockingClient.java From product-microgateway with Apache License 2.0 | 5 votes |
public ThrottlingBlockingClient(Channel channel, String token) { ThrottlingTestServiceGrpc.ThrottlingTestServiceBlockingStub stub = ThrottlingTestServiceGrpc.newBlockingStub(channel); //add metadata Metadata metadata = new Metadata(); metadata.put(Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), token); blockingStub = MetadataUtils.attachHeaders(stub,metadata); }
Example #17
Source File: ContentAddressableStorages.java From bazel-buildfarm with Apache License 2.0 | 5 votes |
public static ContentAddressableStorage createGrpcCAS(GrpcCASConfig config) { Channel channel = createChannel(config.getTarget()); ByteStreamUploader byteStreamUploader = new ByteStreamUploader("", channel, null, 300, NO_RETRIES); ListMultimap<Digest, Runnable> onExpirations = synchronizedListMultimap(MultimapBuilder.hashKeys().arrayListValues().build()); return new GrpcCAS(config.getInstanceName(), channel, byteStreamUploader, onExpirations); }
Example #18
Source File: LoggingInterceptor.java From bazel with Apache License 2.0 | 5 votes |
@Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { ClientCall<ReqT, RespT> call = next.newCall(method, callOptions); @SuppressWarnings("unchecked") // handler matches method, but that type is inexpressible LoggingHandler<ReqT, RespT> handler = selectHandler(method); if (handler != null) { return new LoggingForwardingCall<>(call, handler, method); } else { return call; } }
Example #19
Source File: GrpcChannelScope.java From micronaut-grpc with Apache License 2.0 | 5 votes |
@Override public <T> T get( BeanResolutionContext resolutionContext, BeanDefinition<T> beanDefinition, BeanIdentifier identifier, Provider<T> provider) { BeanResolutionContext.Segment segment = resolutionContext.getPath().currentSegment().orElseThrow(() -> new IllegalStateException("@GrpcChannel used in invalid location") ); Argument argument = segment.getArgument(); String value = argument.getAnnotationMetadata().getValue(GrpcChannel.class, String.class).orElse(null); if (StringUtils.isEmpty(value)) { throw new DependencyInjectionException(resolutionContext, argument, "No value specified to @GrpcChannel annotation"); } if (!Channel.class.isAssignableFrom(argument.getType())) { throw new DependencyInjectionException(resolutionContext, argument, "@GrpcChannel used on type that is not a Channel"); } if ("grpc-server".equalsIgnoreCase(value)) { return (T) applicationContext.getBean(ManagedChannel.class, Qualifiers.byName("grpc-server")); } if (!(provider instanceof ParametrizedProvider)) { throw new DependencyInjectionException(resolutionContext, argument, "GrpcChannelScope called with invalid bean provider"); } value = applicationContext.resolveRequiredPlaceholders(value); String finalValue = value; return (T) channels.computeIfAbsent(new ChannelKey(identifier, value), channelKey -> (ManagedChannel) ((ParametrizedProvider<T>) provider).get(finalValue) ); }
Example #20
Source File: AsyncClient.java From grpc-java with Apache License 2.0 | 5 votes |
private void warmup(SimpleRequest req, List<? extends Channel> channels) throws Exception { long endTime = System.nanoTime() + TimeUnit.SECONDS.toNanos(config.warmupDuration); doBenchmark(req, channels, endTime); // I don't know if this helps, but it doesn't hurt trying. We sometimes run warmups // of several minutes at full load and it would be nice to start the actual benchmark // with a clean heap. System.gc(); }
Example #21
Source File: OpenLoopClient.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
LoadGenerationWorker(Channel channel, SimpleRequest request, int targetQps, int duration) { stub = BenchmarkServiceGrpc.newStub(checkNotNull(channel, "channel")); this.request = checkNotNull(request, "request"); this.targetQps = targetQps; numRpcs = (long) targetQps * duration; rnd = new Random(); }
Example #22
Source File: AltsProtocolNegotiator.java From grpc-java with Apache License 2.0 | 5 votes |
/** * If channel is null, gets a channel from the channel pool, otherwise, returns the cached * channel. */ synchronized Channel get() { if (channel == null) { channel = channelPool.getObject(); } return channel; }
Example #23
Source File: Jdk8GeneratorStructureTest.java From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void GeneratedClassHasCompletableFutureStubMethod() throws Exception { Class<?> clazz = Class.forName("com.salesforce.jprotoc.GreeterGrpc8"); Method stubMethod = clazz.getMethod("newCompletableFutureStub", Channel.class); assertNotNull(stubMethod); assertTrue(Modifier.isPublic(stubMethod.getModifiers())); assertTrue(Modifier.isStatic(stubMethod.getModifiers())); }
Example #24
Source File: ManagedChannelImplTest.java From grpc-java with Apache License 2.0 | 5 votes |
@Test public void binaryLogInstalled() throws Exception { final SettableFuture<Boolean> intercepted = SettableFuture.create(); channelBuilder.binlog = new BinaryLog() { @Override public void close() throws IOException { // noop } @Override public <ReqT, RespT> ServerMethodDefinition<?, ?> wrapMethodDefinition( ServerMethodDefinition<ReqT, RespT> oMethodDef) { return oMethodDef; } @Override public Channel wrapChannel(Channel channel) { return ClientInterceptors.intercept(channel, new ClientInterceptor() { @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { intercepted.set(true); return next.newCall(method, callOptions); } }); } }; createChannel(); ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT); call.start(mockCallListener, new Metadata()); assertTrue(intercepted.get()); }
Example #25
Source File: BackpressureController.java From reactive-grpc with BSD 3-Clause "New" or "Revised" License | 5 votes |
@FXML public void initialize() throws Exception { Server server = ServerBuilder.forPort(9000).addService(this).build().start(); Channel channel = ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext().build(); stub = RxBackpressureDemoGrpc.newRxStub(channel); producedSeries.setName("Produced"); consumedSeries.setName("Consumed"); lineChart.getData().add(producedSeries); lineChart.getData().add(consumedSeries); }
Example #26
Source File: EmeraldTransport.java From etherjar with Apache License 2.0 | 5 votes |
public EmeraldTransport(Channel channel, ObjectMapper objectMapper, RpcConverter rpcConverter, ExecutorService executorService, Common.ChainRef chainRef) { this.channel = channel; this.objectMapper = objectMapper; this.rpcConverter = rpcConverter; this.executorService = executorService; this.chainRef = chainRef; blockingStub = BlockchainGrpc.newBlockingStub(channel); }
Example #27
Source File: ManagedChannelImpl.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
@Override public Channel asChannel() { return new SubchannelChannel( subchannel, balancerRpcExecutorHolder.getExecutor(), transportFactory.getScheduledExecutorService(), callTracerFactory.create()); }
Example #28
Source File: ServerImplTest.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
@Test public void binaryLogInstalled() throws Exception { final SettableFuture<Boolean> intercepted = SettableFuture.create(); final ServerInterceptor interceptor = new ServerInterceptor() { @Override public <ReqT, RespT> Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) { intercepted.set(true); return next.startCall(call, headers); } }; builder.binlog = new BinaryLog() { @Override public void close() throws IOException { // noop } @Override public <ReqT, RespT> ServerMethodDefinition<?, ?> wrapMethodDefinition( ServerMethodDefinition<ReqT, RespT> oMethodDef) { return ServerMethodDefinition.create( oMethodDef.getMethodDescriptor(), InternalServerInterceptors.interceptCallHandlerCreate( interceptor, oMethodDef.getServerCallHandler())); } @Override public Channel wrapChannel(Channel channel) { return channel; } }; createAndStartServer(); basicExchangeHelper(METHOD, "Lots of pizza, please", 314, 50); assertTrue(intercepted.get()); }
Example #29
Source File: InProcessOrAlternativeChannelFactory.java From grpc-spring-boot-starter with MIT License | 5 votes |
@Override public Channel createChannel(final String name, final List<ClientInterceptor> interceptors, boolean sortInterceptors) { final URI address = this.properties.getChannel(name).getAddress(); if (address != null && IN_PROCESS_SCHEME.equals(address.getScheme())) { return this.inProcessChannelFactory.createChannel(address.getSchemeSpecificPart(), interceptors, sortInterceptors); } return this.alternativeChannelFactory.createChannel(name, interceptors, sortInterceptors); }
Example #30
Source File: NetworkTime.java From bazel with Apache License 2.0 | 5 votes |
@Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { ClientCall<ReqT, RespT> call = next.newCall(method, callOptions); // prevent accounting for execution wait time if (method != ExecutionGrpc.getExecuteMethod() && method != ExecutionGrpc.getWaitExecutionMethod()) { NetworkTime networkTime = CONTEXT_KEY.get(); if (networkTime != null) { call = new NetworkTimeCall<>(call, networkTime); } } return call; }