Java Code Examples for io.grpc.CallOptions#DEFAULT

The following examples show how to use io.grpc.CallOptions#DEFAULT . 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: NettyClientStreamTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void setHttp2StreamShouldNotifyReady() {
  listener = mock(ClientStreamListener.class);

  stream = new NettyClientStream(new TransportStateImpl(handler, DEFAULT_MAX_MESSAGE_SIZE),
      methodDescriptor,
      new Metadata(),
      channel,
      AsciiString.of("localhost"),
      AsciiString.of("http"),
      AsciiString.of("agent"),
      StatsTraceContext.NOOP,
      transportTracer,
      CallOptions.DEFAULT);
  stream.start(listener);
  stream().transportState().setId(STREAM_ID);
  verify(listener, never()).onReady();
  assertFalse(stream.isReady());
  stream().transportState().setHttp2Stream(http2Stream);
  verify(listener).onReady();
  assertTrue(stream.isReady());
}
 
Example 2
Source File: OkHttpClientStreamTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("GuardedBy")
public void start_headerPlaintext() throws IOException {
  Metadata metaData = new Metadata();
  metaData.put(GrpcUtil.USER_AGENT_KEY, "misbehaving-application");
  when(transport.isUsingPlaintext()).thenReturn(true);
  stream = new OkHttpClientStream(methodDescriptor, metaData, frameWriter, transport,
      flowController, lock, MAX_MESSAGE_SIZE, INITIAL_WINDOW_SIZE, "localhost",
      "good-application", StatsTraceContext.NOOP, transportTracer, CallOptions.DEFAULT, false);
  stream.start(new BaseClientStreamListener());
  stream.transportState().start(3);

  verify(mockedFrameWriter)
      .synStream(eq(false), eq(false), eq(3), eq(0), headersCaptor.capture());
  assertThat(headersCaptor.getValue()).containsExactly(
      Headers.HTTP_SCHEME_HEADER,
      Headers.METHOD_HEADER,
      new Header(Header.TARGET_AUTHORITY, "localhost"),
      new Header(Header.TARGET_PATH, "/" + methodDescriptor.getFullMethodName()),
      new Header(GrpcUtil.USER_AGENT_KEY.name(), "good-application"),
      Headers.CONTENT_TYPE_HEADER,
      Headers.TE_HEADER)
      .inOrder();
}
 
Example 3
Source File: DiscardClientInterceptorTest.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    this.descriptor = MethodDescriptor.<String, Integer>newBuilder()
            .setType(MethodDescriptor.MethodType.CLIENT_STREAMING)
            .setFullMethodName("a.service/method")
            .setRequestMarshaller(stringMarshaller)
            .setResponseMarshaller(intMarshaller)
            .build();
    this.callOptions = CallOptions.DEFAULT;
    this.clientCall = new ClientCallRecorder();
    when(channel.newCall(descriptor, callOptions)).thenReturn(clientCall);

    discardEventListener = spy(new LoggingDiscardEventListener<String>(DiscardClientInterceptorTest.class.getName(), 1));
    this.interceptor = new DiscardClientInterceptor(discardEventListener, 1);

    this.call = (DiscardClientInterceptor.DiscardClientCall<String, Integer>) interceptor.interceptCall(descriptor, callOptions, channel);
}
 
Example 4
Source File: NettyClientStreamTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void setHttp2StreamShouldNotifyReady() {
  listener = mock(ClientStreamListener.class);

  stream = new NettyClientStream(new TransportStateImpl(handler, DEFAULT_MAX_MESSAGE_SIZE),
      methodDescriptor,
      new Metadata(),
      channel,
      AsciiString.of("localhost"),
      AsciiString.of("http"),
      AsciiString.of("agent"),
      StatsTraceContext.NOOP,
      transportTracer,
      CallOptions.DEFAULT,
      false);
  stream.start(listener);
  stream().transportState().setId(STREAM_ID);
  verify(listener, never()).onReady();
  assertFalse(stream.isReady());
  stream().transportState().setHttp2Stream(http2Stream);
  verify(listener).onReady();
  assertTrue(stream.isReady());
}
 
