Java Code Examples for io.grpc.inprocess.InProcessServerBuilder#generateName()

The following examples show how to use io.grpc.inprocess.InProcessServerBuilder#generateName() . 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: HelloWorldClientTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  // Generate a unique in-process server name.
  String serverName = InProcessServerBuilder.generateName();

  // Create a server, add service, start, and register for automatic graceful shutdown.
  grpcCleanup.register(InProcessServerBuilder
      .forName(serverName).directExecutor().addService(serviceImpl).build().start());

  // Create a client channel and register for automatic graceful shutdown.
  ManagedChannel channel = grpcCleanup.register(
      InProcessChannelBuilder.forName(serverName).directExecutor().build());

  // Create a HelloWorldClient using the in-process channel;
  client = new HelloWorldClient(channel);
}
 
Example 2
Source File: GrpcServerTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
private void createServer(CommandDispatcher dispatcher) throws Exception {
  serverDirectory = fileSystem.getPath("/bazel_server_directory");
  serverDirectory.createDirectoryAndParents();
  FileSystemUtils.writeContentAsLatin1(serverDirectory.getChild("server.pid.txt"), "12345");
  serverImpl =
      new GrpcServerImpl(
          dispatcher,
          new JavaClock(),
          /* port= */ -1,
          REQUEST_COOKIE,
          "response-cookie",
          serverDirectory,
          1000,
          false,
          false);
  String uniqueName = InProcessServerBuilder.generateName();
  server =
      InProcessServerBuilder.forName(uniqueName)
          .directExecutor()
          .addService(serverImpl)
          .build()
          .start();
  channel = InProcessChannelBuilder.forName(uniqueName).directExecutor().build();
}
 
Example 3
Source File: HeaderServerInterceptorTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  GreeterImplBase greeterImplBase =
      new GreeterImplBase() {
        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
          responseObserver.onNext(HelloReply.getDefaultInstance());
          responseObserver.onCompleted();
        }
      };
  // Generate a unique in-process server name.
  String serverName = InProcessServerBuilder.generateName();
  // Create a server, add service, start, and register for automatic graceful shutdown.
  grpcCleanup.register(InProcessServerBuilder.forName(serverName).directExecutor()
      .addService(ServerInterceptors.intercept(greeterImplBase, new HeaderServerInterceptor()))
      .build().start());
  // Create a client channel and register for automatic graceful shutdown.
  channel =
      grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build());
}
 
Example 4
Source File: HeaderServerInterceptorTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  GreeterImplBase greeterImplBase =
      new GreeterImplBase() {
        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
          responseObserver.onNext(HelloReply.getDefaultInstance());
          responseObserver.onCompleted();
        }
      };
  // Generate a unique in-process server name.
  String serverName = InProcessServerBuilder.generateName();
  // Create a server, add service, start, and register for automatic graceful shutdown.
  grpcCleanup.register(InProcessServerBuilder.forName(serverName).directExecutor()
      .addService(ServerInterceptors.intercept(greeterImplBase, new HeaderServerInterceptor()))
      .build().start());
  // Create a client channel and register for automatic graceful shutdown.
  channel =
      grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build());
}
 
Example 5
Source File: GrpcRetryInterceptorTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoRetryOnOk() throws IOException {
  String uniqueName = InProcessServerBuilder.generateName();
  ExecutionImpl service = new ExecutionImpl(Status.OK, 0);
  InProcessServerBuilder.forName(uniqueName).addService(service).build().start();
  CallCounter beforeRetry = new CallCounter();
  ManagedChannel channel =
      InProcessChannelBuilder.forName(uniqueName)
          .intercept(
              new RetryClientInterceptor(
                  RetryPolicy.builder().setMaxRetries(2).setBeforeRetry(beforeRetry).build()))
          .build();
  ExecutionBlockingStub stub = ExecutionGrpc.newBlockingStub(channel);
  stub.execute(ExecuteRequest.newBuilder().build()).forEachRemaining(resp -> {});

  Assert.assertEquals(1, service.calls);
  Assert.assertEquals(0, beforeRetry.calls);
}
 
