@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); } }; }
@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 (GoogleCredentialsInterceptor.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); } }; }
private ClientInterceptor metadataInterceptor() { ClientInterceptor interceptor = new ClientInterceptor() { @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( final io.grpc.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 { for (ConfigProto.CallMetadataEntry entry : callConfiguration.getMetadataList()) { Metadata.Key<String> key = Metadata.Key.of(entry.getName(), Metadata.ASCII_STRING_MARSHALLER); headers.put(key, entry.getValue()); } delegate().start(responseListener, headers); } }; } }; return interceptor; }
/** * Initializes a connection to the gRPC server. * @return a boolean indicating the success. */ private boolean initServerConnection() { if(!mConnected) { mInterceptor = new AuthHeaderClientInterceptor( getUserIdToken()); try { mChannelImpl = OkHttpChannelBuilder .forAddress(AndroidConstants.HOST, AndroidConstants.PORT) .build(); Channel mOriginChannel = ClientInterceptors .intercept(mChannelImpl, mInterceptor); mBlockingStub = AbelanaGrpc.newBlockingStub(mOriginChannel); mConnected = true; } catch (RuntimeException e) { mConnected = false; } } return mConnected; }
@Test public void clientHeaderDeliveredToServer() { grpcServerRule.getServiceRegistry() .addService(ServerInterceptors.intercept(new GreeterImplBase() {}, mockServerInterceptor)); GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub( ClientInterceptors.intercept(grpcServerRule.getChannel(), new HeaderClientInterceptor())); ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class); try { blockingStub.sayHello(HelloRequest.getDefaultInstance()); fail(); } catch (StatusRuntimeException expected) { // expected because the method is not implemented at server side } verify(mockServerInterceptor).interceptCall( Matchers.<ServerCall<HelloRequest, HelloReply>>any(), metadataCaptor.capture(), Matchers.<ServerCallHandler<HelloRequest, HelloReply>>any()); assertEquals( "customRequestValue", metadataCaptor.getValue().get(HeaderClientInterceptor.CUSTOM_HEADER_KEY)); }
@Before public void setUp() throws Exception { faker = new Faker(); Injector injector = Guice.createInjector(); EchoService echoService = injector.getInstance(EchoService.class); ServiceInterceptor serviceInterceptor = injector.getInstance(ServiceInterceptor.class); CallerInterceptor callerInterceptor = injector.getInstance(CallerInterceptor.class); grpcServerRule.getServiceRegistry().addService(ServerInterceptors.intercept(echoService, serviceInterceptor)); Channel channel = ClientInterceptors.intercept( grpcServerRule.getChannel(), callerInterceptor); stub = EchoServiceGrpc.newBlockingStub(channel); }
/** Construct client for accessing RouteGuide server using the existing channel. */ public SeldonClientExample(ManagedChannelBuilder<?> channelBuilder) { ClientInterceptor interceptor = new HeaderClientInterceptor(); channel = channelBuilder.build(); Channel interceptChannel = ClientInterceptors.intercept(channel, interceptor); blockingStub = SeldonGrpc.newBlockingStub(interceptChannel); asyncStub = SeldonGrpc.newStub(interceptChannel); }
/** * A custom client. */ private CustomHeaderClient(String host, int port) { originChannel = ManagedChannelBuilder.forAddress(host, port) .usePlaintext(true) .build(); ClientInterceptor interceptor = new HeaderClientInterceptor(); Channel channel = ClientInterceptors.intercept(originChannel, interceptor); blockingStub = GreeterGrpc.newBlockingStub(channel); }
/** Return {@link io.grpc.Channel} which is used by Cloud Pub/Sub gRPC API's. */ public static Channel getChannel() throws IOException { ManagedChannel channelImpl = NettyChannelBuilder.forAddress(ENDPOINT, 443).negotiationType(NegotiationType.TLS).build(); final ClientAuthInterceptor interceptor = new ClientAuthInterceptor( GoogleCredentials.getApplicationDefault().createScoped(CPS_SCOPE), Executors.newCachedThreadPool()); return ClientInterceptors.intercept(channelImpl, interceptor); }
/** * Wrap a Listener that will record the final Call status in onClose. */ Listener<ResponseT> createGatheringListener(Listener<ResponseT> responseListener) { return new ClientInterceptors.ForwardingListener<ResponseT>(responseListener) { @Override public void onClose(Status status, Metadata.Trailers trailers) { callCompletionStatuses.add(new CallCompletionStatus(method, status)); super.onClose(status, trailers); }}; }
/** Construct client connecting to HelloWorld server at {@code host:port}. */ public HelloWorldClient(String address, String apiKey) { channel = ManagedChannelBuilder.forTarget(address) // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid // needing certificates. .usePlaintext(true) .build(); Channel ch = ClientInterceptors.intercept(channel, new Interceptor(apiKey)); blockingStub = GreeterGrpc.newBlockingStub(ch); }
static BookstoreGrpc.BookstoreBlockingStub createBookstoreStub( String address, String apiKey, String authToken) { Channel channel = ManagedChannelBuilder.forTarget(address) .usePlaintext(true) .build(); channel = ClientInterceptors.intercept(channel, new Interceptor(apiKey, authToken)); return BookstoreGrpc.newBlockingStub(channel); }
public static void main(final String[] args) throws Exception { if (args.length == 0) { System.err.println("Please specify your project name."); System.exit(1); } final String project = args[0]; ManagedChannelImpl channelImpl = NettyChannelBuilder .forAddress("pubsub.googleapis.com", 443) .negotiationType(NegotiationType.TLS) .build(); GoogleCredentials creds = GoogleCredentials.getApplicationDefault(); // Down-scope the credential to just the scopes required by the service creds = creds.createScoped(Arrays.asList("https://www.googleapis.com/auth/pubsub")); // Intercept the channel to bind the credential ExecutorService executor = Executors.newSingleThreadExecutor(); ClientAuthInterceptor interceptor = new ClientAuthInterceptor(creds, executor); Channel channel = ClientInterceptors.intercept(channelImpl, interceptor); // Create a stub using the channel that has the bound credential PublisherGrpc.PublisherBlockingStub publisherStub = PublisherGrpc.newBlockingStub(channel); ListTopicsRequest request = ListTopicsRequest.newBuilder() .setPageSize(10) .setProject("projects/" + project) .build(); ListTopicsResponse resp = publisherStub.listTopics(request); System.out.println("Found " + resp.getTopicsCount() + " topics."); for (Topic topic : resp.getTopicsList()) { System.out.println(topic.getName()); } }
private GrpcRemoteCache newClient() throws IOException { AuthAndTLSOptions authTlsOptions = Options.getDefaults(AuthAndTLSOptions.class); authTlsOptions.useGoogleDefaultCredentials = true; authTlsOptions.googleCredentials = "/exec/root/creds.json"; authTlsOptions.googleAuthScopes = ImmutableList.of("dummy.scope"); GenericJson json = new GenericJson(); json.put("type", "authorized_user"); json.put("client_id", "some_client"); json.put("client_secret", "foo"); json.put("refresh_token", "bar"); Scratch scratch = new Scratch(); scratch.file(authTlsOptions.googleCredentials, new JacksonFactory().toString(json)); CallCredentials creds = GoogleAuthUtils.newCallCredentials( scratch.resolve(authTlsOptions.googleCredentials).getInputStream(), authTlsOptions.googleAuthScopes); RemoteOptions remoteOptions = Options.getDefaults(RemoteOptions.class); RemoteRetrier retrier = new RemoteRetrier( remoteOptions, RemoteRetrier.RETRIABLE_GRPC_ERRORS, Retrier.ALLOW_ALL_CALLS); return new GrpcRemoteCache( ClientInterceptors.intercept( InProcessChannelBuilder.forName(fakeServerName).directExecutor().build(), ImmutableList.of(new CallCredentialsInterceptor(creds))), creds, remoteOptions, retrier, DIGEST_UTIL); }
@Before public void setUp() throws Exception { grpcServerRule .getServiceRegistry() .addService( ServerInterceptors.intercept(greeterServiceImpl, injectCacheControlInterceptor)); grpcServerRule.getServiceRegistry().addService(anotherGreeterServiceImpl); baseChannel = grpcServerRule.getChannel(); SafeMethodCachingInterceptor interceptor = SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache); channelToUse = ClientInterceptors.intercept(baseChannel, interceptor); }
@Test public void invalidResponseMaxAge_usesDefault() throws Exception { SafeMethodCachingInterceptor interceptorWithCustomMaxAge = SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache, 1); channelToUse = ClientInterceptors.intercept(baseChannel, interceptorWithCustomMaxAge); cacheControlDirectives.add("max-age=-10"); HelloReply reply1 = ClientCalls.blockingUnaryCall( channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message); HelloReply reply2 = ClientCalls.blockingUnaryCall( channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message); assertEquals(reply1, reply2); // Wait for cache entry to expire sleepAtLeast(1001); assertNotEquals( reply1, ClientCalls.blockingUnaryCall( channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message)); Truth.assertThat(cache.removedKeys).hasSize(1); assertEquals( new SafeMethodCachingInterceptor.Key( GreeterGrpc.getSayHelloMethod().getFullMethodName(), message), cache.removedKeys.get(0)); }
@Test public void afterDefaultMaxAge_cacheEntryInvalidated() throws Exception { SafeMethodCachingInterceptor interceptorWithCustomMaxAge = SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache, 1); channelToUse = ClientInterceptors.intercept(baseChannel, interceptorWithCustomMaxAge); HelloReply reply1 = ClientCalls.blockingUnaryCall( channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message); HelloReply reply2 = ClientCalls.blockingUnaryCall( channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message); assertSame(reply1, reply2); // Wait for cache entry to expire sleepAtLeast(1001); assertNotEquals( reply1, ClientCalls.blockingUnaryCall( channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message)); Truth.assertThat(cache.removedKeys).hasSize(1); assertEquals( new SafeMethodCachingInterceptor.Key( GreeterGrpc.getSayHelloMethod().getFullMethodName(), message), cache.removedKeys.get(0)); }
public InteropTester(String testCase, ManagedChannel channel, TestListener listener, boolean useGet) { this.testCase = testCase; this.listener = listener; this.channel = channel; Channel channelToUse = channel; if (useGet) { channelToUse = ClientInterceptors.intercept(channel, new SafeMethodChannelInterceptor()); } blockingStub = TestServiceGrpc.newBlockingStub(channelToUse); asyncStub = TestServiceGrpc.newStub(channelToUse); }
/** Sends a cacheable unary rpc using GET. Requires that the server is behind a caching proxy. */ public void cacheableUnary() { // Set safe to true. MethodDescriptor<SimpleRequest, SimpleResponse> safeCacheableUnaryCallMethod = TestServiceGrpc.getCacheableUnaryCallMethod().toBuilder().setSafe(true).build(); // Set fake user IP since some proxies (GFE) won't cache requests from localhost. Metadata.Key<String> userIpKey = Metadata.Key.of("x-user-ip", Metadata.ASCII_STRING_MARSHALLER); Metadata metadata = new Metadata(); metadata.put(userIpKey, "1.2.3.4"); Channel channelWithUserIpKey = ClientInterceptors.intercept(channel, MetadataUtils.newAttachHeadersInterceptor(metadata)); SimpleRequest requests1And2 = SimpleRequest.newBuilder() .setPayload( Payload.newBuilder() .setBody(ByteString.copyFromUtf8(String.valueOf(System.nanoTime())))) .build(); SimpleRequest request3 = SimpleRequest.newBuilder() .setPayload( Payload.newBuilder() .setBody(ByteString.copyFromUtf8(String.valueOf(System.nanoTime())))) .build(); SimpleResponse response1 = ClientCalls.blockingUnaryCall( channelWithUserIpKey, safeCacheableUnaryCallMethod, CallOptions.DEFAULT, requests1And2); SimpleResponse response2 = ClientCalls.blockingUnaryCall( channelWithUserIpKey, safeCacheableUnaryCallMethod, CallOptions.DEFAULT, requests1And2); SimpleResponse response3 = ClientCalls.blockingUnaryCall( channelWithUserIpKey, safeCacheableUnaryCallMethod, CallOptions.DEFAULT, request3); assertEquals(response1, response2); assertNotEquals(response1, response3); }
public Channel createChannelWithCredentials(HostAndPort endpoint, Credentials credentials) { return ClientInterceptors.intercept( createChannel(endpoint), new ClientAuthInterceptor(credentials, authExecutor)); }
/** * Return channel with interceptor for returning credentials. */ private Channel newChannel() throws IOException { checkState(publisherChannel != null, "PubsubGrpcClient has been closed"); ClientAuthInterceptor interceptor = new ClientAuthInterceptor(credentials, Executors.newSingleThreadExecutor()); return ClientInterceptors.intercept(publisherChannel, interceptor); }
private static CloseableChannel wrapChannel(ChannelOptions channelOptions, ExecutorService executor, Channel channel, ClientCloseHandler onClientClose) { List<ClientInterceptor> interceptors = new ArrayList<>(); if (channelOptions.getCredential() != null) { interceptors.add(new ClientAuthInterceptor(channelOptions.getCredential(), executor)); } if (channelOptions.getAuthority() != null) { Metadata.Headers headers = new Metadata.Headers(); headers.setAuthority(channelOptions.getAuthority()); interceptors.add(MetadataUtils.newAttachHeadersInterceptor(headers)); } CallCompletionStatusInterceptor preRetryCallStatusInterceptor = null; if (!Strings.isNullOrEmpty(channelOptions.getCallStatusReportPath())) { preRetryCallStatusInterceptor = new CallCompletionStatusInterceptor(); interceptors.add(preRetryCallStatusInterceptor); } if (!interceptors.isEmpty()) { channel = ClientInterceptors.intercept(channel, interceptors); interceptors.clear(); } if (channelOptions.getUnaryCallRetryOptions().enableRetries()) { ScheduledExecutorService scheduledRetries; if (channelOptions.getScheduledExecutorService() != null) { scheduledRetries = channelOptions.getScheduledExecutorService(); } else { scheduledRetries = createScheduledRetryPool(); onClientClose = createChainedCloseHandler( onClientClose, createExecutorCloseHandler(scheduledRetries)); } RetryOptions unaryCallRetryOptions = channelOptions.getUnaryCallRetryOptions(); channel = new UnaryCallRetryInterceptor( channel, scheduledRetries, METHODS_TO_RETRY_MAP, unaryCallRetryOptions.getInitialBackoffMillis(), unaryCallRetryOptions.getBackoffMultiplier(), unaryCallRetryOptions.getMaxElaspedBackoffMillis()); } if (!Strings.isNullOrEmpty(channelOptions.getCallStatusReportPath())) { CallCompletionStatusInterceptor postRetryCallStatusInterceptor = new CallCompletionStatusInterceptor(); registerCallStatusReportingShutdownHook( channelOptions.getCallStatusReportPath(), preRetryCallStatusInterceptor, postRetryCallStatusInterceptor); channel = ClientInterceptors.intercept(channel, postRetryCallStatusInterceptor); } return createCloseableChannel(channel, onClientClose); }
@Override protected String doInBackground(Object... params) { String host = (String) params[0]; String message = (String) params[1]; String portStr = (String) params[2]; boolean useGet = (boolean) params[3]; boolean noCache = (boolean) params[4]; boolean onlyIfCached = (boolean) params[5]; int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr); try { channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build(); Channel channelToUse = ClientInterceptors.intercept( channel, SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache)); HelloRequest request = HelloRequest.newBuilder().setName(message).build(); HelloReply reply; if (useGet) { MethodDescriptor<HelloRequest, HelloReply> safeCacheableUnaryCallMethod = GreeterGrpc.getSayHelloMethod().toBuilder().setSafe(true).build(); CallOptions callOptions = CallOptions.DEFAULT; if (noCache) { callOptions = callOptions.withOption(SafeMethodCachingInterceptor.NO_CACHE_CALL_OPTION, true); } if (onlyIfCached) { callOptions = callOptions.withOption( SafeMethodCachingInterceptor.ONLY_IF_CACHED_CALL_OPTION, true); } reply = ClientCalls.blockingUnaryCall( channelToUse, safeCacheableUnaryCallMethod, callOptions, request); } else { GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channelToUse); reply = stub.sayHello(request); } return reply.getMessage(); } catch (Exception e) { Log.e(TAG, "RPC failed", e); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); pw.flush(); return String.format("Failed... : %n%s", sw); } }
/** * Wraps a channel to provide binary logging on {@link ClientCall}s as needed. */ Channel wrapChannel(Channel channel) { return ClientInterceptors.intercept(channel, binaryLogShim); }
ManagedChannelImpl( AbstractManagedChannelImplBuilder<?> builder, ClientTransportFactory clientTransportFactory, BackoffPolicy.Provider backoffPolicyProvider, ObjectPool<? extends Executor> oobExecutorPool, Supplier<Stopwatch> stopwatchSupplier, List<ClientInterceptor> interceptors, ProxyDetector proxyDetector, CallTracer.Factory callTracerFactory) { this.target = checkNotNull(builder.target, "target"); this.nameResolverFactory = builder.getNameResolverFactory(); this.nameResolverParams = checkNotNull(builder.getNameResolverParams(), "nameResolverParams"); this.nameResolver = getNameResolver(target, nameResolverFactory, nameResolverParams); this.loadBalancerFactory = checkNotNull(builder.loadBalancerFactory, "loadBalancerFactory"); this.executorPool = checkNotNull(builder.executorPool, "executorPool"); this.oobExecutorPool = checkNotNull(oobExecutorPool, "oobExecutorPool"); this.executor = checkNotNull(executorPool.getObject(), "executor"); this.delayedTransport = new DelayedClientTransport(this.executor, this.channelExecutor); this.delayedTransport.start(delayedTransportListener); this.backoffPolicyProvider = backoffPolicyProvider; this.transportFactory = new CallCredentialsApplyingTransportFactory(clientTransportFactory, this.executor); Channel channel = new RealChannel(); if (builder.binlogProvider != null) { channel = builder.binlogProvider.wrapChannel(channel); } this.interceptorChannel = ClientInterceptors.intercept(channel, interceptors); this.stopwatchSupplier = checkNotNull(stopwatchSupplier, "stopwatchSupplier"); if (builder.idleTimeoutMillis == IDLE_TIMEOUT_MILLIS_DISABLE) { this.idleTimeoutMillis = builder.idleTimeoutMillis; } else { checkArgument( builder.idleTimeoutMillis >= AbstractManagedChannelImplBuilder.IDLE_MODE_MIN_TIMEOUT_MILLIS, "invalid idleTimeoutMillis %s", builder.idleTimeoutMillis); this.idleTimeoutMillis = builder.idleTimeoutMillis; } this.fullStreamDecompression = builder.fullStreamDecompression; this.decompressorRegistry = checkNotNull(builder.decompressorRegistry, "decompressorRegistry"); this.compressorRegistry = checkNotNull(builder.compressorRegistry, "compressorRegistry"); this.userAgent = builder.userAgent; this.proxyDetector = proxyDetector; this.channelBufferLimit = builder.retryBufferSize; this.perRpcBufferLimit = builder.perRpcBufferLimit; phantom = new ManagedChannelReference(this); this.callTracerFactory = callTracerFactory; channelCallTracer = callTracerFactory.create(); logger.log(Level.FINE, "[{0}] Created with target {1}", new Object[] {getLogId(), target}); }
/** * Returns a new stub that has the given interceptors attached to the underlying channel. * * @since 1.0.0 */ public final S withInterceptors(ClientInterceptor... interceptors) { return build(ClientInterceptors.intercept(channel, interceptors), callOptions); }