Example 5
Source File: OkHttpClientStreamTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void start_headerFieldOrder() {
  Metadata metaData = new Metadata();
  metaData.put(GrpcUtil.USER_AGENT_KEY, "misbehaving-application");
  stream = new OkHttpClientStream(methodDescriptor, metaData, frameWriter, transport,
      flowController, lock, MAX_MESSAGE_SIZE, INITIAL_WINDOW_SIZE, "localhost",
      "good-application", StatsTraceContext.NOOP, transportTracer, CallOptions.DEFAULT);
  stream.start(new BaseClientStreamListener());
  stream.transportState().start(3);

  verify(frameWriter).synStream(eq(false), eq(false), eq(3), eq(0), headersCaptor.capture());
  assertThat(headersCaptor.getValue()).containsExactly(
      Headers.SCHEME_HEADER,
      Headers.METHOD_HEADER,
      new Header(Header.TARGET_AUTHORITY, "localhost"),
      new Header(Header.TARGET_PATH, "/" + methodDescriptor.getFullMethodName()),
      new Header(GrpcUtil.USER_AGENT_KEY.name(), "good-application"),
      Headers.CONTENT_TYPE_HEADER,
      Headers.TE_HEADER)
          .inOrder();
}
 
Example 6
Source File: OkHttpClientStreamTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("GuardedBy")
public void start_headerFieldOrder() throws IOException {
  Metadata metaData = new Metadata();
  metaData.put(GrpcUtil.USER_AGENT_KEY, "misbehaving-application");
  stream = new OkHttpClientStream(methodDescriptor, metaData, frameWriter, transport,
      flowController, lock, MAX_MESSAGE_SIZE, INITIAL_WINDOW_SIZE, "localhost",
      "good-application", StatsTraceContext.NOOP, transportTracer, CallOptions.DEFAULT, false);
  stream.start(new BaseClientStreamListener());
  stream.transportState().start(3);

  verify(mockedFrameWriter)
      .synStream(eq(false), eq(false), eq(3), eq(0), headersCaptor.capture());
  assertThat(headersCaptor.getValue()).containsExactly(
      Headers.HTTPS_SCHEME_HEADER,
      Headers.METHOD_HEADER,
      new Header(Header.TARGET_AUTHORITY, "localhost"),
      new Header(Header.TARGET_PATH, "/" + methodDescriptor.getFullMethodName()),
      new Header(GrpcUtil.USER_AGENT_KEY.name(), "good-application"),
      Headers.CONTENT_TYPE_HEADER,
      Headers.TE_HEADER)
          .inOrder();
}
 
Example 7
Source File: OkHttpClientStreamTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  methodDescriptor = MethodDescriptor.<Void, Void>newBuilder()
      .setType(MethodDescriptor.MethodType.UNARY)
      .setFullMethodName("testService/test")
      .setRequestMarshaller(marshaller)
      .setResponseMarshaller(marshaller)
      .build();

  frameWriter =
      new ExceptionHandlingFrameWriter(transport, mockedFrameWriter);
  stream = new OkHttpClientStream(
      methodDescriptor,
      new Metadata(),
      frameWriter,
      transport,
      flowController,
      lock,
      MAX_MESSAGE_SIZE,
      INITIAL_WINDOW_SIZE,
      "localhost",
      "userAgent",
      StatsTraceContext.NOOP,
      transportTracer,
      CallOptions.DEFAULT,
      false);
}
 