Example 6
Source File: HealthServiceImplTest.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Test
public void healthException() throws Exception {
    // Generate a unique in-process server name.
    String serverName = InProcessServerBuilder.generateName();
    HealthCheckAggregator hca = mock(HealthCheckAggregator.class);
    CompletableFuture<HealthCheckStatus> hcsf = mock(CompletableFuture.class);
    when(hcsf.get()).thenThrow(InterruptedException.class);
    when(hca.check()).thenReturn(hcsf);
    HealthServiceImpl healthyService = new HealthServiceImpl(hca);

    addService(serverName, healthyService);
    HealthGrpc.HealthBlockingStub blockingStub = HealthGrpc.newBlockingStub(
            // Create a client channel and register for automatic graceful shutdown.
            grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()));

    thrown.expect(StatusRuntimeException.class);
    thrown.expect(hasProperty("status", is(Status.INTERNAL)));
    blockingStub.check(HealthCheckRequest.newBuilder().build());

}
 
Example 7
Source File: HealthServiceImplTest.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Test
public void healthNotServing() throws Exception {
    // Generate a unique in-process server name.
    String serverName = InProcessServerBuilder.generateName();
    HealthCheckAggregator hca = mock(HealthCheckAggregator.class);
    CompletableFuture<HealthCheckStatus> hcsf = mock(CompletableFuture.class);
    HealthCheckStatus hcs = mock(HealthCheckStatus.class);
    when(hcs.isHealthy()).thenReturn(false);
    when(hcsf.get()).thenReturn(hcs);
    when(hca.check()).thenReturn(hcsf);
    HealthServiceImpl healthyService = new HealthServiceImpl(hca);

    addService(serverName, healthyService);
    HealthGrpc.HealthBlockingStub blockingStub = HealthGrpc.newBlockingStub(
            // Create a client channel and register for automatic graceful shutdown.
            grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()));


    HealthCheckResponse reply = blockingStub.check(HealthCheckRequest.newBuilder().build());

    assertEquals(HealthCheckResponse.ServingStatus.NOT_SERVING, reply.getStatus());
}
 
Example 8
Source File: HelloWorldServerTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * To test the server, make calls with a real stub using the in-process channel, and verify
 * behaviors or state changes from the client side.
 */
@Test
public void greeterImpl_replyMessage() throws Exception {
  // Generate a unique in-process server name.
  String serverName = InProcessServerBuilder.generateName();

  // Create a server, add service, start, and register for automatic graceful shutdown.
  grpcCleanup.register(InProcessServerBuilder
      .forName(serverName).directExecutor().addService(new GreeterImpl()).build().start());

  GreeterGrpc.GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(
      // Create a client channel and register for automatic graceful shutdown.
      grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()));


  HelloReply reply =
      blockingStub.sayHello(HelloRequest.newBuilder().setName( "test name").build());

  assertEquals("Hello test name", reply.getMessage());
}
 
Example 9
Source File: GoogleCloudStorageGrpcWriteChannelTest.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  fakeService = spy(new FakeService());
  String serverName = InProcessServerBuilder.generateName();
  grpcCleanup.register(
      InProcessServerBuilder.forName(serverName)
          .directExecutor()
          .addService(fakeService)
          .build()
          .start());
  stub =
      StorageGrpc.newStub(
          grpcCleanup.register(
              InProcessChannelBuilder.forName(serverName).directExecutor().build()));
}
 
Example 10
Source File: ShadowE2ETest.java    From metastore with Apache License 2.0 5 votes vote down vote up
private RegistryGrpc.RegistryBlockingStub getSchemaRegistryStub(MetaStore metaStore)
    throws IOException {
  String serverName = InProcessServerBuilder.generateName();
  grpcCleanup.register(
      InProcessServerBuilder.forName(serverName)
          .directExecutor()
          .addService(new RegistryService(metaStore))
          .build()
          .start());
  return RegistryGrpc.newBlockingStub(
      grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()));
}
 
