@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(METADATA_KEY, contextValue); stub = MetadataUtils.attachHeaders(stub, fixedHeaders); // .. and expect it to be echoed back in trailers AtomicReference<Metadata> trailersCapture = new AtomicReference<Metadata>(); AtomicReference<Metadata> headersCapture = new AtomicReference<Metadata>(); 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(METADATA_KEY)); Assert.assertEquals(contextValue, trailersCapture.get().get(METADATA_KEY)); }
static SdkServerServiceBlockingStub addClientIdentification(SdkServerServiceBlockingStub stub) { // Optional client id header String clientId = AfricasTalking.getClientId(); if (clientId != null) { Metadata headers = new Metadata(); headers.put(CLIENT_ID_HEADER_KEY, clientId); stub = MetadataUtils.attachHeaders(stub, headers); } return stub; }
@Test public void testMissingScheme() { Metadata metadata = new Metadata(); metadata.put(Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER), "dXNlcjp1c2Vy"); LoggersServiceGrpc.LoggersServiceBlockingStub stub = MetadataUtils.attachHeaders(LoggersServiceGrpc.newBlockingStub(inProcessChannel), metadata); assertGetLoggersReturnsCode(stub, Status.Code.UNAUTHENTICATED); }
@Test public void testWrongUser() { doThrow(new BadCredentialsException("unknown user")).when(authenticationManager).authenticate(anyObject()); Metadata metadata = new Metadata(); metadata.put(Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER), "<%=authScheme%> dXNlcjp1c2Vy"); LoggersServiceGrpc.LoggersServiceBlockingStub stub = MetadataUtils.attachHeaders(LoggersServiceGrpc.newBlockingStub(inProcessChannel), metadata); assertGetLoggersReturnsCode(stub, Status.Code.UNAUTHENTICATED); }
@Test public void testMalformedToken() { Metadata metadata = new Metadata(); metadata.put(Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER), "Basic dXNlcjp1c2Vy!"); LoggersServiceGrpc.LoggersServiceBlockingStub stub = MetadataUtils.attachHeaders(LoggersServiceGrpc.newBlockingStub(inProcessChannel), metadata); assertGetLoggersReturnsCode(stub, Status.Code.UNAUTHENTICATED); }
@Test public void testMissingColon() { Metadata metadata = new Metadata(); // Basic useruser metadata.put(Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER), "Basic dXNlcnVzZXI="); LoggersServiceGrpc.LoggersServiceBlockingStub stub = MetadataUtils.attachHeaders(LoggersServiceGrpc.newBlockingStub(inProcessChannel), metadata); assertGetLoggersReturnsCode(stub, Status.Code.UNAUTHENTICATED); }
/** * Create a new gRPC channel to the Google Genomics API, using the provided credentials for auth. * * @param creds The credential. * @param fields Which fields to return in the partial response, or null for none. * @return The ManagedChannel. * @throws SSLException */ public static ManagedChannel fromCreds(GoogleCredentials creds, String fields) throws SSLException { List<ClientInterceptor> interceptors = new ArrayList(); interceptors.add(new ClientAuthInterceptor(creds.createScoped(Arrays.asList(GENOMICS_SCOPE)), Executors.newSingleThreadExecutor())); if (!Strings.isNullOrEmpty(fields)) { Metadata headers = new Metadata(); Metadata.Key<String> partialResponseHeader = Metadata.Key.of(PARTIAL_RESPONSE_HEADER, Metadata.ASCII_STRING_MARSHALLER); headers.put(partialResponseHeader, fields); interceptors.add(MetadataUtils.newAttachHeadersInterceptor(headers)); } return getGenomicsManagedChannel(interceptors); }
/** 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); }
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); }
public static ClientInterceptor attachMetadataFromContextInterceptor() { return MetadataUtils.newAttachHeadersInterceptor(headersFromCurrentContext()); }
@Test public void exchangeMetadataStreamingCall() throws Exception { TestServiceGrpc.TestServiceStub stub = asyncStub; // 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(METADATA_KEY, contextValue); stub = MetadataUtils.attachHeaders(stub, fixedHeaders); // .. and expect it to be echoed back in trailers AtomicReference<Metadata> trailersCapture = new AtomicReference<Metadata>(); AtomicReference<Metadata> headersCapture = new AtomicReference<Metadata>(); stub = MetadataUtils.captureMetadata(stub, headersCapture, trailersCapture); List<Integer> responseSizes = Arrays.asList(50, 100, 150, 200); Messages.StreamingOutputCallRequest.Builder streamingOutputBuilder = Messages.StreamingOutputCallRequest.newBuilder(); streamingOutputBuilder.setResponseType(COMPRESSABLE); for (Integer size : responseSizes) { streamingOutputBuilder.addResponseParametersBuilder().setSize(size).setIntervalUs(0); } final Messages.StreamingOutputCallRequest request = streamingOutputBuilder.build(); StreamRecorder<Messages.StreamingOutputCallResponse> recorder = StreamRecorder.create(); StreamObserver<Messages.StreamingOutputCallRequest> requestStream = stub.fullDuplexCall(recorder); final int numRequests = 10; List<StreamingOutputCallRequest> requests = new ArrayList<StreamingOutputCallRequest>(numRequests); for (int ix = numRequests; ix > 0; --ix) { requests.add(request); requestStream.onNext(request); } requestStream.onCompleted(); recorder.awaitCompletion(); assertSuccess(recorder); org.junit.Assert.assertEquals(responseSizes.size() * numRequests, recorder.getValues().size()); // Assert that our side channel object is echoed back in both headers and trailers Assert.assertEquals(contextValue, headersCapture.get().get(METADATA_KEY)); Assert.assertEquals(contextValue, trailersCapture.get().get(METADATA_KEY)); }
/** * Returns the gRPC-generated {@link ReleaseServiceBlockingStub} * object that represents the capabilities of the Tiller server. * * <p>This method will never return {@code null}.</p> * * <p>Overrides of this method must never return {@code null}.</p> * * @return a non-{@code null} {@link ReleaseServiceBlockingStub} * * @see ReleaseServiceBlockingStub */ public ReleaseServiceBlockingStub getReleaseServiceBlockingStub() { ReleaseServiceBlockingStub returnValue = null; if (this.channel != null) { returnValue = MetadataUtils.attachHeaders(ReleaseServiceGrpc.newBlockingStub(this.channel), metadata); } return returnValue; }
/** * Returns the gRPC-generated {@link ReleaseServiceFutureStub} * object that represents the capabilities of the Tiller server. * * <p>This method will never return {@code null}.</p> * * <p>Overrides of this method must never return {@code null}.</p> * * @return a non-{@code null} {@link ReleaseServiceFutureStub} * * @see ReleaseServiceFutureStub */ public ReleaseServiceFutureStub getReleaseServiceFutureStub() { ReleaseServiceFutureStub returnValue = null; if (this.channel != null) { returnValue = MetadataUtils.attachHeaders(ReleaseServiceGrpc.newFutureStub(this.channel), metadata); } return returnValue; }
/** * Returns the gRPC-generated {@link ReleaseServiceStub} * object that represents the capabilities of the Tiller server. * * <p>This method will never return {@code null}.</p> * * <p>Overrides of this method must never return {@code null}.</p> * * @return a non-{@code null} {@link ReleaseServiceStub} * * @see ReleaseServiceStub */ public ReleaseServiceStub getReleaseServiceStub() { ReleaseServiceStub returnValue = null; if (this.channel != null) { returnValue = MetadataUtils.attachHeaders(ReleaseServiceGrpc.newStub(this.channel), metadata); } return returnValue; }