Example 8
Source File: CronetClientStreamTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void alwaysUsePutOption_usesHttpPut() {
  SetStreamFactoryRunnable callback = new SetStreamFactoryRunnable(factory);
  CronetClientStream stream =
      new CronetClientStream(
          "https://www.google.com:443",
          "cronet",
          executor,
          metadata,
          transport,
          callback,
          lock,
          100,
          true /* alwaysUsePut */,
          method,
          StatsTraceContext.NOOP,
          CallOptions.DEFAULT,
          transportTracer,
          true,
          true);
  callback.setStream(stream);
  ExperimentalBidirectionalStream.Builder builder =
      mock(ExperimentalBidirectionalStream.Builder.class);
  when(factory.newBidirectionalStreamBuilder(
          any(String.class), any(BidirectionalStream.Callback.class), any(Executor.class)))
      .thenReturn(builder);
  when(builder.build()).thenReturn(cronetStream);
  stream.start(clientListener);

  verify(builder).setHttpMethod("PUT");
}
 
Example 9
Source File: TripleClientInvoker.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * set some custom info
 * @param sofaRequest
 * @param timeout
 * @return
 */
protected CallOptions buildCustomCallOptions(SofaRequest sofaRequest, int timeout) {
    CallOptions tripleCallOptions = CallOptions.DEFAULT;
    final String target = consumerConfig.getParameter("interworking.target");
    if (StringUtils.isNotBlank(target)) {
        tripleCallOptions = tripleCallOptions.withAuthority(target);
    }
    return tripleCallOptions;
}
 
Example 10
Source File: OkHttpClientStreamTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("GuardedBy")
public void getUnaryRequest() throws IOException {
  MethodDescriptor<?, ?> getMethod = MethodDescriptor.<Void, Void>newBuilder()
      .setType(MethodDescriptor.MethodType.UNARY)
      .setFullMethodName("service/method")
      .setIdempotent(true)
      .setSafe(true)
      .setRequestMarshaller(marshaller)
      .setResponseMarshaller(marshaller)
      .build();
  stream = new OkHttpClientStream(getMethod, new Metadata(), frameWriter, transport,
      flowController, lock, MAX_MESSAGE_SIZE, INITIAL_WINDOW_SIZE, "localhost",
      "good-application", StatsTraceContext.NOOP, transportTracer, CallOptions.DEFAULT, true);
  stream.start(new BaseClientStreamListener());

  // GET streams send headers after halfClose is called.
  verify(mockedFrameWriter, times(0)).synStream(
      eq(false), eq(false), eq(3), eq(0), headersCaptor.capture());
  verify(transport, times(0)).streamReadyToStart(isA(OkHttpClientStream.class));

  byte[] msg = "request".getBytes(Charset.forName("UTF-8"));
  stream.writeMessage(new ByteArrayInputStream(msg));
  stream.halfClose();
  verify(transport).streamReadyToStart(eq(stream));
  stream.transportState().start(3);

  verify(mockedFrameWriter)
      .synStream(eq(true), eq(false), eq(3), eq(0), headersCaptor.capture());
  assertThat(headersCaptor.getValue()).contains(Headers.METHOD_GET_HEADER);
  assertThat(headersCaptor.getValue()).contains(
      new Header(Header.TARGET_PATH, "/" + getMethod.getFullMethodName() + "?"
          + BaseEncoding.base64().encode(msg)));
}
 
Example 11
Source File: AbstractClientStreamTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
public BaseAbstractClientStream(
    WritableBufferAllocator allocator,
    TransportState state,
    Sink sink,
    StatsTraceContext statsTraceCtx,
    TransportTracer transportTracer,
    boolean useGet) {
  super(allocator, statsTraceCtx, transportTracer, new Metadata(), CallOptions.DEFAULT, useGet);
  this.state = state;
  this.sink = sink;
}
 
Example 12
Source File: DefaultCallOptionsClientInterceptorTest.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void simpleValueTransfers() {
    CallOptions baseOptions = CallOptions.DEFAULT;
    CallOptions defaultOptions = CallOptions.DEFAULT.withAuthority("FOO");

    DefaultCallOptionsClientInterceptor interceptor = new DefaultCallOptionsClientInterceptor(defaultOptions);

    CallOptions patchedOptions = interceptor.patchOptions(baseOptions);

    assertThat(patchedOptions.getAuthority()).isEqualTo("FOO");
}
 