Example 11
Source File: HeaderClientInterceptorTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void clientHeaderDeliveredToServer() throws Exception {
  // Generate a unique in-process server name.
  String serverName = InProcessServerBuilder.generateName();
  // Create a server, add service, start, and register for automatic graceful shutdown.
  grpcCleanup.register(InProcessServerBuilder.forName(serverName).directExecutor()
      .addService(ServerInterceptors.intercept(new GreeterImplBase() {}, mockServerInterceptor))
      .build().start());
  // Create a client channel and register for automatic graceful shutdown.
  ManagedChannel channel = grpcCleanup.register(
      InProcessChannelBuilder.forName(serverName).directExecutor().build());
  GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(
      ClientInterceptors.intercept(channel, 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(
      ArgumentMatchers.<ServerCall<HelloRequest, HelloReply>>any(),
      metadataCaptor.capture(),
      ArgumentMatchers.<ServerCallHandler<HelloRequest, HelloReply>>any());
  assertEquals(
      "customRequestValue",
      metadataCaptor.getValue().get(HeaderClientInterceptor.CUSTOM_HEADER_KEY));
}
 
Example 12
Source File: TestProfiles.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  // start in-memory metrics store
  metricsStore = new LocalMetricsStore();
  metricsStore.start();

  // start in-memory profile store
  profileStore = new LocalProfileStore(TempLegacyKVStoreProviderCreator.create());
  profileStore.start();

  final String serverName = InProcessServerBuilder.generateName();
  profileService =
    new JobTelemetryServiceImpl(metricsStore, profileStore, false, 100);

  grpcCleanupRule.register(InProcessServerBuilder
    .forName(serverName)
    .directExecutor()
    .addService(profileService)
    .build()
    .start());
  server = JobTelemetryServiceGrpc.newBlockingStub(
    grpcCleanupRule.register(
      InProcessChannelBuilder
        .forName(serverName)
        .directExecutor()
        .build()
    ));
  asyncServer = JobTelemetryServiceGrpc.newStub(
    grpcCleanupRule.register(
      InProcessChannelBuilder
        .forName(serverName)
        .directExecutor()
        .build()
    ));
}
 
Example 13
Source File: StubWriteOutputStreamTest.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  String serverName = InProcessServerBuilder.generateName();

  grpcCleanup
      .register(
          InProcessServerBuilder.forName(serverName)
              .directExecutor()
              .addService(serviceImpl)
              .build())
      .start();

  channel =
      grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build());
}
 
Example 14
Source File: ByteStreamHelperTest.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  String serverName = InProcessServerBuilder.generateName();

  grpcCleanup
      .register(
          InProcessServerBuilder.forName(serverName)
              .directExecutor()
              .addService(serviceImpl)
              .build())
      .start();

  channel =
      grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build());
}
 
Example 15
Source File: LogdServerTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  // Generate a unique in-process server name.
  String serverName = InProcessServerBuilder.generateName();

  // Use directExecutor for both InProcessServerBuilder and InProcessChannelBuilder can reduce the
  // usage timeouts and latches in test.
  server = new LogdServer(PORT, InProcessServerBuilder.forName(serverName).directExecutor());
  server.start();
  // Create a client channel and register for automatic graceful shutdown.
  inProcessChannel =
      grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build());
}
 
Example 16
Source File: GrpcRetryInterceptorTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testRetryOnPartialResponse() throws IOException {
  String uniqueName = InProcessServerBuilder.generateName();
  ExecutionImpl service = new ExecutionImpl(Status.UNAVAILABLE, 1);
  InProcessServerBuilder.forName(uniqueName).addService(service).build().start();
  CallCounter beforeRetry = new CallCounter();
  ManagedChannel channel =
      InProcessChannelBuilder.forName(uniqueName)
          .intercept(
              new RetryClientInterceptor(
                  RetryPolicy.builder()
                      .setMaxRetries(2)
                      .setBeforeRetry(beforeRetry)
                      .setRestartAllStreamingCalls(true)
                      .build()))
          .build();
  ExecutionBlockingStub stub = ExecutionGrpc.newBlockingStub(channel);
  try {
    stub.execute(ExecuteRequest.newBuilder().build()).forEachRemaining(resp -> {});
    Assert.fail("Final retry should cause an exception");
  } catch (StatusRuntimeException ex) {
    Assert.assertEquals(Status.Code.UNAVAILABLE, ex.getStatus().getCode());
  }

  Assert.assertEquals(3, service.calls);
  Assert.assertEquals(2, beforeRetry.calls);
}
 
