io.grpc.stub.MetadataUtils Java Examples
The following examples show how to use
io.grpc.stub.MetadataUtils.
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: OtlpGrpcSpanExporter.java From opentelemetry-java with Apache License 2.0 | 7 votes |
/** * Constructs a new instance of the exporter based on the builder's values. * * @return a new exporter's instance */ public OtlpGrpcSpanExporter build() { if (endpoint != null) { final ManagedChannelBuilder<?> managedChannelBuilder = ManagedChannelBuilder.forTarget(endpoint); if (useTls) { managedChannelBuilder.useTransportSecurity(); } else { managedChannelBuilder.usePlaintext(); } if (metadata != null) { managedChannelBuilder.intercept(MetadataUtils.newAttachHeadersInterceptor(metadata)); } channel = managedChannelBuilder.build(); } return new OtlpGrpcSpanExporter(channel, deadlineMs); }
Example #2
Source File: AbstractInteropTest.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
@Test public void exchangeMetadataUnaryCall() throws Exception { TestServiceGrpc.TestServiceBlockingStub stub = blockingStub; // Capture the metadata exchange Metadata fixedHeaders = new Metadata(); // Send a context proto (as it's in the default extension registry) Messages.SimpleContext contextValue = Messages.SimpleContext.newBuilder().setValue("dog").build(); fixedHeaders.put(Util.METADATA_KEY, contextValue); stub = MetadataUtils.attachHeaders(stub, fixedHeaders); // .. and expect it to be echoed back in trailers AtomicReference<Metadata> trailersCapture = new AtomicReference<>(); AtomicReference<Metadata> headersCapture = new AtomicReference<>(); stub = MetadataUtils.captureMetadata(stub, headersCapture, trailersCapture); assertNotNull(stub.emptyCall(EMPTY)); // Assert that our side channel object is echoed back in both headers and trailers Assert.assertEquals(contextValue, headersCapture.get().get(Util.METADATA_KEY)); Assert.assertEquals(contextValue, trailersCapture.get().get(Util.METADATA_KEY)); }
Example #3
Source File: AbstractInteropTest.java From grpc-java with Apache License 2.0 | 6 votes |
@Test public void exchangeMetadataUnaryCall() throws Exception { TestServiceGrpc.TestServiceBlockingStub stub = blockingStub; // Capture the metadata exchange Metadata fixedHeaders = new Metadata(); // Send a context proto (as it's in the default extension registry) Messages.SimpleContext contextValue = Messages.SimpleContext.newBuilder().setValue("dog").build(); fixedHeaders.put(Util.METADATA_KEY, contextValue); stub = MetadataUtils.attachHeaders(stub, fixedHeaders); // .. and expect it to be echoed back in trailers AtomicReference<Metadata> trailersCapture = new AtomicReference<>(); AtomicReference<Metadata> headersCapture = new AtomicReference<>(); stub = MetadataUtils.captureMetadata(stub, headersCapture, trailersCapture); assertNotNull(stub.emptyCall(EMPTY)); // Assert that our side channel object is echoed back in both headers and trailers Assert.assertEquals(contextValue, headersCapture.get().get(Util.METADATA_KEY)); Assert.assertEquals(contextValue, trailersCapture.get().get(Util.METADATA_KEY)); }
Example #4
Source File: BrokerGateway.java From gcp-token-broker with Apache License 2.0 | 6 votes |
public void setSPNEGOToken() { String encodedToken; try { encodedToken = BaseEncoding.base64().encode(SpnegoUtils.newSPNEGOToken(serverInfo.getKerberosPrincipal())); } catch (GSSException e) { // Clean up the channel before re-throwing the exception managedChannel.shutdownNow(); throw new RuntimeException( "Failed creating a SPNEGO token. Make sure that you have run kinit and that your Kerberos configuration is correct. See the full Kerberos error message: " + e.getMessage()); } // Set the 'authorization' header with the SPNEGO token Metadata metadata = new Metadata(); Metadata.Key<String> key = Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); metadata.put(key, "Negotiate " + encodedToken); stub = MetadataUtils.attachHeaders(stub, metadata); }
Example #5
Source File: DgraphAsyncClient.java From dgraph4j with Apache License 2.0 | 6 votes |
/** * getStubWithJwt adds an AttachHeadersInterceptor to the stub, which will eventually attach a * header whose key is accessJwt and value is the access JWT stored in the current * DgraphAsyncClient object. * * @param stub the original stub that we should attach JWT to * @return the augmented stub with JWT */ protected DgraphGrpc.DgraphStub getStubWithJwt(DgraphGrpc.DgraphStub stub) { Lock readLock = jwtLock.readLock(); readLock.lock(); try { if (jwt != null && !jwt.getAccessJwt().isEmpty()) { Metadata metadata = new Metadata(); metadata.put( Metadata.Key.of("accessJwt", Metadata.ASCII_STRING_MARSHALLER), jwt.getAccessJwt()); return MetadataUtils.attachHeaders(stub, metadata); } return stub; } finally { readLock.unlock(); } }
Example #6
Source File: XfccServerInterceptorTest.java From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void endToEndTest() { AtomicReference<List<XForwardedClientCert>> certs = new AtomicReference<>(); GreeterGrpc.GreeterImplBase svc = new GreeterGrpc.GreeterImplBase() { @Override public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) { certs.set(XForwardedClientCert.XFCC_CONTEXT_KEY.get()); responseObserver.onNext(HelloResponse.newBuilder().setMessage("Hello " + request.getName()).build()); responseObserver.onCompleted(); } }; serverRule.getServiceRegistry().addService(ServerInterceptors.intercept(svc, new XfccServerInterceptor())); String xfcc = "By=http://frontend.lyft.com;Hash=468ed33be74eee6556d90c0149c1309e9ba61d6425303443c0748a02dd8de688;SAN=http://testclient.lyft.com," + "By=http://backend.lyft.com;Hash=9ba61d6425303443c0748a02dd8de688468ed33be74eee6556d90c0149c1309e;SAN=http://frontend.lyft.com"; Metadata xfccHeader = new Metadata(); xfccHeader.put(Metadata.Key.of("x-forwarded-client-cert", Metadata.ASCII_STRING_MARSHALLER), xfcc); GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(serverRule.getChannel()) .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(xfccHeader)); stub.sayHello(HelloRequest.newBuilder().setName("World").build()); assertThat(certs.get().size()).isEqualTo(2); assertThat(certs.get().get(0).getBy()).isEqualTo("http://frontend.lyft.com"); assertThat(certs.get().get(1).getBy()).isEqualTo("http://backend.lyft.com"); }
Example #7
Source File: GrpcHeaderHandler.java From buck with Apache License 2.0 | 5 votes |
/** Receives RemoteExecutionMetadata from the initial GRPC headers. */ public static <Stub extends AbstractStub<Stub>> StubAndResponseMetadata<Stub> wrapStubToReceiveMetadata(Stub grpcStub) { AtomicReference<Metadata> initialMetadata = new AtomicReference<>(); AtomicReference<Metadata> trailingMetadata = new AtomicReference<>(); Stub grpcWrappedStub = MetadataUtils.captureMetadata(grpcStub, initialMetadata, trailingMetadata); return new StubAndResponseMetadataImpl<>(grpcWrappedStub, initialMetadata, trailingMetadata); }
Example #8
Source File: XfccServerInterceptorTest.java From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void endToEndTestMultiple() { AtomicReference<List<XForwardedClientCert>> certs = new AtomicReference<>(); GreeterGrpc.GreeterImplBase svc = new GreeterGrpc.GreeterImplBase() { @Override public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) { certs.set(XForwardedClientCert.XFCC_CONTEXT_KEY.get()); responseObserver.onNext(HelloResponse.newBuilder().setMessage("Hello " + request.getName()).build()); responseObserver.onCompleted(); } }; serverRule.getServiceRegistry().addService(ServerInterceptors.intercept(svc, new XfccServerInterceptor())); String xfcc = "By=http://frontend.lyft.com;Hash=468ed33be74eee6556d90c0149c1309e9ba61d6425303443c0748a02dd8de688;SAN=http://testclient.lyft.com," + "By=http://backend.lyft.com;Hash=9ba61d6425303443c0748a02dd8de688468ed33be74eee6556d90c0149c1309e;SAN=http://frontend.lyft.com"; String xfcc2 = "By=http://middle.lyft.com;Hash=468ed33be74eee6556d90c0149c1309e9ba61d6425303443c0748a02dd8de688;" + "SAN=http://testclient.lyft.com"; Metadata xfccHeader = new Metadata(); Metadata.Key<String> key = Metadata.Key.of("x-forwarded-client-cert", Metadata.ASCII_STRING_MARSHALLER); xfccHeader.put(key, xfcc); xfccHeader.put(key, xfcc2); GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(serverRule.getChannel()) .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(xfccHeader)); stub.sayHello(HelloRequest.newBuilder().setName("World").build()); assertThat(certs.get().size()).isEqualTo(3); assertThat(certs.get().get(0).getBy()).isEqualTo("http://frontend.lyft.com"); assertThat(certs.get().get(1).getBy()).isEqualTo("http://backend.lyft.com"); assertThat(certs.get().get(2).getBy()).isEqualTo("http://middle.lyft.com"); }
Example #9
Source File: EmbeddedTitusGateway.java From titus-control-plane with Apache License 2.0 | 5 votes |
private <STUB extends AbstractStub<STUB>> STUB attachCallHeaders(STUB client) { Metadata metadata = new Metadata(); metadata.put(V3HeaderInterceptor.CALLER_ID_KEY, "embeddedGatewayClient"); metadata.put(V3HeaderInterceptor.CALL_REASON_KEY, "test call"); metadata.put(V3HeaderInterceptor.DEBUG_KEY, "true"); return client.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(metadata)); }
Example #10
Source File: EmbeddedTitusFederation.java From titus-control-plane with Apache License 2.0 | 5 votes |
private <STUB extends AbstractStub<STUB>> STUB attachCallHeaders(STUB client) { Metadata metadata = new Metadata(); metadata.put(V3HeaderInterceptor.CALLER_ID_KEY, "embeddedFederationClient"); metadata.put(V3HeaderInterceptor.CALL_REASON_KEY, "test call"); metadata.put(V3HeaderInterceptor.DEBUG_KEY, "true"); return client.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(metadata)); }
Example #11
Source File: TestKitGrpcClientErrorUtils.java From titus-control-plane with Apache License 2.0 | 5 votes |
public static <STUB extends AbstractStub<STUB>> STUB attachCallHeaders(STUB client) { Metadata metadata = new Metadata(); metadata.put(V3HeaderInterceptor.CALLER_ID_KEY, "testkitClient"); metadata.put(V3HeaderInterceptor.CALL_REASON_KEY, "test call"); metadata.put(V3HeaderInterceptor.DEBUG_KEY, "true"); return client.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(metadata)); }
Example #12
Source File: App.java From dgraph4j with Apache License 2.0 | 5 votes |
private static DgraphClient createDgraphClient(boolean withAuthHeader) { ManagedChannel channel = ManagedChannelBuilder.forAddress(TEST_HOSTNAME, TEST_PORT).usePlaintext().build(); DgraphStub stub = DgraphGrpc.newStub(channel); if (withAuthHeader) { Metadata metadata = new Metadata(); metadata.put( Metadata.Key.of("auth-token", Metadata.ASCII_STRING_MARSHALLER), "the-auth-token-value"); stub = MetadataUtils.attachHeaders(stub, metadata); } return new DgraphClient(stub); }
Example #13
Source File: AuthServiceChannel.java From modeldb with Apache License 2.0 | 5 votes |
private void initUACServiceStubChannel() { Metadata requestHeaders = getMetadataHeaders(); LOGGER.trace("Header attaching with stub : {}", requestHeaders); ClientInterceptor clientInterceptor = MetadataUtils.newAttachHeadersInterceptor(requestHeaders); uacServiceBlockingStub = UACServiceGrpc.newBlockingStub(authServiceChannel).withInterceptors(clientInterceptor); LOGGER.trace("Header attached with stub"); }
Example #14
Source File: AuthServiceChannel.java From modeldb with Apache License 2.0 | 5 votes |
private void initRoleServiceStubChannel() { Metadata requestHeaders = getMetadataHeaders(); LOGGER.trace("Header attaching with stub : {}", requestHeaders); ClientInterceptor clientInterceptor = MetadataUtils.newAttachHeadersInterceptor(requestHeaders); roleServiceBlockingStub = RoleServiceGrpc.newBlockingStub(authServiceChannel).withInterceptors(clientInterceptor); LOGGER.trace("Header attached with stub"); }
Example #15
Source File: AuthServiceChannel.java From modeldb with Apache License 2.0 | 5 votes |
private void initRoleServiceFutureStubChannel() { Metadata requestHeaders = getMetadataHeaders(); LOGGER.trace("Header attaching with stub : {}", requestHeaders); ClientInterceptor clientInterceptor = MetadataUtils.newAttachHeadersInterceptor(requestHeaders); roleServiceFutureStub = RoleServiceGrpc.newFutureStub(authServiceChannel).withInterceptors(clientInterceptor); LOGGER.trace("Header attached with stub"); }
Example #16
Source File: AuthServiceChannel.java From modeldb with Apache License 2.0 | 5 votes |
private void initAuthzServiceStubChannel(Metadata requestHeaders) { if (requestHeaders == null) requestHeaders = getMetadataHeaders(); LOGGER.trace("Header attaching with stub : {}", requestHeaders); ClientInterceptor clientInterceptor = MetadataUtils.newAttachHeadersInterceptor(requestHeaders); authzServiceBlockingStub = AuthzServiceGrpc.newBlockingStub(authServiceChannel).withInterceptors(clientInterceptor); LOGGER.trace("Header attached with stub"); }
Example #17
Source File: AuthServiceChannel.java From modeldb with Apache License 2.0 | 5 votes |
private void initTeamServiceStubChannel() { Metadata requestHeaders = getMetadataHeaders(); LOGGER.trace("Header attaching with stub : {}", requestHeaders); ClientInterceptor clientInterceptor = MetadataUtils.newAttachHeadersInterceptor(requestHeaders); teamServiceBlockingStub = TeamServiceGrpc.newBlockingStub(authServiceChannel).withInterceptors(clientInterceptor); LOGGER.trace("Header attached with stub"); }
Example #18
Source File: AuthServiceChannel.java From modeldb with Apache License 2.0 | 5 votes |
private void initOrganizationServiceStubChannel() { Metadata requestHeaders = getMetadataHeaders(); LOGGER.trace("Header attaching with stub : {}", requestHeaders); ClientInterceptor clientInterceptor = MetadataUtils.newAttachHeadersInterceptor(requestHeaders); organizationServiceBlockingStub = OrganizationServiceGrpc.newBlockingStub(authServiceChannel) .withInterceptors(clientInterceptor); LOGGER.trace("Header attached with stub"); }
Example #19
Source File: GrpcClientTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void exchangeHeadersUnaryCall_armeriaHeaders() throws Exception { TestServiceBlockingStub stub = Clients.newDerivedClient( blockingStub, ClientOption.HTTP_HEADERS.newValue( HttpHeaders.of(TestServiceImpl.EXTRA_HEADER_NAME, "dog"))); final AtomicReference<Metadata> headers = new AtomicReference<>(); final AtomicReference<Metadata> trailers = new AtomicReference<>(); stub = MetadataUtils.captureMetadata(stub, headers, trailers); assertThat(stub.emptyCall(EMPTY)).isNotNull(); // Assert that our side channel object is echoed back in both headers and trailers assertThat(CLIENT_HEADERS_CAPTURE.get().get(TestServiceImpl.EXTRA_HEADER_NAME)).isEqualTo("dog"); assertThat(SERVER_TRAILERS_CAPTURE.get().get(TestServiceImpl.EXTRA_HEADER_NAME)).isEqualTo("dog"); assertThat(headers.get()).isNull(); assertThat(trailers.get().get(TestServiceImpl.EXTRA_HEADER_KEY)).isEqualTo("dog"); assertThat(trailers.get().getAll(TestServiceImpl.STRING_VALUE_KEY)).containsExactly( StringValue.newBuilder().setValue("hello").build(), StringValue.newBuilder().setValue("world").build()); checkRequestLog((rpcReq, rpcRes, grpcStatus) -> { assertThat(rpcReq.params()).containsExactly(EMPTY); assertThat(rpcRes.get()).isEqualTo(EMPTY); }); }
Example #20
Source File: GrpcClientTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void exchangeHeadersUnaryCall_grpcMetadata() throws Exception { final Metadata metadata = new Metadata(); metadata.put(TestServiceImpl.EXTRA_HEADER_KEY, "dog"); TestServiceBlockingStub stub = MetadataUtils.attachHeaders(blockingStub, metadata); final AtomicReference<Metadata> headers = new AtomicReference<>(); final AtomicReference<Metadata> trailers = new AtomicReference<>(); stub = MetadataUtils.captureMetadata(stub, headers, trailers); assertThat(stub.emptyCall(EMPTY)).isNotNull(); final HttpHeaders clientHeaders = CLIENT_HEADERS_CAPTURE.get(); assertThat(clientHeaders.get(HttpHeaderNames.TE)) .isEqualTo(HttpHeaderValues.TRAILERS.toString()); // Assert that our side channel object is echoed back in both headers and trailers assertThat(clientHeaders.get(TestServiceImpl.EXTRA_HEADER_NAME)).isEqualTo("dog"); assertThat(SERVER_TRAILERS_CAPTURE.get().get(TestServiceImpl.EXTRA_HEADER_NAME)).isEqualTo("dog"); assertThat(headers.get()).isNull(); assertThat(trailers.get().get(TestServiceImpl.EXTRA_HEADER_KEY)).isEqualTo("dog"); assertThat(trailers.get().getAll(TestServiceImpl.STRING_VALUE_KEY)).containsExactly( StringValue.newBuilder().setValue("hello").build(), StringValue.newBuilder().setValue("world").build()); checkRequestLog((rpcReq, rpcRes, grpcStatus) -> { assertThat(rpcReq.params()).containsExactly(EMPTY); assertThat(rpcRes.get()).isEqualTo(EMPTY); }); }
Example #21
Source File: HelloWorldSimpleClient.java From pinpoint with Apache License 2.0 | 5 votes |
/** * Construct client connecting to HelloWorld server at {@code host:port}. */ @SuppressWarnings("deprecated") public HelloWorldSimpleClient(String host, int port) { this(ManagedChannelBuilder.forAddress(host, port) // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid // needing certificates. // .usePlaintext() // no API in old version .usePlaintext(true) .intercept(MetadataUtils.newCaptureMetadataInterceptor(new AtomicReference<Metadata>(), new AtomicReference<Metadata>())) .build()); }
Example #22
Source File: AgentClientMock.java From pinpoint with Apache License 2.0 | 5 votes |
public AgentClientMock(final String host, final int port, final boolean agentHeader) { NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port); if (agentHeader) { HeaderFactory headerFactory = new AgentHeaderFactory("mockAgentId", "mockApplicationName", System.currentTimeMillis()); final Metadata extraHeaders = headerFactory.newHeader(); final ClientInterceptor headersInterceptor = MetadataUtils.newAttachHeadersInterceptor(extraHeaders); builder.intercept(headersInterceptor); } builder.usePlaintext(); channel = builder.build(); this.agentStub = AgentGrpc.newStub(channel); this.metadataStub = MetadataGrpc.newBlockingStub(channel); }
Example #23
Source File: StatClientMock.java From pinpoint with Apache License 2.0 | 5 votes |
public StatClientMock(final String host, final int port) { NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port); HeaderFactory headerFactory = new AgentHeaderFactory("mockAgentId", "mockApplicationName", System.currentTimeMillis()); final Metadata extraHeaders = headerFactory.newHeader(); final ClientInterceptor headersInterceptor = MetadataUtils.newAttachHeadersInterceptor(extraHeaders); builder.intercept(headersInterceptor); builder.usePlaintext(); channel = builder.build(); this.statStub = StatGrpc.newStub(channel); }
Example #24
Source File: DefaultChannelFactory.java From pinpoint with Apache License 2.0 | 5 votes |
private void addHeader(NettyChannelBuilder channelBuilder) { final Metadata extraHeaders = headerFactory.newHeader(); if (logger.isDebugEnabled()) { logger.debug("addHeader {}", extraHeaders); } final ClientInterceptor headersInterceptor = MetadataUtils.newAttachHeadersInterceptor(extraHeaders); channelBuilder.intercept(headersInterceptor); }
Example #25
Source File: AbstractInteropTest.java From grpc-java with Apache License 2.0 | 5 votes |
/** Sends a cacheable unary rpc using GET. Requires that the server is behind a caching proxy. */ public void cacheableUnary() { // THIS TEST IS BROKEN. Enabling safe just on the MethodDescriptor does nothing by itself. This // test would need to enable GET on the channel. // 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); // THIS TEST IS BROKEN. See comment at start of method. }
Example #26
Source File: GrpcHeaderHandler.java From buck with Apache License 2.0 | 5 votes |
/** Appends RemoteExecutionMetadata to the GRPC headers. */ public static <Stub extends AbstractStub<Stub>> Stub wrapStubToSendMetadata( Stub grpcStub, RemoteExecutionMetadata metadata) { Metadata extraHeaders = new Metadata(); extraHeaders.put(REMOTE_EXECUTION_METADATA_KEY, metadata.toByteArray()); return MetadataUtils.attachHeaders(grpcStub, extraHeaders); }
Example #27
Source File: AbstractInteropTest.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
/** 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); }
Example #28
Source File: Tiller.java From microbean-helm with Apache License 2.0 | 5 votes |
public HealthBlockingStub getHealthBlockingStub() { HealthBlockingStub returnValue = null; if (this.channel != null) { returnValue = MetadataUtils.attachHeaders(HealthGrpc.newBlockingStub(this.channel), metadata); } return returnValue; }
Example #29
Source File: GrpcClientTest.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
@Before public void setup() { MockitoAnnotations.initMocks(this); inAppMessagingSdkServingBlockingStub = InAppMessagingSdkServingGrpc.newBlockingStub( ClientInterceptors.intercept( grpcServerRule.getChannel(), MetadataUtils.newAttachHeadersInterceptor(testMetadata))); grpcClient = new GrpcClient(inAppMessagingSdkServingBlockingStub); }
Example #30
Source File: GrpcClientModule.java From firebase-android-sdk with Apache License 2.0 | 5 votes |
@Provides @FirebaseAppScope public InAppMessagingSdkServingBlockingStub providesInAppMessagingSdkServingStub( Channel channel, Metadata metadata) { return InAppMessagingSdkServingGrpc.newBlockingStub( ClientInterceptors.intercept(channel, MetadataUtils.newAttachHeadersInterceptor(metadata))); }