Example 13
Source File: CronetClientStreamTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void idempotentMethod_usesHttpPut() {
  SetStreamFactoryRunnable callback = new SetStreamFactoryRunnable(factory);
  MethodDescriptor<?, ?> idempotentMethod = method.toBuilder().setIdempotent(true).build();
  CronetClientStream stream =
      new CronetClientStream(
          "https://www.google.com:443",
          "cronet",
          executor,
          metadata,
          transport,
          callback,
          lock,
          100,
          false /* alwaysUsePut */,
          idempotentMethod,
          StatsTraceContext.NOOP,
          CallOptions.DEFAULT,
          transportTracer,
          true,
          true);
  callback.setStream(stream);
  ExperimentalBidirectionalStream.Builder builder =
      mock(ExperimentalBidirectionalStream.Builder.class);
  when(factory.newBidirectionalStreamBuilder(
          any(String.class), any(BidirectionalStream.Callback.class), any(Executor.class)))
      .thenReturn(builder);
  when(builder.build()).thenReturn(cronetStream);
  stream.start(clientListener);

  verify(builder).setHttpMethod("PUT");
}
 
Example 14
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private void subtestFailRpcFromBalancer(boolean waitForReady, boolean drop, boolean shouldFail) {
  createChannel();

  // This call will be buffered by the channel, thus involve delayed transport
  CallOptions callOptions = CallOptions.DEFAULT;
  if (waitForReady) {
    callOptions = callOptions.withWaitForReady();
  } else {
    callOptions = callOptions.withoutWaitForReady();
  }
  ClientCall<String, Integer> call1 = channel.newCall(method, callOptions);
  call1.start(mockCallListener, new Metadata());

  SubchannelPicker picker = mock(SubchannelPicker.class);
  Status status = Status.UNAVAILABLE.withDescription("for test");

  when(picker.pickSubchannel(any(PickSubchannelArgs.class)))
      .thenReturn(drop ? PickResult.withDrop(status) : PickResult.withError(status));
  updateBalancingStateSafely(helper, READY, picker);

  executor.runDueTasks();
  if (shouldFail) {
    verify(mockCallListener).onClose(same(status), any(Metadata.class));
  } else {
    verifyZeroInteractions(mockCallListener);
  }

  // This call doesn't involve delayed transport
  ClientCall<String, Integer> call2 = channel.newCall(method, callOptions);
  call2.start(mockCallListener2, new Metadata());

  executor.runDueTasks();
  if (shouldFail) {
    verify(mockCallListener2).onClose(same(status), any(Metadata.class));
  } else {
    verifyZeroInteractions(mockCallListener2);
  }
}
 
Example 15
Source File: CronetClientStreamTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);

  SetStreamFactoryRunnable callback = new SetStreamFactoryRunnable(factory);
  clientStream =
      new CronetClientStream(
          "https://www.google.com:443",
          "cronet",
          executor,
          metadata,
          transport,
          callback,
          lock,
          100,
          false /* alwaysUsePut */,
          method,
          StatsTraceContext.NOOP,
          CallOptions.DEFAULT,
          transportTracer,
          false,
          false);
  callback.setStream(clientStream);
  when(factory.newBidirectionalStreamBuilder(
          any(String.class), any(BidirectionalStream.Callback.class), any(Executor.class)))
      .thenReturn(builder);
  when(builder.build()).thenReturn(cronetStream);
  clientStream.start(clientListener);
}
 