Example 17
Source File: BrokerServerTest.java    From gcp-token-broker with Apache License 2.0 5 votes vote down vote up
private BrokerBlockingStub getStub() {
    String serverName = InProcessServerBuilder.generateName();

    try {
        grpcCleanup.register(InProcessServerBuilder
            .forName(serverName).directExecutor().addService(BrokerServer.getServiceDefinition()).build().start());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return BrokerGrpc.newBlockingStub(
        grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()));
}
 
Example 18
Source File: OcAgentTraceServiceRpcHandlersTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException {
  MockitoAnnotations.initMocks(this);
  Mockito.doReturn(TraceParams.DEFAULT).when(mockTraceConfig).getActiveTraceParams();
  Mockito.doNothing().when(mockTraceConfig).updateActiveTraceParams(any(TraceParams.class));

  traceServiceGrpc = new FakeOcAgentTraceServiceGrpcImpl();
  serverName = InProcessServerBuilder.generateName();
  server =
      InProcessServerBuilder.forName(serverName)
          .directExecutor() // directExecutor is fine for unit tests
          .addService(traceServiceGrpc)
          .build()
          .start();
}
 
Example 19
Source File: RouteGuideServerTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  // Generate a unique in-process server name.
  String serverName = InProcessServerBuilder.generateName();
  features = new ArrayList<>();
  // Use directExecutor for both InProcessServerBuilder and InProcessChannelBuilder can reduce the
  // usage timeouts and latches in test. But we still add timeout and latches where they would be
  // needed if no directExecutor were used, just for demo purpose.
  server = new RouteGuideServer(
      InProcessServerBuilder.forName(serverName).directExecutor(), 0, features);
  server.start();
  // Create a client channel and register for automatic graceful shutdown.
  inProcessChannel = grpcCleanup.register(
      InProcessChannelBuilder.forName(serverName).directExecutor().build());
}
 
Example 20
Source File: XdsNameResolverIntegrationTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws IOException {
  final String serverName = InProcessServerBuilder.generateName();
  AggregatedDiscoveryServiceImplBase serviceImpl = new AggregatedDiscoveryServiceImplBase() {
    @Override
    public StreamObserver<DiscoveryRequest> streamAggregatedResources(
        final StreamObserver<DiscoveryResponse> responseObserver) {
      responseObservers.offer(responseObserver);
      @SuppressWarnings("unchecked")
      StreamObserver<DiscoveryRequest> requestObserver = mock(StreamObserver.class);
      return requestObserver;
    }
  };

  cleanupRule.register(
      InProcessServerBuilder
          .forName(serverName)
          .addService(serviceImpl)
          .directExecutor()
          .build()
          .start());
  final ManagedChannel channel =
      cleanupRule.register(InProcessChannelBuilder.forName(serverName).directExecutor().build());

  channelFactory = new XdsChannelFactory() {
    @Override
    ManagedChannel createChannel(List<ServerInfo> servers) {
      assertThat(Iterables.getOnlyElement(servers).getServerUri()).isEqualTo(serverName);
      return channel;
    }
  };
  Bootstrapper bootstrapper = new Bootstrapper() {
    @Override
    public BootstrapInfo readBootstrap() {
      List<ServerInfo> serverList =
          ImmutableList.of(
              new ServerInfo(serverName,
                  ImmutableList.<ChannelCreds>of()));
      return new BootstrapInfo(serverList, FAKE_BOOTSTRAP_NODE);
    }
  };
  xdsNameResolver =
      new XdsNameResolver(
          AUTHORITY,
          args,
          backoffPolicyProvider,
          fakeClock.getStopwatchSupplier(),
          channelFactory,
          bootstrapper);
  assertThat(responseObservers).isEmpty();
}