Example 16
Source File: RPCTracingHelpersTest.java    From pravega with Apache License 2.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testInterceptors() {
    String requestDescriptor = "createStream-myScope-myStream";
    long requestId = 1234L;
    ClientInterceptor clientInterceptor = RPCTracingHelpers.getClientInterceptor();
    RequestTracker requestTracker = new RequestTracker(true);

    // Mocking RPC elements.
    MethodDescriptor.Marshaller<Object> mockMarshaller = Mockito.mock(MethodDescriptor.Marshaller.class);
    ClientCall.Listener<Object> listener = Mockito.mock(ClientCall.Listener.class);
    ServerCall serverCall = Mockito.mock(ServerCall.class);
    ServerCallHandler serverCallHandler = Mockito.mock(ServerCallHandler.class);
    ManagedChannel channel = NettyChannelBuilder.forTarget("localhost").build();
    MethodDescriptor method = MethodDescriptor.newBuilder()
                                              .setFullMethodName("createStream")
                                              .setType(MethodDescriptor.MethodType.UNARY)
                                              .setRequestMarshaller(mockMarshaller)
                                              .setResponseMarshaller(mockMarshaller)
                                              .build();
    Mockito.when(serverCall.getMethodDescriptor()).thenReturn(method);

    // Actual elements to work with.
    CallOptions callOptions = CallOptions.DEFAULT;
    Metadata headers = new Metadata();

    // Test that headers do not contain tracing-related key/values, as call options are not set.
    clientInterceptor.interceptCall(method, callOptions, channel).start(listener, headers);
    assertFalse(headers.containsKey(RPCTracingHelpers.DESCRIPTOR_HEADER));
    assertFalse(headers.containsKey(RPCTracingHelpers.ID_HEADER));

    // Check that the server interceptor handles clients not sending tracing headers and that the cache remains clean.
    ServerInterceptor serverInterceptor = RPCTracingHelpers.getServerInterceptor(requestTracker);
    serverInterceptor.interceptCall(serverCall, headers, serverCallHandler);
    assertEquals(0, requestTracker.getNumDescriptors());

    // Add call options and check that headers are correctly set.
    callOptions = callOptions.withOption(RPCTracingHelpers.REQUEST_DESCRIPTOR_CALL_OPTION, requestDescriptor)
                             .withOption(RPCTracingHelpers.REQUEST_ID_CALL_OPTION, String.valueOf(requestId));
    clientInterceptor.interceptCall(method, callOptions, channel).start(listener, headers);
    assertEquals(requestDescriptor, headers.get(RPCTracingHelpers.DESCRIPTOR_HEADER));
    assertEquals(requestId, Long.parseLong(headers.get(RPCTracingHelpers.ID_HEADER)));

    // Test that the server interceptor correctly sets these headers in the cache for further tracking.
    serverInterceptor.interceptCall(serverCall, headers, serverCallHandler);
    assertEquals(1, requestTracker.getNumDescriptors());
    assertEquals(requestId, requestTracker.getRequestIdFor(requestDescriptor));
}
 
Example 17
Source File: CronetClientStreamTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Test
public void reservedHeadersStripped() {
  String userAgent = "cronet";
  Metadata headers = new Metadata();
  Metadata.Key<String> userKey = Metadata.Key.of("user-key", Metadata.ASCII_STRING_MARSHALLER);
  headers.put(GrpcUtil.CONTENT_TYPE_KEY, "to-be-removed");
  headers.put(GrpcUtil.USER_AGENT_KEY, "to-be-removed");
  headers.put(GrpcUtil.TE_HEADER, "to-be-removed");
  headers.put(userKey, "user-value");

  SetStreamFactoryRunnable callback = new SetStreamFactoryRunnable(factory);
  CronetClientStream stream =
      new CronetClientStream(
          "https://www.google.com:443",
          userAgent,
          executor,
          headers,
          transport,
          callback,
          lock,
          100,
          false /* alwaysUsePut */,
          method,
          StatsTraceContext.NOOP,
          CallOptions.DEFAULT,
          transportTracer);
  callback.setStream(stream);
  ExperimentalBidirectionalStream.Builder builder =
      mock(ExperimentalBidirectionalStream.Builder.class);
  when(factory.newBidirectionalStreamBuilder(
          any(String.class), any(BidirectionalStream.Callback.class), any(Executor.class)))
      .thenReturn(builder);
  when(builder.build()).thenReturn(cronetStream);
  stream.start(clientListener);

  verify(builder, times(4)).addHeader(any(String.class), any(String.class));
  verify(builder).addHeader(GrpcUtil.USER_AGENT_KEY.name(), userAgent);
  verify(builder).addHeader(GrpcUtil.CONTENT_TYPE_KEY.name(), GrpcUtil.CONTENT_TYPE_GRPC);
  verify(builder).addHeader("te", GrpcUtil.TE_TRAILERS);
  verify(builder).addHeader(userKey.name(), "user-value");
}
 
Example 18
Source File: ClientCacheExampleActivity.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@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().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);
  }
}
 
Example 19
Source File: CronetClientStreamTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void getUnaryRequest() {
  StreamBuilderFactory getFactory = mock(StreamBuilderFactory.class);
  MethodDescriptor<?, ?> getMethod =
      MethodDescriptor.<Void, Void>newBuilder()
          .setType(MethodDescriptor.MethodType.UNARY)
          .setFullMethodName("/service/method")
          .setIdempotent(true)
          .setSafe(true)
          .setRequestMarshaller(marshaller)
          .setResponseMarshaller(marshaller)
          .build();
  SetStreamFactoryRunnable callback = new SetStreamFactoryRunnable(getFactory);
  CronetClientStream stream =
      new CronetClientStream(
          "https://www.google.com/service/method",
          "cronet",
          executor,
          metadata,
          transport,
          callback,
          lock,
          100,
          false /* alwaysUsePut */,
          getMethod,
          StatsTraceContext.NOOP,
          CallOptions.DEFAULT,
          transportTracer,
          true,
          false);
  callback.setStream(stream);
  ExperimentalBidirectionalStream.Builder getBuilder =
      mock(ExperimentalBidirectionalStream.Builder.class);
  when(getFactory.newBidirectionalStreamBuilder(
          any(String.class), any(BidirectionalStream.Callback.class), any(Executor.class)))
      .thenReturn(getBuilder);
  when(getBuilder.build()).thenReturn(cronetStream);
  stream.start(clientListener);

  // We will not create BidirectionalStream until we have the full request.
  verify(getFactory, times(0))
      .newBidirectionalStreamBuilder(
          isA(String.class), isA(BidirectionalStream.Callback.class), isA(Executor.class));

  byte[] msg = "request".getBytes(Charset.forName("UTF-8"));
  stream.writeMessage(new ByteArrayInputStream(msg));
  // We still haven't built the stream or sent anything.
  verify(cronetStream, times(0)).write(isA(ByteBuffer.class), isA(Boolean.class));
  verify(getFactory, times(0))
      .newBidirectionalStreamBuilder(
          isA(String.class), isA(BidirectionalStream.Callback.class), isA(Executor.class));

  // halfClose will trigger sending.
  stream.halfClose();

  // Stream should be built with request payload in the header.
  ArgumentCaptor<String> urlCaptor = ArgumentCaptor.forClass(String.class);
  verify(getFactory)
      .newBidirectionalStreamBuilder(
          urlCaptor.capture(), isA(BidirectionalStream.Callback.class), isA(Executor.class));
  verify(getBuilder).setHttpMethod("GET");
  assertEquals(
      "https://www.google.com/service/method?" + BaseEncoding.base64().encode(msg),
      urlCaptor.getValue());
}
 
Example 20
Source File: AbstractStub.java    From grpc-java with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor for use by subclasses, with the default {@code CallOptions}.
 *
 * @since 1.0.0
 * @param channel the channel that this stub will use to do communications
 */
protected AbstractStub(Channel channel) {
  this(channel, CallOptions.DEFAULT);
}